'use client';

import { useState } from 'react';
import { createManualSale } from '@/app/admin/accounts/actions';
import Price from './Price';

type ProductOption = {
  id: string;
  name: string;
  basePrice: number; // pence
  colors: string[];
  sizes: string[];
};

type Row = {
  key: number;
  productId: string; // '' = free-text item
  description: string;
  color: string;
  size: string;
  quantity: number;
  unitPriceInput: string; // pounds, as typed — parsed on serialize
};

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

export default function ManualSaleForm({ products }: { products: ProductOption[] }) {
  const [rows, setRows] = useState<Row[]>([
    { key: 1, productId: '', description: '', color: '', size: '', quantity: 1, unitPriceInput: '' },
  ]);
  const [nextKey, setNextKey] = useState(2);

  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) {
      // switched to free text — keep whatever was typed, clear product-specific fields
      updateRow(key, { productId: '', color: '', size: '' });
      return;
    }
    updateRow(key, {
      productId,
      description: product.name,
      color: product.colors[0] ?? '',
      size: product.sizes[0] ?? '',
      unitPriceInput: (product.basePrice / 100).toFixed(2),
    });
  };

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

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

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

  // What actually gets submitted — the server recomputes the total itself.
  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,
        unitPrice: pence(r.unitPriceInput),
      })),
  );

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

      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <label htmlFor="soldAt" className="tag-label mb-2 block">
            Date of sale
          </label>
          <input
            id="soldAt"
            name="soldAt"
            type="date"
            defaultValue={todayInput()}
            required
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          />
        </div>
        <div>
          <label htmlFor="buyerName" className="tag-label mb-2 block">
            Buyer name (optional)
          </label>
          <input
            id="buyerName"
            name="buyerName"
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="Cash buyer at a fair? Leave blank"
          />
        </div>
        <div>
          <label htmlFor="buyerEmail" className="tag-label mb-2 block">
            Buyer email (optional)
          </label>
          <input
            id="buyerEmail"
            name="buyerEmail"
            type="email"
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="Links to their account if they have one"
          />
        </div>
      </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="Product"
                  >
                    <option value="">Free-text item…</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 was sold, e.g. Custom commission"
                    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">
                    £
                    <input
                      type="number"
                      step="0.01"
                      min={0}
                      value={row.unitPriceInput}
                      onChange={(e) => updateRow(row.key, { unitPriceInput: e.target.value })}
                      placeholder="0.00"
                      className="w-24 border border-line bg-paper px-2 py-2 text-sm"
                      aria-label="Unit price in pounds"
                    />
                  </label>
                  <span className="ml-auto font-mono text-sm">
                    <Price cents={row.quantity * pence(row.unitPriceInput)} />
                  </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>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <label htmlFor="paymentMethod" className="tag-label mb-2 block">
            Paid by
          </label>
          <select
            id="paymentMethod"
            name="paymentMethod"
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
          >
            <option value="CASH">Cash</option>
            <option value="BANK_TRANSFER">Bank transfer</option>
          </select>
        </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. Spring fair, collected in person"
          />
        </div>
      </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 sale
        </button>
      </div>
    </form>
  );
}
