"use client";

import { useState } from "react";

import { Minus, Plus, Trash2, UtensilsCrossed } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { useT } from "@/lib/i18n";
import { useLanguage } from "@/lib/language-context";
import type { Order, OrderItem } from "@/lib/order/types";
import { ItemCodeInput } from "./item-code-input";
import { SectionHeader } from "./section-header";

interface ItemsSectionProps {
  order: Order;
  readOnly?: boolean;
  /** Called with the full updated items array when a new item is added */
  onAddItem?: (item: OrderItem) => void;
  /** Called with the updated items array when qty/notes change */
  onUpdateItem?: (updatedItems: OrderItem[]) => void;
}

export function ItemsSection({ order, readOnly = false, onAddItem, onUpdateItem }: ItemsSectionProps) {
  const [adding, setAdding] = useState(false);
  const t = useT();

  const requestedTime = order.requestedAt
    ? new Date(order.requestedAt).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })
    : null;

  const handleAdd = (item: OrderItem) => {
    onAddItem?.(item);
    // Keep the input open so staff can keep adding
  };

  return (
    <Collapsible defaultOpen>
      <CollapsibleTrigger className="w-full">
          <SectionHeader
          icon={UtensilsCrossed}
          label={`${t.sec_items} (${order.items.length})`}
          badge={
            requestedTime ? (
              <span className="ml-2 rounded bg-primary/10 px-2 py-0.5 font-semibold text-[13px] text-primary">
                {requestedTime}
              </span>
            ) : undefined
          }
        />
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="divide-y">
          {order.items.map((item, i) => (
            <ItemRow
              key={`${item.code}-${i}`}
              item={item}
              readOnly={readOnly}
              onQtyChange={onUpdateItem ? (delta) => {
                const updated = order.items.map((it, idx) =>
                  idx === i ? { ...it, qty: Math.max(1, it.qty + delta) } : it,
                );
                onUpdateItem(updated);
              } : undefined}
              onNotesChange={onUpdateItem ? (notes) => {
                const updated = order.items.map((it, idx) =>
                  idx === i ? { ...it, notes } : it,
                );
                onUpdateItem(updated);
              } : undefined}
              onRemove={onUpdateItem ? () => {
                const updated = order.items.filter((_, idx) => idx !== i);
                onUpdateItem(updated);
              } : undefined}
            />
          ))}
        </div>

        {!readOnly && (
          <div className="px-3 py-2">
            {adding ? (
              <div className="space-y-2">
                <ItemCodeInput
                  onAdd={handleAdd}
                  onDone={() => setAdding(false)}
                  cartSize={order.items.length}
                  autoFocus
                />
              <button
                type="button"
                onClick={() => setAdding(false)}
                className="w-full py-1 text-center text-[11px] text-muted-foreground hover:text-foreground"
              >
                {t.items_done_adding}
              </button>
              </div>
            ) : (
              <button
                type="button"
                onClick={() => setAdding(true)}
                className="flex w-full items-center justify-center gap-1.5 rounded border border-dashed py-1.5 text-center text-muted-foreground text-xs transition-colors hover:border-primary/50 hover:text-primary"
              >
                <Plus className="size-3" /> {t.items_add_more}
              </button>
            )}
          </div>
        )}
      </CollapsibleContent>
    </Collapsible>
  );
}

function ItemRow({
  item,
  readOnly,
  onQtyChange,
  onNotesChange,
  onRemove,
}: {
  item: OrderItem;
  readOnly?: boolean;
  onQtyChange?: (delta: number) => void;
  onNotesChange?: (notes: string) => void;
  onRemove?: () => void;
}) {
  const { lang } = useLanguage();
  const t = useT();
  const [editingNotes, setEditingNotes] = useState(false);
  const [notesDraft, setNotesDraft] = useState(item.notes ?? "");
  const primaryName   = lang === "zh" ? item.chineseName : item.description;
  const secondaryName = lang === "zh" ? item.description : null;

  const canEdit = !readOnly && (onQtyChange || onNotesChange || onRemove);

  return (
    <div className="px-3 py-2">
      <div className="flex items-center gap-2">
        <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">{item.code}</span>
        <span className="flex-1 font-bold text-[13px] leading-tight">{primaryName}</span>

        {canEdit ? (
          <div className="flex items-center gap-0.5">
            <button
              type="button"
              onClick={() => onQtyChange?.(-1)}
              className="flex size-5 items-center justify-center rounded border text-muted-foreground hover:border-primary hover:text-primary"
            >
              <Minus className="size-3" />
            </button>
            <span className="w-6 text-center font-bold text-sm tabular-nums">{item.qty}</span>
            <button
              type="button"
              onClick={() => onQtyChange?.(1)}
              className="flex size-5 items-center justify-center rounded border text-muted-foreground hover:border-primary hover:text-primary"
            >
              <Plus className="size-3" />
            </button>
          </div>
        ) : (
          <span className="font-bold text-base tabular-nums">{item.qty}</span>
        )}

        <span className="w-14 text-right text-[13px] tabular-nums">
          £{(item.unitPrice * item.qty).toFixed(2)}
        </span>

        {canEdit && onRemove && (
          <button
            type="button"
            onClick={onRemove}
            className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-destructive transition-colors"
            title="Remove item"
          >
            <Trash2 className="size-3.5" />
          </button>
        )}
      </div>

      {(secondaryName || item.notes || (canEdit && !editingNotes)) && (
        <div className="pl-12 text-[11px] mt-0.5">
          {secondaryName && <span className="text-muted-foreground">{secondaryName}</span>}
          {!editingNotes ? (
            <div className="flex items-center gap-1">
              {item.notes ? (
                <span className="font-bold text-amber-700 dark:text-amber-400">{item.notes}</span>
              ) : (
                canEdit && <span className="text-muted-foreground/50 italic">{t.items_no_notes}</span>
              )}
              {canEdit && onNotesChange && (
                <button
                  type="button"
                  onClick={() => { setNotesDraft(item.notes ?? ""); setEditingNotes(true); }}
                  className="text-muted-foreground hover:text-primary underline underline-offset-2"
                >
                  {item.notes ? t.items_edit : t.items_add_note}
                </button>
              )}
            </div>
          ) : (
            <div className="flex items-center gap-1 mt-0.5">
              <input
                autoFocus
                value={notesDraft}
                onChange={(e) => setNotesDraft(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") { onNotesChange?.(notesDraft.trim()); setEditingNotes(false); }
                  if (e.key === "Escape") setEditingNotes(false);
                }}
                placeholder="Special request…"
                className="flex-1 rounded border px-1.5 py-0.5 text-[12px] outline-none focus:border-primary"
              />
              <button
                type="button"
                onClick={() => { onNotesChange?.(notesDraft.trim()); setEditingNotes(false); }}
                className="rounded bg-primary px-1.5 py-0.5 text-[11px] font-semibold text-primary-foreground"
              >
                ✓
              </button>
              <button
                type="button"
                onClick={() => setEditingNotes(false)}
                className="text-muted-foreground hover:text-foreground px-0.5"
              >
                ✕
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
