'use client';

import { useState, useRef } from 'react';
import { createPurchase } from '@/app/admin/accounts/purchases/actions';
import Price from './Price';

type ProductOption = {
  id: string;
  name: string;
  colors: string[];
  sizes: string[];
};

type Row = {
  key: number;
  productId: string; // '' = material / other line
  description: string;
  color: string;
  size: string;
  quantity: number;
  unitCostInput: string; // pounds as typed
};

function todayInput() {
  return new Date().toISOString().slice(0, 10);
}

export default function PurchaseForm({ products }: { products: ProductOption[] }) {
  const [rows, setRows] = useState<Row[]>([
    { key: 1, productId: '', description: '', color: '', size: '', quantity: 1, unitCostInput: '' },
  ]);
  const [nextKey, setNextKey] = useState(2);
  const [parsing, setParsing] = useState(false);
  const [parseError, setParseError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const updateRow = (key: number, patch: Partial<Row>) => {
    setRows((prev) => prev.map((r) => (r.key === key ? { ...r, ...patch } : r)));
  };

  const pickProduct = (key: number, productId: string) => {
    const product = products.find((p) => p.id === productId);
    if (!product) {
      updateRow(key, { productId: '', color: '', size: '' });
      return;
    }
    updateRow(key, {
      productId,
      description: product.name,
      color: product.colors[0] ?? '',
      size: product.sizes[0] ?? '',
    });
  };

  const addRow = () => {
    setRows((prev) => [
      ...prev,
      { key: nextKey, productId: '', description: '', color: '', size: '', quantity: 1, unitCostInput: '' },
    ]);
    setNextKey((k) => k + 1);
  };

  const removeRow = (key: number) => {
    setRows((prev) => (prev.length > 1 ? prev.filter((r) => r.key !== key) : prev));
  };

  const parseInvoice = async () => {
    if (!fileInputRef.current?.files?.[0]) {
      setParseError('No file selected');
      return;
    }

    setParsing(true);
    setParseError(null);

    try {
      const formData = new FormData();
      formData.append('invoice', fileInputRef.current.files[0]);

      const res = await fetch('/api/admin/parse-invoice', {
        method: 'POST',
        body: formData,
      });

      const data = await res.json();

      if (!res.ok) {
        setParseError(data.error || 'Failed to parse invoice');
        return;
      }

      if (!data.items || data.items.length === 0) {
        setParseError('No items found in invoice. Please add them manually.');
        return;
      }

      // Convert extracted items to form rows
      const newRows: Row[] = data.items.map((item: any, index: number) => ({
        key: nextKey + index,
        productId: item.productId || '',
        description: item.description,
        color: '',
        size: '',
        quantity: item.quantity,
        unitCostInput: '',
      }));

      setRows(newRows);
      setNextKey(nextKey + newRows.length);
    } catch (err) {
      setParseError(err instanceof Error ? err.message : 'Failed to parse invoice');
    } finally {
      setParsing(false);
    }
  };

  const pence = (input: string) => Math.max(0, Math.round(Number(input || '0') * 100));
  const total = rows.reduce((sum, r) => sum + r.quantity * pence(r.unitCostInput), 0);

  const itemsJson = JSON.stringify(
    rows
      .filter((r) => r.description.trim())
      .map((r) => ({
        productId: r.productId || null,
        description: r.description,
        color: r.productId ? r.color || null : null,
        size: r.productId ? r.size || null : null,
        quantity: r.quantity,
        unitCost: pence(r.unitCostInput),
      })),
  );

  return (
    <form action={createPurchase} className="mt-10 space-y-6" encType="multipart/form-data">
      <input type="hidden" name="items" value={itemsJson} />

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <label htmlFor="supplierName" className="tag-label mb-2 block">
            Supplier
          </label>
          <input
            id="supplierName"
            name="supplierName"
            required
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="e.g. AWD Apparel"
          />
        </div>
        <div>
          <label htmlFor="purchasedAt" className="tag-label mb-2 block">
            Invoice date
          </label>
          <input
            id="purchasedAt"
            name="purchasedAt"
            type="date"
            defaultValue={todayInput()}
            required
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          />
        </div>
      </div>

      <div>
        <label htmlFor="invoice" className="tag-label mb-2 block">
          Invoice file (optional)
        </label>
        <div className="flex gap-2">
          <input
            ref={fileInputRef}
            id="invoice"
            name="invoice"
            type="file"
            accept="application/pdf,image/*"
            className="flex-1 border border-line bg-paper px-3 py-2 text-sm"
          />
          <button
            type="button"
            onClick={parseInvoice}
            disabled={parsing}
            className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper disabled:opacity-50"
          >
            {parsing ? 'Parsing…' : 'Extract items'}
          </button>
        </div>
        <p className="mt-1 text-xs text-muted">
          PDF or photo, up to 8 MB. Click "Extract items" to auto-fill line items from the invoice.
        </p>
        {parseError && (
          <p className="mt-2 border border-splash-pink/40 bg-splash-pink/10 px-3 py-2 text-xs text-splash-pink">
            {parseError}
          </p>
        )}
      </div>

      <div>
        <p className="tag-label mb-2">Items</p>
        <div className="space-y-3">
          {rows.map((row) => {
            const product = products.find((p) => p.id === row.productId);
            return (
              <div key={row.key} className="border border-line bg-surface p-3">
                <div className="grid gap-2 sm:grid-cols-2">
                  <select
                    value={row.productId}
                    onChange={(e) => pickProduct(row.key, e.target.value)}
                    className="border border-line bg-paper px-2 py-2 text-sm"
                    aria-label="Stock for product"
                  >
                    <option value="">Material / other (no stock count)…</option>
                    {products.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.name}
                      </option>
                    ))}
                  </select>
                  <input
                    value={row.description}
                    onChange={(e) => updateRow(row.key, { description: e.target.value })}
                    placeholder="What you bought, e.g. Vinyl rolls"
                    className="border border-line bg-paper px-3 py-2 text-sm"
                    aria-label="Description"
                  />
                </div>

                <div className="mt-2 flex flex-wrap items-center gap-2">
                  {product && product.colors.length > 0 && (
                    <select
                      value={row.color}
                      onChange={(e) => updateRow(row.key, { color: e.target.value })}
                      className="border border-line bg-paper px-2 py-2 text-sm"
                      aria-label="Colour"
                    >
                      {product.colors.map((c) => (
                        <option key={c} value={c}>
                          {c}
                        </option>
                      ))}
                    </select>
                  )}
                  {product && product.sizes.length > 0 && (
                    <select
                      value={row.size}
                      onChange={(e) => updateRow(row.key, { size: e.target.value })}
                      className="border border-line bg-paper px-2 py-2 text-sm"
                      aria-label="Size"
                    >
                      {product.sizes.map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </select>
                  )}
                  <label className="flex items-center gap-1 text-sm text-muted">
                    Qty
                    <input
                      type="number"
                      min={1}
                      value={row.quantity}
                      onChange={(e) => updateRow(row.key, { quantity: Math.max(1, Math.floor(Number(e.target.value) || 1)) })}
                      className="w-16 border border-line bg-paper px-2 py-2 text-sm"
                    />
                  </label>
                  <label className="flex items-center gap-1 text-sm text-muted">
                    £ each
                    <input
                      type="number"
                      step="0.01"
                      min={0}
                      value={row.unitCostInput}
                      onChange={(e) => updateRow(row.key, { unitCostInput: e.target.value })}
                      placeholder="0.00"
                      className="w-24 border border-line bg-paper px-2 py-2 text-sm"
                      aria-label="Unit cost in pounds"
                    />
                  </label>
                  <span className="ml-auto font-mono text-sm">
                    <Price cents={row.quantity * pence(row.unitCostInput)} />
                  </span>
                  {rows.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeRow(row.key)}
                      className="tag-label text-muted hover:text-splash-pink"
                    >
                      Remove
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
        <button
          type="button"
          onClick={addRow}
          className="mt-3 border border-ink px-3 py-1.5 text-xs hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add another item
        </button>
        <p className="mt-2 text-xs text-muted">
          Lines matched to a product add to its stock count. &quot;Material / other&quot; lines are just
          recorded — ink, packaging, anything without a shelf count.
        </p>
      </div>

      <div>
        <label htmlFor="notes" className="tag-label mb-2 block">
          Notes (optional)
        </label>
        <input
          id="notes"
          name="notes"
          className="w-full border border-line bg-paper px-3 py-2 text-sm"
          placeholder="e.g. Restock ahead of Christmas fair"
        />
      </div>

      <div className="flex items-center justify-between border-t border-line pt-4">
        <p className="font-mono text-lg">
          Total <Price cents={total} />
        </p>
        <button type="submit" className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
          Record purchase
        </button>
      </div>
    </form>
  );
}
