'use client';

import { Plus, Trash2 } from 'lucide-react';

export type ProductLookup = { id: number; sku: string; name: string; priceTzs: string; vatEnabled: boolean; stockQty: number };
export type LineItem = { description: string; qty: number; unitPriceTzs: number; vatEnabled: boolean };

/**
 * Shared by the Quote, Order, and manual-Invoice creation forms. Each row
 * can either be picked from the product catalog (autofills description +
 * price + whether it carries VAT) or typed freely — the prototype's real
 * quotes mix real SKUs with free-text lines like "Installation &
 * Commissioning", so this has to support both, not just catalog products.
 */
export default function LineItemBuilder({
  items, onChange, products,
}: { items: LineItem[]; onChange: (items: LineItem[]) => void; products: ProductLookup[] }) {
  function update(i: number, patch: Partial<LineItem>) {
    onChange(items.map((li, idx) => idx === i ? { ...li, ...patch } : li));
  }

  function addBlank() {
    onChange([...items, { description: '', qty: 1, unitPriceTzs: 0, vatEnabled: true }]);
  }

  function addFromProduct(product: ProductLookup) {
    onChange([...items, {
      description: product.name, qty: 1, unitPriceTzs: Number(product.priceTzs), vatEnabled: product.vatEnabled,
    }]);
  }

  function remove(i: number) {
    onChange(items.filter((_, idx) => idx !== i));
  }

  const subtotal = items.reduce((s, li) => s + li.qty * li.unitPriceTzs, 0);
  const vat = items.filter((li) => li.vatEnabled).reduce((s, li) => s + li.qty * li.unitPriceTzs * 0.18, 0);
  const total = subtotal + vat;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <label className="text-xs font-medium text-gray-600">Line items</label>
        <select
          value=""
          onChange={(e) => {
            const product = products.find((p) => p.id === Number(e.target.value));
            if (product) addFromProduct(product);
          }}
          className="text-[11px] border border-brand-border rounded-lg px-2 py-1"
        >
          <option value="">+ Add from catalog…</option>
          {products.map((p) => <option key={p.id} value={p.id}>{p.name} (TZS {Number(p.priceTzs).toLocaleString()})</option>)}
        </select>
      </div>

      <div className="space-y-1.5 max-h-[220px] overflow-y-auto pr-1">
        {items.map((li, i) => (
          <div key={i} className="flex gap-1.5 items-center animate-fadeInUp">
            <input
              placeholder="Description" value={li.description} onChange={(e) => update(i, { description: e.target.value })}
              className="flex-1 border border-brand-border rounded-lg px-2 py-1.5 text-xs min-w-0"
            />
            <input
              type="number" min={1} placeholder="Qty" value={li.qty} onChange={(e) => update(i, { qty: Number(e.target.value) })}
              className="w-14 border border-brand-border rounded-lg px-2 py-1.5 text-xs"
            />
            <input
              type="number" min={0} placeholder="Unit TZS" value={li.unitPriceTzs} onChange={(e) => update(i, { unitPriceTzs: Number(e.target.value) })}
              className="w-24 border border-brand-border rounded-lg px-2 py-1.5 text-xs"
            />
            <label className="flex items-center gap-1 text-[10px] text-gray-500 shrink-0">
              <input type="checkbox" checked={li.vatEnabled} onChange={(e) => update(i, { vatEnabled: e.target.checked })} /> VAT
            </label>
            <button type="button" onClick={() => remove(i)} className="text-brand-red shrink-0 transition-colors hover:text-red-800"><Trash2 size={14} /></button>
          </div>
        ))}
        {items.length === 0 && <p className="text-xs text-gray-400 py-2">No line items yet — add one above.</p>}
      </div>

      <button type="button" onClick={addBlank} className="text-[11px] border border-brand-border rounded-full px-3 py-1 flex items-center gap-1 transition-colors hover:bg-brand-bg">
        <Plus size={12} /> Blank line
      </button>

      <div className="border-t border-brand-border pt-2 text-xs space-y-0.5">
        <div className="flex justify-between text-gray-500"><span>Subtotal</span><span>TZS {subtotal.toLocaleString()}</span></div>
        <div className="flex justify-between text-gray-500"><span>VAT (18%)</span><span>TZS {vat.toLocaleString()}</span></div>
        <div className="flex justify-between font-bold"><span>Total</span><span>TZS {total.toLocaleString()}</span></div>
      </div>
    </div>
  );
}

export function computeTotals(items: LineItem[]) {
  const subtotalTzs = items.reduce((s, li) => s + li.qty * li.unitPriceTzs, 0);
  const vatTzs = items.filter((li) => li.vatEnabled).reduce((s, li) => s + li.qty * li.unitPriceTzs * 0.18, 0);
  const totalTzs = subtotalTzs + vatTzs;
  return { subtotalTzs, vatTzs, totalTzs };
}

export function toProductsJson(items: LineItem[]) {
  return items.map((li) => ({
    description: li.description, qty: li.qty, unitPriceTzs: li.unitPriceTzs, amountTzs: li.qty * li.unitPriceTzs,
  }));
}
