'use client';

import { HelpCircle, Info, Plus, Trash2 } from 'lucide-react';
import type { ReactNode } from 'react';

import { describedBy, FieldError, FormField } from '@/components/forms/form-field';
import { CountryCombobox } from '@/components/shipments/country-combobox';
import { Input } from '@/components/ui/input';
import { Tooltip } from '@/components/ui/tooltip';
import { formatMoney } from '@/lib/money';
import { declaredTotalMinor, emptyItem, type ItemDraft, type ShipmentDraft } from '@/lib/wizard';

const update = (items: ItemDraft[], index: number, patch: Partial<ItemDraft>, onChange: (items: ItemDraft[]) => void): void => {
  onChange(items.map((item, itemIndex) => (itemIndex === index ? { ...item, ...patch } : item)));
};

const HS_HELP = 'Harmonized System code for customs, for example 6109.10. Optional, but speeds up clearance.';

/** Desktop cell: input with an accessible label and an error line beneath. */
function Cell({ id, label, error, children }: { id: string; label: string; error?: string; children: ReactNode }) {
  return (
    <td className="px-1.5 py-2 align-top">
      <label htmlFor={id} className="sr-only">
        {label}
      </label>
      {children}
      {error === undefined ? null : (
        <div className="mt-1">
          <FieldError id={`${id}-error`}>{error}</FieldError>
        </div>
      )}
    </td>
  );
}

export function ItemsTable({
  draft,
  errors,
  currency,
  international,
  onChange,
}: {
  draft: ShipmentDraft;
  errors: Record<string, string>;
  currency: string;
  international: boolean;
  onChange: (items: ItemDraft[]) => void;
}) {
  const items = draft.items;
  const err = (index: number, field: string): string | undefined => errors[`items.${index}.${field}`];
  const aria = (id: string, error: string | undefined) => ({
    'aria-invalid': error !== undefined ? true : undefined,
    'aria-describedby': describedBy(id, undefined, error),
  });

  return (
    <section className="rounded-xl border border-border bg-surface p-5 shadow-xs md:p-6" aria-labelledby="items-title">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h3 id="items-title" className="font-display text-h3 font-bold">
            Items in this shipment
          </h3>
          <p className="mt-0.5 text-small text-muted-foreground">{international ? 'Required for customs.' : 'Optional for domestic shipments.'}</p>
        </div>
      </div>

      {international ? (
        <div className="mt-4 flex items-start gap-3 rounded-lg border border-info/25 bg-info-soft px-4 py-3 text-small" role="note">
          <Info className="mt-0.5 h-4 w-4 shrink-0 text-info" aria-hidden="true" />
          <p>
            <span className="font-semibold">Customs information is required</span>
            <span className="text-muted-foreground"> because the sender and recipient are in different countries. Description, declared value and origin country are mandatory.</span>
          </p>
        </div>
      ) : null}
      {errors.items === undefined ? null : (
        <div className="mt-3">
          <FieldError id="items-error">{errors.items}</FieldError>
        </div>
      )}

      {items.length > 0 ? (
        <>
          {/* Desktop editable table */}
          <div className="-mx-1.5 mt-4 hidden overflow-x-auto md:block">
            <table className="w-full min-w-[860px] text-left text-small">
              <thead>
                <tr className="text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  <th scope="col" className="px-1.5 pb-2 font-semibold">Description</th>
                  <th scope="col" className="w-20 px-1.5 pb-2 font-semibold">Qty</th>
                  <th scope="col" className="w-32 px-1.5 pb-2 font-semibold">Declared value</th>
                  <th scope="col" className="w-16 px-1.5 pb-2 font-semibold">Currency</th>
                  <th scope="col" className="w-32 px-1.5 pb-2 font-semibold">
                    <span className="inline-flex items-center gap-1">
                      HS code
                      <Tooltip label="Customs tariff code (optional)">
                        <button type="button" className="rounded-full text-subtle-foreground hover:text-foreground" aria-label={HS_HELP}>
                          <HelpCircle className="h-3.5 w-3.5" aria-hidden="true" />
                        </button>
                      </Tooltip>
                    </span>
                  </th>
                  <th scope="col" className="w-48 px-1.5 pb-2 font-semibold">Origin country</th>
                  <th scope="col" className="w-28 px-1.5 pb-2 font-semibold">SKU</th>
                  <th scope="col" className="w-10 px-1.5 pb-2">
                    <span className="sr-only">Remove</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {items.map((item, index) => {
                  const ids = {
                    description: `item-${index}-description`,
                    quantity: `item-${index}-quantity`,
                    value: `item-${index}-value`,
                    hs: `item-${index}-hs`,
                    origin: `item-${index}-origin`,
                    sku: `item-${index}-sku`,
                  };
                  return (
                    <tr key={index} className="border-t border-border">
                      <Cell id={ids.description} label={`Item ${index + 1} description`} error={err(index, 'description')}>
                        <Input id={ids.description} value={item.description} onChange={(event) => update(items, index, { description: event.target.value }, onChange)} {...aria(ids.description, err(index, 'description'))} />
                      </Cell>
                      <Cell id={ids.quantity} label={`Item ${index + 1} quantity`} error={err(index, 'quantity')}>
                        <Input id={ids.quantity} inputMode="numeric" className="tabular-nums" value={item.quantity} onChange={(event) => update(items, index, { quantity: event.target.value }, onChange)} {...aria(ids.quantity, err(index, 'quantity'))} />
                      </Cell>
                      <Cell id={ids.value} label={`Item ${index + 1} declared value`} error={err(index, 'declaredValue')}>
                        <Input id={ids.value} inputMode="decimal" className="tabular-nums" value={item.declaredValue} onChange={(event) => update(items, index, { declaredValue: event.target.value }, onChange)} {...aria(ids.value, err(index, 'declaredValue'))} />
                      </Cell>
                      <td className="px-1.5 py-2 align-top">
                        <span className="flex h-11 items-center text-muted-foreground">{item.currency}</span>
                      </td>
                      <Cell id={ids.hs} label={`Item ${index + 1} HS code`}>
                        <Input id={ids.hs} value={item.hsCode} onChange={(event) => update(items, index, { hsCode: event.target.value }, onChange)} />
                      </Cell>
                      <Cell id={ids.origin} label={`Item ${index + 1} origin country`} error={err(index, 'originCountryCode')}>
                        <CountryCombobox
                          id={ids.origin}
                          value={item.originCountryCode}
                          onChange={(originCountryCode) => update(items, index, { originCountryCode }, onChange)}
                          invalid={err(index, 'originCountryCode') !== undefined}
                          describedBy={describedBy(ids.origin, undefined, err(index, 'originCountryCode'))}
                        />
                      </Cell>
                      <Cell id={ids.sku} label={`Item ${index + 1} SKU`}>
                        <Input id={ids.sku} value={item.sku} onChange={(event) => update(items, index, { sku: event.target.value }, onChange)} />
                      </Cell>
                      <td className="px-1.5 py-2 align-top">
                        <button
                          type="button"
                          aria-label={`Remove item ${index + 1}`}
                          onClick={() => onChange(items.filter((_, itemIndex) => itemIndex !== index))}
                          className="grid h-11 w-9 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-danger-soft hover:text-danger"
                        >
                          <Trash2 className="h-4 w-4" aria-hidden="true" />
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Mobile stacked cards */}
          <div className="mt-4 grid gap-3 md:hidden">
            {items.map((item, index) => {
              const prefix = `item-m-${index}`;
              return (
                <div key={index} className="grid gap-3 rounded-lg border border-border p-4">
                  <div className="flex items-center justify-between">
                    <p className="text-small font-semibold">Item {index + 1}</p>
                    <button
                      type="button"
                      aria-label={`Remove item ${index + 1}`}
                      onClick={() => onChange(items.filter((_, itemIndex) => itemIndex !== index))}
                      className="grid h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-danger-soft hover:text-danger"
                    >
                      <Trash2 className="h-4 w-4" aria-hidden="true" />
                    </button>
                  </div>
                  <FormField id={`${prefix}-description`} label="Description" error={err(index, 'description')}>
                    <Input id={`${prefix}-description`} value={item.description} onChange={(event) => update(items, index, { description: event.target.value }, onChange)} {...aria(`${prefix}-description`, err(index, 'description'))} />
                  </FormField>
                  <div className="grid grid-cols-2 gap-3">
                    <FormField id={`${prefix}-quantity`} label="Qty" error={err(index, 'quantity')}>
                      <Input id={`${prefix}-quantity`} inputMode="numeric" value={item.quantity} onChange={(event) => update(items, index, { quantity: event.target.value }, onChange)} {...aria(`${prefix}-quantity`, err(index, 'quantity'))} />
                    </FormField>
                    <FormField id={`${prefix}-value`} label={`Value (${item.currency})`} error={err(index, 'declaredValue')}>
                      <Input id={`${prefix}-value`} inputMode="decimal" value={item.declaredValue} onChange={(event) => update(items, index, { declaredValue: event.target.value }, onChange)} {...aria(`${prefix}-value`, err(index, 'declaredValue'))} />
                    </FormField>
                  </div>
                  <FormField id={`${prefix}-origin`} label="Origin country" error={err(index, 'originCountryCode')}>
                    <CountryCombobox id={`${prefix}-origin`} value={item.originCountryCode} onChange={(originCountryCode) => update(items, index, { originCountryCode }, onChange)} invalid={err(index, 'originCountryCode') !== undefined} />
                  </FormField>
                  <div className="grid grid-cols-2 gap-3">
                    <FormField id={`${prefix}-hs`} label="HS code">
                      <Input id={`${prefix}-hs`} value={item.hsCode} onChange={(event) => update(items, index, { hsCode: event.target.value }, onChange)} />
                    </FormField>
                    <FormField id={`${prefix}-sku`} label="SKU">
                      <Input id={`${prefix}-sku`} value={item.sku} onChange={(event) => update(items, index, { sku: event.target.value }, onChange)} />
                    </FormField>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      ) : (
        <p className="mt-4 rounded-lg border border-dashed border-border px-4 py-6 text-center text-small text-muted-foreground">No items added yet.</p>
      )}

      <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
        <button
          type="button"
          onClick={() => onChange([...items, emptyItem(currency)])}
          className="inline-flex h-9 items-center gap-1.5 rounded-md px-2 text-small font-semibold text-primary transition-colors hover:bg-primary-soft"
        >
          <Plus className="h-4 w-4" aria-hidden="true" />
          Add item
        </button>
        <p className="text-small text-muted-foreground">
          Total declared value <span className="ml-1 font-display text-h3 font-bold tabular-nums text-foreground">{formatMoney(declaredTotalMinor(draft), currency)}</span>
        </p>
      </div>
    </section>
  );
}
