import { useState } from 'react';
import { ChevronDown, ChevronUp } from 'lucide-react';

const MATERIALS = [
  { label: 'PLA', value: 'PLA', price: 19.99 },
  { label: 'PLA Special', value: 'PLA Special', price: 24.99 },
  { label: 'PETG', value: 'PETG', price: 20.99 },
  { label: 'ASA', value: 'ASA', price: 22.99 },
  { label: 'CF', value: 'CF', price: 30.99 },
  { label: 'Specialist Filament', value: 'Specialist Filament', price: 36.99 },
  { label: 'Extreme Cost', value: 'Extreme Cost', price: 150.99 },
];

const PRINTERS = [
  { label: 'Bambu Lab A1', watts: 95 },
  { label: 'Bambu Lab A1 Mini', watts: 70 },
  { label: 'Bambu Lab P1P', watts: 100 },
  { label: 'Bambu Lab P1S', watts: 100 },
  { label: 'Bambu Lab X1C', watts: 110 },
  { label: 'SnapMaker U1', watts: 120 },
  { label: 'Ender 3', watts: 300 },
  { label: 'K1', watts: 350 },
  { label: 'K1 Max', watts: 1000 },
  { label: 'K2 Plus', watts: 160 },
  { label: 'CR10', watts: 375 },
];

const cardStyle = {
  background: '#1a1a2e',
  border: '1px solid rgba(107,47,179,0.4)',
  boxShadow: '0 0 20px rgba(107,47,179,0.15)',
};

const inputClass = `w-full px-3 py-2 text-sm text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 transition-all`;
const inputStyle = { background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)' };

const SectionHeader = ({ emoji, title }) => (
  <div className="flex items-center gap-2 mb-4">
    <div className="w-1 h-5 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
    <span className="text-sm font-bold text-white">{emoji} {title}</span>
  </div>
);

const Field = ({ label, children }) => (
  <div>
    <label className="block text-xs font-medium mb-1.5" style={{ color: 'rgba(200,180,255,0.7)' }}>{label}</label>
    {children}
  </div>
);

export default function PrintDetailsPanel({ data, onChange }) {
  const [businessOpen, setBusinessOpen] = useState(false);

  const set = (key, val) => onChange(prev => ({ ...prev, [key]: val }));

  const handleMaterialChange = (val) => {
    const mat = MATERIALS.find(m => m.value === val);
    onChange(prev => ({ ...prev, materialType: val, costPerKg: mat?.price ?? prev.costPerKg }));
  };

  const handlePrinterChange = (val) => {
    const p = PRINTERS.find(p => p.label === val);
    onChange(prev => ({ ...prev, printerModel: val, printerWatts: p?.watts ?? prev.printerWatts }));
  };

  const updatePackaging = (i, field, val) => {
    const next = data.packaging.map((r, idx) => idx === i ? { ...r, [field]: val } : r);
    set('packaging', next);
  };

  return (
    <div className="space-y-4">
      {/* Print Job */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <SectionHeader emoji="🖨️" title="Print Job" />
        <div className="space-y-3">
          <Field label="STL / Product Name">
            <input type="text" value={data.productName} onChange={e => set('productName', e.target.value)}
              placeholder="e.g. Dragon Mask v2" className={inputClass} style={inputStyle} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Print Time (hrs)">
              <input type="number" step="0.1" value={data.printTime} onChange={e => set('printTime', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
            <Field label="Units to Produce">
              <input type="number" min="1" value={data.units} onChange={e => set('units', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Total Weight (g)">
              <input type="number" step="0.1" value={data.totalWeight} onChange={e => set('totalWeight', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
            <Field label="Purge Waste (g)">
              <input type="number" step="0.1" value={data.purgeWaste} onChange={e => set('purgeWaste', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
          </div>
        </div>
      </div>

      {/* Material */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <SectionHeader emoji="🧵" title="Material" />
        <div className="space-y-3">
          <Field label="Material Type">
            <select value={data.materialType} onChange={e => handleMaterialChange(e.target.value)}
              className={inputClass} style={inputStyle}>
              {MATERIALS.map(m => (
                <option key={m.value} value={m.value}>{m.label} (${m.price}/kg)</option>
              ))}
            </select>
          </Field>
          <Field label="Cost per kg ($)">
            <input type="number" step="0.01" value={data.costPerKg} onChange={e => set('costPerKg', Number(e.target.value))}
              className={inputClass} style={inputStyle} />
          </Field>
        </div>
      </div>

      {/* Power */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <SectionHeader emoji="⚡" title="Power & Machine" />
        <div className="space-y-3">
          <Field label="Printer">
            <select value={data.printerModel} onChange={e => handlePrinterChange(e.target.value)}
              className={inputClass} style={inputStyle}>
              {PRINTERS.map(p => (
                <option key={p.label} value={p.label}>{p.label} ({p.watts}W)</option>
              ))}
            </select>
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Average printing power (watts)">
              <input type="number" value={data.printerWatts} onChange={e => set('printerWatts', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
            <Field label="Cost per kWh ($)">
              <input type="number" step="0.0001" value={data.costPerKwh} onChange={e => set('costPerKwh', Number(e.target.value))}
                className={inputClass} style={inputStyle} />
            </Field>
          </div>
        </div>
      </div>

      {/* Packaging */}
      <div className="rounded-2xl p-5" style={cardStyle}>
        <SectionHeader emoji="📦" title="Packaging" />
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ color: 'rgba(200,180,255,0.5)' }}>
                <th className="text-left text-xs pb-2 font-medium">Name</th>
                <th className="text-left text-xs pb-2 font-medium px-2">Qty</th>
                <th className="text-left text-xs pb-2 font-medium px-2">Unit $</th>
                <th className="text-right text-xs pb-2 font-medium">Total</th>
              </tr>
            </thead>
            <tbody className="space-y-1">
              {data.packaging.map((row, i) => {
                const rowTotal = (Number(row.qty) || 0) * (Number(row.unitPrice) || 0);
                return (
                  <tr key={i}>
                    <td className="pr-2 py-1">
                      <input type="text" value={row.name} onChange={e => updatePackaging(i, 'name', e.target.value)}
                        placeholder="Item…" className="w-full px-2 py-1 text-xs text-white rounded focus:outline-none focus:ring-1 focus:ring-purple-500"
                        style={{ background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.2)' }} />
                    </td>
                    <td className="px-2 py-1">
                      <input type="number" step="0.01" value={row.qty} onChange={e => updatePackaging(i, 'qty', e.target.value)}
                        className="w-16 px-2 py-1 text-xs text-white rounded focus:outline-none focus:ring-1 focus:ring-purple-500"
                        style={{ background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.2)' }} />
                    </td>
                    <td className="px-2 py-1">
                      <input type="number" step="0.01" value={row.unitPrice} onChange={e => updatePackaging(i, 'unitPrice', e.target.value)}
                        className="w-20 px-2 py-1 text-xs text-white rounded focus:outline-none focus:ring-1 focus:ring-purple-500"
                        style={{ background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.2)' }} />
                    </td>
                    <td className="text-right py-1 text-xs font-mono font-semibold" style={{ color: rowTotal > 0 ? '#a78bfa' : 'rgba(255,255,255,0.3)' }}>
                      ${rowTotal.toFixed(2)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Business Settings (collapsible) */}
      <div className="rounded-2xl overflow-hidden" style={cardStyle}>
        <button
          onClick={() => setBusinessOpen(o => !o)}
          className="w-full px-5 py-4 flex items-center justify-between text-left hover:bg-white/5 transition-colors"
        >
          <div className="flex items-center gap-2">
            <div className="w-1 h-5 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
            <span className="text-sm font-bold text-white">⚙️ Business Settings</span>
          </div>
          {businessOpen ? <ChevronUp size={16} style={{ color: '#a78bfa' }} /> : <ChevronDown size={16} style={{ color: '#a78bfa' }} />}
        </button>
        {businessOpen && (
          <div className="px-5 pb-5 grid grid-cols-2 gap-3">
            {[
              { label: 'Fixed Monthly Cost ($)', key: 'fixedMonthlyCost', step: 1 },
              { label: 'Units per Month', key: 'unitsPerMonth', step: 1 },
              { label: 'Printer Lifespan (hrs)', key: 'lifespanHours', step: 100 },
              { label: 'Machine Cost ($)', key: 'machineCost', step: 10 },
              { label: 'Failure Rate (0–1)', key: 'failureRate', step: 0.01 },
              { label: 'Markup Multiplier', key: 'markupMultiplier', step: 0.1 },
              { label: 'Tax/GST Reserve (0–1)', key: 'taxRate', step: 0.01 },
              { label: 'CC Fee (0–1)', key: 'ccFee', step: 0.01 },
              { label: 'Advertising Rate (0–1)', key: 'adsCost', step: 0.01 },
            ].map(({ label, key, step }) => (
              <Field key={key} label={label}>
                <input type="number" step={step} value={data[key]}
                  onChange={e => set(key, Number(e.target.value))}
                  className={inputClass} style={inputStyle} />
              </Field>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
