"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

import { CheckCircle2, ChevronRight, Minus, Plus, ShoppingBag, Trash2, X } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { MOCK_MENU } from "@/lib/order/mock-menu";
import { MASTER_ADDRESSES, searchMasterAddresses } from "@/lib/order/master-addresses";
import type { MasterAddress } from "@/lib/order/master-addresses";
import { useOrdersStore } from "@/stores/orders/orders-store";
import type { Order, OrderItem, OrderType } from "@/lib/order/types";

type Step = "phone" | "otp" | "type" | "address" | "items" | "review";

interface CartItem extends OrderItem {
  tempId: string;
}

export default function CustomerOrderPage() {
  const router = useRouter();
  const orders = useOrdersStore((s) => s.orders);
  const [step, setStep] = useState<Step>("phone");

  // Customer info
  const [phone, setPhone] = useState("");
  const [existingCustomer, setExistingCustomer] = useState<{ na: string; mo: string } | null>(null);
  const [orderType, setOrderType] = useState<OrderType>("delivery");

  // Address
  const [addrQuery, setAddrQuery] = useState("");
  const [addrResults, setAddrResults] = useState<MasterAddress[]>([]);
  const [selectedAddress, setSelectedAddress] = useState<MasterAddress | null>(null);

  // Cart
  const [cart, setCart] = useState<CartItem[]>([]);
  const [searchItem, setSearchItem] = useState("");
  // Per-item note editing (code → note text)
  const [itemNoteEdit, setItemNoteEdit] = useState<Record<string, string>>({});
  // Delivery / order note
  const [deliveryNote, setDeliveryNote] = useState("");

  // Placed order
  const [placedOrderId, setPlacedOrderId] = useState<string | null>(null);
  // OTP verification (mock)
  const [mockOtp, setMockOtp] = useState("");
  const [otpInput, setOtpInput] = useState("");
  // Last order for 1-click repeat
  const [lastOrder, setLastOrder] = useState<Order | null>(null);

  // Look up existing customer by phone, then send mock OTP
  const handlePhoneSubmit = () => {
    const norm = phone.replace(/\s/g, "");
    if (norm.length < 10) { toast.error("Enter a valid phone number"); return; }
    const history = orders
      .filter((o) => o.customer.mo === norm || o.customer.mo === `+44${norm.slice(1)}`)
      .sort((a, b) => new Date(b.orderedAt).getTime() - new Date(a.orderedAt).getTime());
    if (history.length > 0) {
      setExistingCustomer({ na: history[0].customer.na, mo: history[0].customer.mo });
      setLastOrder(history[0]);
    }
    const code = String(Math.floor(100000 + Math.random() * 900000));
    setMockOtp(code);
    setOtpInput("");
    setStep("otp");
  };

  const handleOtpVerify = () => {
    if (otpInput.trim() !== mockOtp) { toast.error("Incorrect code — try again"); return; }
    if (existingCustomer) toast.success(`Welcome back, ${existingCustomer.na}!`);
    setStep("type");
  };

  const handleAddrSearch = (q: string) => {
    setAddrQuery(q);
    setAddrResults(q.trim().length >= 2 ? searchMasterAddresses(q) : []);
  };

  const addToCart = (item: (typeof MOCK_MENU)[number]) => {
    setCart((prev) => {
      const existing = prev.find((c) => c.code === item.code);
      if (existing) return prev.map((c) => c.code === item.code ? { ...c, qty: c.qty + 1 } : c);
      return [...prev, { ...item, qty: 1, notes: undefined, tempId: `${item.code}-${Date.now()}` }];
    });
  };
  const removeFromCart = (code: string) => setCart((p) => p.filter((c) => c.code !== code));
  const changeQty = (code: string, delta: number) =>
    setCart((p) => p.map((c) => c.code === code ? { ...c, qty: Math.max(1, c.qty + delta) } : c));
  const saveItemNote = (code: string) =>
    setCart((p) => p.map((c) => c.code === code ? { ...c, notes: itemNoteEdit[code]?.trim() || undefined } : c));

  const subtotal = cart.reduce((acc, i) => acc + i.unitPrice * i.qty, 0);
  const deliveryFee = orderType === "delivery" ? (selectedAddress?.miles ?? 0) < 2 ? 2.5 : selectedAddress?.miles ?? 0 < 3 ? 3.5 : 5.0 : 0;
  const total = subtotal + deliveryFee;

  const handlePlaceOrder = () => {
    if (cart.length === 0) { toast.error("Your cart is empty"); return; }
    if (orderType === "delivery" && !selectedAddress) { toast.error("Please select a delivery address"); return; }

    const now = new Date();
    const yy = String(now.getFullYear()).slice(2);
    const mm = String(now.getMonth() + 1).padStart(2, "0");
    const dd = String(now.getDate()).padStart(2, "0");
    const existing = orders.filter((o) => o.id.startsWith(`${yy}${mm}${dd}`)).length;
    const newId = `${yy}${mm}${dd}-${String(existing + 1).padStart(3, "0")}O`;

    const mo = phone.replace(/\s/g, "");
    const newOrder: Order = {
      id: newId,
      type: orderType,
      suffix: "O",
      stage: "confirmed",
      orderedAt: now.toISOString(),
      requestedAt: new Date(now.getTime() + 45 * 60_000).toISOString(),
      customer: {
        na: existingCustomer?.na ?? "Online Customer",
        mo: existingCustomer?.mo ?? mo,
        lifetimeSpend: 0,
        lifetimeOrders: 0,
      },
      customerMessage: deliveryNote.trim() || undefined,
      address: orderType === "delivery" && selectedAddress ? selectedAddress : undefined,
      items: cart.map(({ tempId: _t, ...rest }) => rest),
      charges: {
        subtotal: Math.round(subtotal * 100) / 100,
        deliveryFee: orderType === "delivery" ? deliveryFee : undefined,
        total: Math.round(total * 100) / 100,
        paymentMethod: "paylink",
        paymentStatus: "unpaid",
      },
      events: [{ at: now.toISOString(), actor: "customer:online", type: "order_created", label: "Order placed online" }],
    };

    useOrdersStore.getState().updateItems; // ensure store is hydrated
    // Add order directly
    useOrdersStore.setState((s) => {
      const updatedOrders = [...s.orders, newOrder];
      try { localStorage.setItem("orderos_orders", JSON.stringify(updatedOrders)); } catch {}
      return { orders: updatedOrders };
    });

    setPlacedOrderId(newId);
    setStep("review");
    toast.success(`Order ${newId} placed!`);
  };

  const filteredMenu = MOCK_MENU.filter((m) =>
    !searchItem || m.description.toLowerCase().includes(searchItem.toLowerCase()) || m.code.toLowerCase().includes(searchItem.toLowerCase()),
  );

  if (step === "review" && placedOrderId) {
    return (
      <div className="min-h-screen bg-zinc-950 flex items-center justify-center p-4">
        <div className="w-full max-w-sm rounded-2xl bg-white p-8 text-center shadow-xl">
          <CheckCircle2 className="mx-auto size-16 text-green-500 mb-4" />
          <h1 className="text-2xl font-bold mb-1">Order Placed!</h1>
          <p className="text-muted-foreground mb-2">Your order ID is</p>
          <p className="font-mono font-bold text-primary text-xl mb-4">{placedOrderId}</p>
          <p className="text-sm text-muted-foreground mb-6">
            Estimated ready in 45 minutes. You can track your order using the link below.
          </p>
          <div className="flex flex-col gap-2">
            <Link
              href={`/track/${placedOrderId}`}
              className="w-full rounded-lg bg-primary py-2.5 text-center font-semibold text-primary-foreground hover:bg-primary/90"
            >
              Track My Order
            </Link>
            <button
              type="button"
              onClick={() => { setStep("phone"); setCart([]); setPhone(""); setPlacedOrderId(null); setExistingCustomer(null); setSelectedAddress(null); setDeliveryNote(""); setItemNoteEdit({}); setLastOrder(null); setMockOtp(""); setOtpInput(""); }}
              className="w-full rounded-lg border py-2.5 text-sm text-muted-foreground hover:text-foreground"
            >
              Place Another Order
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-zinc-950 flex items-center justify-center p-4">
      <div className="w-full max-w-md rounded-2xl bg-white shadow-2xl overflow-hidden">
        {/* Header */}
        <div className="bg-primary px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="font-bold text-primary-foreground text-xl">Place Order</h1>
              <p className="text-primary-foreground/70 text-xs">Haka Bracknell · Online Ordering</p>
            </div>
            <ShoppingBag className="size-6 text-primary-foreground/60" />
          </div>
          {/* Step indicator */}
          <div className="mt-3 flex items-center gap-1">
            {(["phone", "type", "address", "items"] as const).map((s) => {
              const ORDER: Step[] = ["phone", "otp", "type", "address", "items", "review"];
              const cur = ORDER.indexOf(step);
              const bar = ORDER.indexOf(s);
              const active = step === s || (s === "phone" && step === "otp");
              return (
                <div key={s} className={`h-1 flex-1 rounded-full transition-colors ${
                  active ? "bg-white" : cur > bar ? "bg-white/60" : "bg-white/20"
                }`} />
              );
            })}
          </div>
        </div>

        <div className="p-6">
          {/* Step 1: Phone */}
          {step === "phone" && (
            <div className="space-y-4">
              <div>
                <h2 className="font-semibold text-lg mb-1">Your phone number</h2>
                <p className="text-muted-foreground text-sm mb-4">We use this to recognise returning customers and send order updates.</p>
                <Input
                  type="tel"
                  placeholder="+44 7xxx xxxxxx"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && handlePhoneSubmit()}
                  className="text-base"
                  autoFocus
                />
              </div>
              <Button className="w-full" onClick={handlePhoneSubmit}>
                Continue <ChevronRight className="ml-1 size-4" />
              </Button>
              <p className="text-center text-xs text-muted-foreground">No account needed · Phone number only</p>
            </div>
          )}

          {/* Step OTP: Verify phone number */}
          {step === "otp" && (
            <div className="space-y-4">
              <div>
                <h2 className="font-semibold text-lg mb-1">Verify your number</h2>
                <p className="text-muted-foreground text-sm mb-3">
                  A 6-digit code was sent to <span className="font-mono font-medium">{phone}</span>
                </p>
                <div className="mb-4 rounded-lg bg-sky-50 border border-sky-200 px-4 py-3 text-center">
                  <p className="text-[11px] text-sky-600 mb-1">📱 Demo — code sent to your phone:</p>
                  <p className="font-mono font-bold text-2xl text-sky-800 tracking-[0.3em]">{mockOtp}</p>
                </div>
                <Input
                  type="tel"
                  inputMode="numeric"
                  placeholder="Enter 6-digit code"
                  value={otpInput}
                  onChange={(e) => setOtpInput(e.target.value.replace(/\D/g, "").slice(0, 6))}
                  onKeyDown={(e) => e.key === "Enter" && otpInput.length === 6 && handleOtpVerify()}
                  className="text-center text-xl tracking-widest font-mono"
                  autoFocus
                />
              </div>
              <Button className="w-full" onClick={handleOtpVerify} disabled={otpInput.length !== 6}>
                Verify <ChevronRight className="ml-1 size-4" />
              </Button>
              <button
                type="button"
                onClick={() => { setStep("phone"); setOtpInput(""); }}
                className="w-full text-center text-sm text-muted-foreground hover:text-foreground"
              >
                ← Change phone number
              </button>
            </div>
          )}

          {/* Step 2: Order type */}
          {step === "type" && (
            <div className="space-y-4">
              {existingCustomer && (
                <div className="rounded-lg bg-green-50 border border-green-200 px-4 py-2.5 text-sm text-green-800">
                  Welcome back, <strong>{existingCustomer.na}</strong>!
                </div>
              )}
              {existingCustomer && lastOrder && (
                <div className="rounded-lg border border-amber-200 bg-amber-50 p-3">
                  <p className="text-xs font-semibold text-amber-800 mb-2">Your last order:</p>
                  <div className="space-y-0.5 mb-2">
                    {lastOrder.items.slice(0, 4).map((item) => (
                      <p key={item.code} className="text-[12px] text-amber-900">
                        {item.description} ×{item.qty}
                      </p>
                    ))}
                    {lastOrder.items.length > 4 && (
                      <p className="text-[11px] text-muted-foreground">+{lastOrder.items.length - 4} more items</p>
                    )}
                  </div>
                  <p className="text-[11px] text-muted-foreground mb-2">
                    £{lastOrder.charges.total.toFixed(2)} · {lastOrder.type}
                  </p>
                  <Button
                    size="sm"
                    className="w-full"
                    variant="outline"
                    onClick={() => {
                      setCart(lastOrder.items.map((item) => ({ ...item, tempId: `${item.code}-repeat` })));
                      setOrderType(lastOrder.type);
                      if (lastOrder.address) {
                        setSelectedAddress(lastOrder.address as unknown as MasterAddress);
                        setAddrQuery(lastOrder.address.ad);
                      }
                      setStep("items");
                    }}
                  >
                    Repeat this order →
                  </Button>
                </div>
              )}
              <div>
                <h2 className="font-semibold text-lg mb-3">How would you like your order?</h2>
                <div className="grid grid-cols-2 gap-3">
                  {(["delivery", "collection"] as OrderType[]).map((t) => (
                    <button
                      key={t}
                      type="button"
                      onClick={() => setOrderType(t)}
                      className={`rounded-xl border-2 p-4 text-center capitalize font-semibold transition-colors ${
                        orderType === t ? "border-primary bg-primary/5 text-primary" : "border-border text-muted-foreground"
                      }`}
                    >
                      {t === "delivery" ? "🚚 Delivery" : "🏪 Collection"}
                    </button>
                  ))}
                </div>
              </div>
              <Button className="w-full" onClick={() => setStep(orderType === "delivery" ? "address" : "items")}>
                Continue <ChevronRight className="ml-1 size-4" />
              </Button>
            </div>
          )}

          {/* Step 3: Address (delivery only) */}
          {step === "address" && (
            <div className="space-y-4">
              <div>
                <h2 className="font-semibold text-lg mb-1">Delivery address</h2>
                <p className="text-muted-foreground text-sm mb-3">Type your postcode or address fragment</p>
                <Input
                  placeholder="e.g. RG12 8AP or Pigeon Grove"
                  value={addrQuery}
                  onChange={(e) => handleAddrSearch(e.target.value)}
                  autoFocus
                />
                {addrResults.length > 0 && (
                  <div className="mt-2 rounded-lg border shadow-sm bg-white max-h-52 overflow-y-auto">
                    {addrResults.map((r) => (
                      <button
                        key={r.id}
                        type="button"
                        onClick={() => { setSelectedAddress(r); setAddrQuery(r.ad); setAddrResults([]); }}
                        className="flex w-full flex-col gap-0.5 border-b px-3 py-2.5 text-left last:border-0 hover:bg-muted/40"
                      >
                        <span className="text-[13px] font-medium">{r.ad}</span>
                        {r.miles !== undefined && (
                          <span className="text-[11px] text-muted-foreground">{r.miles} mi · est. delivery £{r.miles < 2 ? "2.50" : r.miles < 3 ? "3.50" : "5.00"}</span>
                        )}
                      </button>
                    ))}
                  </div>
                )}
                {selectedAddress && (
                  <div className="mt-2 rounded-lg bg-primary/5 border border-primary/20 px-3 py-2 text-sm">
                    <p className="font-medium">{selectedAddress.ad}</p>
                    <p className="text-muted-foreground text-xs">{selectedAddress.miles ?? "?"} mi · Delivery fee: £{(selectedAddress.miles ?? 0) < 2 ? "2.50" : (selectedAddress.miles ?? 0) < 3 ? "3.50" : "5.00"}</p>
                  </div>
                )}
              </div>
              <Button className="w-full" onClick={() => { if (!selectedAddress) { toast.error("Please select an address from the list"); return; } setStep("items"); }}>
                Continue <ChevronRight className="ml-1 size-4" />
              </Button>
            </div>
          )}

          {/* Step 4: Items */}
          {step === "items" && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <h2 className="font-semibold text-lg">Choose items</h2>
                {cart.length > 0 && (
                  <span className="rounded-full bg-primary px-2 py-0.5 text-[11px] font-bold text-primary-foreground">
                    {cart.reduce((a, c) => a + c.qty, 0)} in cart
                  </span>
                )}
              </div>
              <Input
                placeholder="Search by name or code…"
                value={searchItem}
                onChange={(e) => setSearchItem(e.target.value)}
                className="text-sm"
              />
              <div className="max-h-56 space-y-1 overflow-y-auto pr-1">
                {filteredMenu.map((item) => {
                  const inCart = cart.find((c) => c.code === item.code);
                  const noteKey = item.code;
                  const isEditingNote = noteKey in itemNoteEdit;
                  return (
                    <div key={item.code} className="rounded-lg border overflow-hidden">
                      <div className="flex items-center gap-2 px-3 py-2">
                        <span className="w-8 shrink-0 font-mono text-[10px] text-muted-foreground">{item.code}</span>
                        <div className="flex-1 min-w-0">
                          <p className="text-[13px] font-medium truncate">{item.description}</p>
                          <p className="text-[11px] text-muted-foreground">£{item.unitPrice.toFixed(2)}</p>
                        </div>
                        {inCart ? (
                          <div className="flex items-center gap-1">
                            <button type="button" onClick={() => changeQty(item.code, -1)} className="rounded p-0.5 hover:bg-muted"><Minus className="size-3" /></button>
                            <span className="w-5 text-center text-sm font-bold">{inCart.qty}</span>
                            <button type="button" onClick={() => changeQty(item.code, 1)} className="rounded p-0.5 hover:bg-muted"><Plus className="size-3" /></button>
                            <button
                              type="button"
                              onClick={() => setItemNoteEdit((p) => isEditingNote ? (({ [noteKey]: _, ...rest }) => rest)(p) : { ...p, [noteKey]: inCart.notes ?? "" })}
                              className={`rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors ${inCart.notes ? "bg-amber-100 text-amber-700" : "bg-muted text-muted-foreground hover:text-foreground"}`}
                              title="Add special request"
                            >
                              {inCart.notes ? "note ✓" : "+ note"}
                            </button>
                            <button type="button" onClick={() => { removeFromCart(item.code); setItemNoteEdit((p) => (({ [noteKey]: _, ...rest }) => rest)(p)); }} className="ml-0.5 text-destructive/60 hover:text-destructive"><Trash2 className="size-3" /></button>
                          </div>
                        ) : (
                          <button type="button" onClick={() => addToCart(item)} className="rounded-lg bg-primary/10 px-2 py-1 text-[11px] font-semibold text-primary hover:bg-primary/20">
                            Add
                          </button>
                        )}
                      </div>
                      {/* Inline note input */}
                      {isEditingNote && (
                        <div className="border-t bg-amber-50 px-3 py-2 flex gap-2">
                          <input
                            type="text"
                            autoFocus
                            placeholder="Special request (e.g. no onion, mild)…"
                            value={itemNoteEdit[noteKey] ?? ""}
                            onChange={(e) => setItemNoteEdit((p) => ({ ...p, [noteKey]: e.target.value }))}
                            onKeyDown={(e) => { if (e.key === "Enter") { saveItemNote(noteKey); setItemNoteEdit((p) => (({ [noteKey]: _, ...rest }) => rest)(p)); } if (e.key === "Escape") setItemNoteEdit((p) => (({ [noteKey]: _, ...rest }) => rest)(p)); }}
                            className="flex-1 bg-transparent text-[12px] outline-none placeholder:text-muted-foreground/60"
                          />
                          <button type="button" onClick={() => { saveItemNote(noteKey); setItemNoteEdit((p) => (({ [noteKey]: _, ...rest }) => rest)(p)); }} className="text-[11px] font-semibold text-primary hover:underline">Save</button>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Delivery note */}
              <div>
                <label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Delivery note / special instruction (optional)</label>
                <textarea
                  className="mt-1 w-full rounded-lg border px-3 py-2 text-[13px] resize-none outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                  rows={2}
                  placeholder="e.g. Leave at door, ring bell, no contact delivery…"
                  value={deliveryNote}
                  onChange={(e) => setDeliveryNote(e.target.value)}
                />
              </div>

              {/* Cart summary */}
              {cart.length > 0 && (
                <div className="rounded-lg border bg-muted/20 px-3 py-2 text-sm space-y-1">
                  {cart.map((c) => (
                    <div key={c.code} className="flex justify-between text-[12px]">
                      <span className="text-muted-foreground">{c.description} ×{c.qty}{c.notes ? <span className="ml-1 text-amber-600 italic">({c.notes})</span> : null}</span>
                      <span>£{(c.unitPrice * c.qty).toFixed(2)}</span>
                    </div>
                  ))}
                  <div className="border-t pt-1 space-y-0.5">
                    {deliveryFee > 0 && <div className="flex justify-between text-[12px] text-muted-foreground"><span>Delivery</span><span>£{deliveryFee.toFixed(2)}</span></div>}
                    <div className="flex justify-between font-bold"><span>Total</span><span>£{total.toFixed(2)}</span></div>
                  </div>
                </div>
              )}

              <Button className="w-full" onClick={handlePlaceOrder} disabled={cart.length === 0}>
                Place Order · £{total.toFixed(2)}
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
