"use client";

import { Check, Link2, Search, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { FilterSelect } from "@/components/app/filters";
import { cn } from "@/lib/utils";
import { linkTypeLabel } from "./mail-shared";
import { useLinkRecordPicker } from "./useMailForms";

// Record types a conversation can link to (GET /api/search types; mail_links linkable aliases).
const TYPE_OPTIONS = [
  { value: "purchase_order", label: "Purchase orders" },
  { value: "inquiry", label: "Inquiries" },
  { value: "style", label: "Styles" },
  { value: "quote", label: "Quotes" },
  { value: "cost_sheet", label: "Cost sheets" },
  { value: "shipment", label: "Shipments" },
  { value: "inspection", label: "Inspections" },
  { value: "invoice", label: "Invoices" },
  { value: "letter_of_credit", label: "L/Cs" },
  { value: "buyer", label: "Buyers" },
  { value: "factory", label: "Factories" },
];

/**
 * "Link to record": search by code or name, pick one or more records, link them to the conversation.
 * <LinkRecordDialog thread={thread} link={(links) => actions.linkRecords(thread.id, links)} onClose={…} />
 */
export function LinkRecordDialog({ thread, link, onClose }) {
  const picker = useLinkRecordPicker({ existing: thread.links || [], link, onDone: onClose });
  const term = picker.query.trim();

  return <Dialog open onOpenChange={(open) => { if (!open && !picker.isSaving) onClose(); }}>
    <DialogContent className="flex max-h-[calc(100dvh-2rem)] flex-col gap-4 sm:max-w-xl">
      <DialogHeader>
        <DialogTitle>Link to record</DialogTitle>
        <DialogDescription>The conversation then shows in the Emails section of each record you pick. Search by code (PO-2026…, SHP-…) or name.</DialogDescription>
      </DialogHeader>
      <form onSubmit={picker.submit} className="flex min-h-0 flex-col gap-3">
        <div className="flex flex-wrap items-center gap-2">
          <FilterSelect label="Type" value={picker.type} onChange={picker.setType} options={TYPE_OPTIONS} allLabel="All records" className="h-9" />
        </div>
        <Command shouldFilter={false} className="min-h-0 rounded-lg border">
          <CommandInput placeholder="PO number, style, shipment, buyer…" value={picker.query} onValueChange={picker.setQuery} autoFocus />
          <CommandList className="max-h-72">
            {term.length < 2 && <p className="px-3 py-6 text-center text-sm text-muted-foreground"><Search className="mx-auto mb-2 size-4" />Type at least 2 characters to search.</p>}
            {term.length >= 2 && picker.lookup.isSearching && <div className="grid gap-2 p-2" role="status" aria-label="Searching records">
              {Array.from({ length: 3 }).map((_, index) => <div key={index} className="flex items-center gap-2"><Skeleton className="size-4 rounded" /><div className="grid flex-1 gap-1"><Skeleton className="h-4 w-1/2" /><Skeleton className="h-3 w-3/4" /></div></div>)}
            </div>}
            {term.length >= 2 && !picker.lookup.isSearching && picker.lookup.error && <p className="px-3 py-4 text-sm text-destructive">Search is unavailable right now. Try again in a moment.</p>}
            {term.length >= 2 && !picker.lookup.isSearching && !picker.lookup.error && <CommandEmpty>No records match “{term}”.</CommandEmpty>}
            {picker.lookup.items.length > 0 && <CommandGroup heading="Records">
              {picker.lookup.items.map((record) => {
                const linked = picker.isLinked(record);
                const selected = picker.isSelected(record);
                return <CommandItem key={`${record.type}:${record.code}`} value={`${record.type}:${record.code}`} disabled={linked} onSelect={() => picker.toggle(record)} className="items-start">
                  <Check className={cn("mt-0.5", selected ? "opacity-100" : "opacity-0")} />
                  <span className="grid min-w-0 flex-1">
                    <span className="truncate"><span className="font-medium">{record.code}</span>{record.title && <span className="text-muted-foreground"> · {record.title}</span>}</span>
                    <span className="truncate text-xs text-muted-foreground">{linkTypeLabel(record.type)}{record.subtitle ? ` · ${record.subtitle}` : ""}{linked ? " · Already linked" : ""}</span>
                  </span>
                </CommandItem>;
              })}
            </CommandGroup>}
          </CommandList>
        </Command>
        {picker.selected.length > 0 && <div className="flex flex-wrap items-center gap-1.5" aria-label="Records to link">
          {picker.selected.map((record) => <Badge key={`${record.type}:${record.code}`} variant="secondary" className="h-6 gap-1 rounded-md pr-0.5 font-normal">
            <Link2 aria-hidden="true" />{record.code}
            <button type="button" className="rounded-sm p-0.5 hover:bg-foreground/10" aria-label={`Remove ${record.code}`} onClick={() => picker.toggle(record)}><X className="size-3" /></button>
          </Badge>)}
        </div>}
        {picker.error && <Alert variant="destructive"><AlertDescription>{picker.error}</AlertDescription></Alert>}
        <DialogFooter>
          <Button type="button" variant="outline" onClick={onClose} disabled={picker.isSaving}>Cancel</Button>
          <Button type="submit" disabled={picker.isSaving}>{picker.isSaving ? <Spinner /> : <Link2 />} {picker.selected.length > 1 ? `Link ${picker.selected.length} records` : "Link record"}</Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>;
}
