'use client';

import { useMemo, useState } from 'react';
import { useFormState, useFormStatus } from 'react-dom';
import { submitBulkInquiry, type BulkInquiryFormState } from '@/app/bulk-orders/actions';
import { formatPrice } from '@/lib/site-settings';
import type { ApiSiteSettings } from '@/lib/backend-api';
import type { Product } from '@/lib/types';

const initialState: BulkInquiryFormState = undefined;
const DEFAULT_QTY = 50;

type Row = { key: number; productId: number | ''; quantity: string; specs: string };

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary w-full disabled:opacity-60">
      {pending ? 'Sending…' : 'Request Quote'}
    </button>
  );
}

const inputClass = 'mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500';

export function BulkOrderForm({
  products = [],
  currency,
  preselectedProductId,
}: {
  products?: Product[];
  currency?: ApiSiteSettings['currency'];
  preselectedProductId?: number;
}) {
  const [state, formAction] = useFormState(submitBulkInquiry, initialState);
  const errors = state?.errors ?? {};
  const values = state?.values ?? {};

  const [rows, setRows] = useState<Row[]>(() =>
    preselectedProductId ? [{ key: 1, productId: preselectedProductId, quantity: String(DEFAULT_QTY), specs: '' }] : []
  );
  const [nextKey, setNextKey] = useState(2);
  const byId = useMemo(() => new Map(products.map((p) => [p.id, p])), [products]);

  const chosen = new Set(rows.map((r) => r.productId).filter(Boolean));
  const itemsJson = JSON.stringify(
    rows
      .filter((r) => r.productId !== '')
      .map((r) => ({
        product_id: Number(r.productId),
        quantity: Math.max(1, Math.floor(Number(r.quantity) || 0)),
        requested_specifications: r.specs.trim() || undefined,
      }))
  );

  function update(key: number, patch: Partial<Row>) {
    setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r)));
  }
  function addRow() {
    setRows((rs) => [...rs, { key: nextKey, productId: '', quantity: String(DEFAULT_QTY), specs: '' }]);
    setNextKey((k) => k + 1);
  }
  function removeRow(key: number) {
    setRows((rs) => rs.filter((r) => r.key !== key));
  }

  if (state?.success) {
    return (
      <div className="rounded-md border border-green-200 bg-green-50 px-4 py-4 text-sm text-green-700">
        Thanks — your bulk order request has been sent. Our team will follow up by email shortly.
      </div>
    );
  }

  return (
    <form action={formAction} className="space-y-4">
      {Object.keys(errors).length > 0 && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          <ul className="list-inside list-disc">
            {Object.values(errors).flat().map((error) => (
              <li key={error}>{error}</li>
            ))}
          </ul>
        </div>
      )}

      {/* Product picker — only products enabled for bulk orders */}
      <fieldset>
        <legend className="block text-sm font-semibold text-navy-800">Products</legend>
        {products.length === 0 ? (
          <p className="mt-1.5 text-xs text-navy-500">
            No products are listed for bulk orders right now — describe what you need in Order Details below.
          </p>
        ) : (
          <>
            <p className="mt-1 text-xs text-navy-500">Choose from products available for bulk orders and set the quantity you need.</p>
            <input type="hidden" name="items_json" value={itemsJson} />
            <ul className="mt-3 space-y-3">
              {rows.map((row, index) => {
                const product = row.productId !== '' ? byId.get(row.productId) : undefined;
                return (
                  <li key={row.key} className="rounded-md border border-navy-100 p-3" data-testid="bulk-row">
                    <div className="flex gap-3">
                      {product ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={product.image} alt="" className="h-14 w-14 shrink-0 rounded object-cover" />
                      ) : (
                        <div className="h-14 w-14 shrink-0 rounded bg-beige" aria-hidden="true" />
                      )}
                      <div className="min-w-0 flex-1">
                        <label className="sr-only" htmlFor={`bulk-product-${row.key}`}>Product {index + 1}</label>
                        <select
                          id={`bulk-product-${row.key}`}
                          value={row.productId}
                          onChange={(e) => update(row.key, { productId: e.target.value ? Number(e.target.value) : '' })}
                          className="w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
                        >
                          <option value="">Select a product…</option>
                          {products.map((p) => (
                            <option key={p.id} value={p.id} disabled={chosen.has(p.id) && p.id !== row.productId}>
                              {p.name} — {formatPrice(p.price, currency)}
                            </option>
                          ))}
                        </select>
                        {product && (
                          <p className="mt-1 truncate text-xs text-navy-500">
                            by {product.artisan} · {product.category}
                          </p>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => removeRow(row.key)}
                        aria-label={`Remove product ${index + 1}`}
                        className="h-9 shrink-0 rounded-md px-2 text-navy-400 hover:bg-beige hover:text-red-600"
                      >
                        &times;
                      </button>
                    </div>
                    <div className="mt-3 grid gap-3 sm:grid-cols-[120px_1fr]">
                      <div>
                        <label className="block text-xs font-medium text-navy-600" htmlFor={`bulk-qty-${row.key}`}>Quantity</label>
                        <input
                          id={`bulk-qty-${row.key}`}
                          type="number"
                          min={1}
                          step={1}
                          inputMode="numeric"
                          value={row.quantity}
                          onChange={(e) => update(row.key, { quantity: e.target.value })}
                          className={inputClass}
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-navy-600" htmlFor={`bulk-specs-${row.key}`}>
                          Customisation (optional)
                        </label>
                        <input
                          id={`bulk-specs-${row.key}`}
                          type="text"
                          maxLength={254}
                          value={row.specs}
                          onChange={(e) => update(row.key, { specs: e.target.value })}
                          placeholder="Colour, size, branding…"
                          className={inputClass}
                        />
                      </div>
                    </div>
                  </li>
                );
              })}
            </ul>
            {rows.length < Math.min(products.length, 50) && (
              <button
                type="button"
                onClick={addRow}
                className="mt-3 w-full rounded-md border border-dashed border-navy-200 px-4 py-2 text-sm font-semibold text-navy-800 hover:border-gold-500 hover:bg-gold-50"
              >
                + Add {rows.length === 0 ? 'a product' : 'another product'}
              </button>
            )}
          </>
        )}
      </fieldset>

      <div>
        <label className="block text-sm font-semibold text-navy-800">Company / Organisation</label>
        <input type="text" name="company_name" defaultValue={values.company_name} className={inputClass} />
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <label className="block text-sm font-semibold text-navy-800">Contact Name *</label>
          <input type="text" name="name" defaultValue={values.name} required className={inputClass} />
        </div>
        <div>
          <label className="block text-sm font-semibold text-navy-800">Email *</label>
          <input type="email" name="email" defaultValue={values.email} required className={inputClass} />
        </div>
      </div>
      <div>
        <label className="block text-sm font-semibold text-navy-800">Phone</label>
        <input type="text" name="phone" defaultValue={values.phone} className={inputClass} />
      </div>
      <div>
        <label className="block text-sm font-semibold text-navy-800">Order Details</label>
        <textarea
          name="message"
          rows={4}
          defaultValue={values.message}
          placeholder="Timeline, delivery location, anything not listed above…"
          className={inputClass}
        />
      </div>
      <SubmitButton />
    </form>
  );
}
