import { useState, useMemo } from 'react';
import PrintDetailsPanel from '@/components/calculator/PrintDetailsPanel';
import ResultsPanel from '@/components/calculator/ResultsPanel';
import SavedCalculations from '@/components/calculator/SavedCalculations';

const DEFAULT_PACKAGING = [
  { name: 'Box', qty: 1, unitPrice: 2.40 },
  { name: 'Filler', qty: 0.1, unitPrice: 5.00 },
  { name: 'Bubble Wrap', qty: 0.2, unitPrice: 12.95 },
  { name: 'Sticker', qty: 0.02, unitPrice: 13.99 },
  { name: '', qty: 0, unitPrice: 0 },
  { name: '', qty: 0, unitPrice: 0 },
];

const DEFAULT_STATE = {
  productName: '',
  printTime: 16.2,
  totalWeight: 384.6,
  purgeWaste: 92.32,
  units: 1,
  materialType: 'PLA',
  costPerKg: 19.99,
  printerModel: 'Bambu Lab P1S',
  printerWatts: 100,
  costPerKwh: 0.3896,
  packaging: DEFAULT_PACKAGING,
  fixedMonthlyCost: 60,
  unitsPerMonth: 20,
  lifespanHours: 25000,
  machineCost: 2356,
  failureRate: 0.10,
  markupMultiplier: 2.0,
  taxRate: 0.10,
  ccFee: 0.03,
  adsCost: 0.20,
};

export function calculate(d) {
  const materialCost = ((d.totalWeight + d.purgeWaste) / 1000) * d.costPerKg;
  const powerUsage = (d.printerWatts * d.printTime) / 1000;
  const powerCost = powerUsage * d.costPerKwh;
  const packagingTotal = d.packaging.reduce((s, r) => s + (Number(r.qty) || 0) * (Number(r.unitPrice) || 0), 0);
  const fixedOverhead = d.fixedMonthlyCost / d.unitsPerMonth;
  const amortization = (d.machineCost / d.lifespanHours) * d.printTime;
  const subtotal = materialCost + powerCost + packagingTotal + fixedOverhead + amortization;
  const failureBuffer = d.failureRate * (materialCost + powerCost + amortization);
  const totalCost = subtotal + failureBuffer;
  const unitCost = totalCost / Math.max(1, d.units);

  const consumerPrice = unitCost * d.markupMultiplier;
  const resellerPrice = consumerPrice / 2;

  const grossProfitConsumer = consumerPrice - unitCost;
  const liquidProfitConsumer = grossProfitConsumer
    - consumerPrice * d.taxRate
    - consumerPrice * d.ccFee
    - consumerPrice * d.adsCost;

  const grossProfitReseller = resellerPrice - unitCost;
  const liquidProfitReseller = grossProfitReseller - resellerPrice * d.taxRate;

  const profitMarginConsumer = consumerPrice > 0 ? (grossProfitConsumer / consumerPrice) * 100 : 0;
  const profitMarginReseller = resellerPrice > 0 ? (grossProfitReseller / resellerPrice) * 100 : 0;

  return {
    materialCost, powerCost, packagingTotal, fixedOverhead, amortization,
    failureBuffer, totalCost, unitCost,
    consumerPrice, resellerPrice,
    grossProfitConsumer, liquidProfitConsumer,
    grossProfitReseller, liquidProfitReseller,
    profitMarginConsumer, profitMarginReseller,
  };
}

export default function CostCalculator() {
  const [data, setData] = useState(DEFAULT_STATE);
  const [history, setHistory] = useState([]);
  const results = useMemo(() => calculate(data), [data]);

  const handleSave = () => {
    setHistory(prev => [{
      id: Date.now(),
      savedAt: new Date(),
      inputs: { ...data },
      results: { ...results },
    }, ...prev]);
  };

  const handleLoad = (entry) => {
    setData(entry.inputs);
  };

  const handleDelete = (id) => {
    setHistory(prev => prev.filter(e => e.id !== id));
  };

  return (
    <div className="min-h-screen p-4 md:p-6" style={{ background: '#0d0d1a' }}>
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <h1 className="text-2xl md:text-3xl font-bold text-white tracking-tight">🧮 Cost Calculator</h1>
          <p className="text-sm mt-1" style={{ color: 'rgba(200,180,255,0.6)' }}>
            Professional pricing tool — results update live as you type
          </p>
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
          <PrintDetailsPanel data={data} onChange={setData} />
          <ResultsPanel results={results} data={data} onSave={handleSave} />
        </div>

        {history.length > 0 && (
          <div className="mt-6">
            <SavedCalculations history={history} onLoad={handleLoad} onDelete={handleDelete} />
          </div>
        )}
      </div>
    </div>
  );
}
