"use client";

import { useRef, useState } from "react";

import { BookmarkPlus, Check, MapPin, Search, X } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { useT } from "@/lib/i18n";
import { type MasterAddress, getRuntimeAddresses, saveMasterAddress, searchMasterAddresses } from "@/lib/order/master-addresses";
import type { Address } from "@/lib/order/types";
import { SectionHeader } from "./section-header";

interface AddressSectionProps {
  address: Address;
  /** When provided, shows the sb: search field and calls this on selection */
  onAddressSelect?: (addr: MasterAddress) => void;
}

export function AddressSection({ address, onAddressSelect }: AddressSectionProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [results, setResults] = useState<MasterAddress[]>([]);
  const [savedToBook, setSavedToBook] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  // Check if this address is already in the master DB
  const isInMasterDB = address.ad
    ? getRuntimeAddresses().some((a) => a.ad.toLowerCase() === address.ad.toLowerCase())
    : true; // no address = nothing to save

  const [pendingAddr, setPendingAddr] = useState<MasterAddress | null>(null);
  const t = useT();

  const handleSearch = (q: string) => {
    setSearchQuery(q);
    setResults(q.trim().length >= 2 ? searchMasterAddresses(q) : []);
  };

  const handleSelect = (addr: MasterAddress) => {
    if ((addr.linkedCustomers?.length ?? 0) > 1) {
      // Multiple customers — force selection first
      setPendingAddr(addr);
      setSearchQuery("");
      setResults([]);
      return;
    }
    onAddressSelect?.(addr);
    setSearchQuery("");
    setResults([]);
  };

  const handleCustomerPick = (addr: MasterAddress, customer: { na: string; mo: string }) => {
    // Pass address + override linked customer to parent
    onAddressSelect?.({ ...addr, linkedCustomers: [customer] });
    setPendingAddr(null);
  };

  return (
    <Collapsible defaultOpen>
      <CollapsibleTrigger className="w-full">
        <SectionHeader icon={MapPin} label={t.sec_address} />
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="space-y-1 px-3 py-2 text-sm">

          {/* sb: search box — visible when editing is enabled */}
          {onAddressSelect && (
            <div className="mb-2 space-y-1">
              <div className="flex items-center gap-1.5 rounded border border-primary/30 bg-primary/5 px-2 py-1">
                <span className="w-8 shrink-0 font-mono text-[11px] text-muted-foreground">sb:</span>
                <Search className="size-3.5 shrink-0 text-muted-foreground" />
                <input
                  ref={inputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => handleSearch(e.target.value)}
                  placeholder="Type postcode fragment + name…"
                  className="flex-1 bg-transparent text-[12px] outline-none placeholder:text-muted-foreground/60"
                />
                {searchQuery && (
                  <button type="button" onClick={() => handleSearch("")}>
                    <X className="size-3.5 text-muted-foreground hover:text-foreground" />
                  </button>
                )}
              </div>
              {results.length > 0 && (
                <div className="rounded border bg-card shadow-sm">
                  {results.map((r) => (
                    <button
                      key={r.id}
                      type="button"
                      onClick={() => handleSelect(r)}
                      className="flex w-full flex-col gap-0.5 border-b px-3 py-2 text-left last:border-0 hover:bg-muted/50"
                    >
                      <span className="font-mono text-[10px] text-primary">{r.sb}</span>
                      <span className="text-[12px] font-medium leading-tight">{r.ad}</span>
                      {r.linkedCustomers && r.linkedCustomers.length > 0 && (
                        <span className="text-[11px] text-muted-foreground">
                          {r.linkedCustomers.map((c) => c.na).join(", ")}
                        </span>
                      )}
                      {r.miles !== undefined && (
                        <span className="text-[10px] text-muted-foreground">{r.miles} mi</span>
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Multi-customer picker */}
          {pendingAddr && (
            <div className="mb-2 rounded border border-blue-300 bg-blue-50 p-2">
              <p className="mb-1.5 text-[11px] font-semibold text-blue-800">
                {t.addr_multi_select}
              </p>
              <p className="mb-1.5 text-[11px] text-blue-600 truncate">{pendingAddr.ad}</p>
              <div className="space-y-1">
                {pendingAddr.linkedCustomers?.map((c) => (
                  <button
                    key={c.mo}
                    type="button"
                    onClick={() => handleCustomerPick(pendingAddr, c)}
                    className="flex w-full items-center justify-between rounded border bg-white px-2 py-1.5 text-left text-[12px] hover:border-blue-400 hover:bg-blue-50 transition-colors"
                  >
                    <span className="font-semibold">{c.na}</span>
                    <span className="font-mono text-muted-foreground">{c.mo}</span>
                  </button>
                ))}
              </div>
              <button
                type="button"
                onClick={() => setPendingAddr(null)}
                className="mt-1.5 text-[11px] text-muted-foreground hover:text-foreground"
              >
                {t.addr_cancel}
              </button>
            </div>
          )}

          {/* Save to address book prompt */}
          {onAddressSelect && !isInMasterDB && !savedToBook && address.ad && (
            <div className="mb-2 flex items-center justify-between gap-2 rounded border border-amber-300 bg-amber-50 px-2 py-1.5">
              <p className="text-[11px] text-amber-800 flex-1">{t.addr_save_prompt}</p>
              <button
                type="button"
                onClick={() => {
                  saveMasterAddress({
                    id: `ma-${Date.now()}`,
                    ad: address.ad,
                    sb: address.sb,
                    an: address.an,
                    ge: address.ge,
                    miles: address.miles,
                  });
                  setSavedToBook(true);
                }}
                className="flex items-center gap-1 rounded bg-amber-600 px-2 py-0.5 text-[11px] font-semibold text-white hover:bg-amber-700"
              >
                <BookmarkPlus className="size-3" /> {t.addr_save_btn}
              </button>
            </div>
          )}
          {savedToBook && (
            <div className="mb-2 flex items-center gap-1 rounded border border-green-300 bg-green-50 px-2 py-1 text-[11px] text-green-700">
              <Check className="size-3" /> {t.addr_saved}
            </div>
          )}

          {address.sb && <FieldRow label="sb" value={address.sb} valueClassName="font-mono text-primary" />}
          <FieldRow label="ad" value={address.ad} valueClassName="font-medium" />
          {address.an && <FieldRow label="an" value={address.an} />}
          {/* ge: and miles: on one line per wireframe */}
          {address.ge && (
            <div className="flex gap-2">
              <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">ge:</span>
              <span className="flex-1 font-mono text-[13px]">{address.ge}</span>
              {address.miles !== undefined && (
                <span className="text-[13px] text-muted-foreground">miles: {address.miles}</span>
              )}
            </div>
          )}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}

function FieldRow({
  label,
  value,
  mono = false,
  valueClassName = "",
}: {
  label: string;
  value: string;
  mono?: boolean;
  valueClassName?: string;
}) {
  return (
    <div className="flex gap-2">
      <span className="w-10 shrink-0 font-mono text-[11px] text-muted-foreground">{label}:</span>
      <span className={`flex-1 text-[13px] ${mono ? "font-mono" : ""} ${valueClassName}`}>{value}</span>
    </div>
  );
}
