/**
 * Review screen for the paste/upload flow.
 *
 * Shows the result of `resolveIdentifiers()`:
 *  - "matched" rows are summarized at the top (no action needed)
 *  - "ambiguous" rows show a radio-pick of candidates per row
 *  - "unmatched" rows are listed separately so the user knows what was
 *    dropped (no inline rescue — user can re-paste a corrected value)
 *
 * On confirm, the dialog returns the final pid+qty list (matched rows
 * plus user-resolved ambiguous rows). Skipped ambiguous rows are
 * dropped silently.
 */

import { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { CheckCircle2, AlertCircle, HelpCircle } from "lucide-react";
import { cn } from "@/lib/utils";
import type { ResolveResult } from "./types";

interface ReviewMatchesDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  result: ResolveResult | null;
  onConfirm: (resolved: Array<{ pid: number; qty: number }>) => void;
}

export function ReviewMatchesDialog({
  open,
  onOpenChange,
  result,
  onConfirm,
}: ReviewMatchesDialogProps) {
  // Per-ambiguous-row selected pid (keyed by row index in result.ambiguous)
  const [picks, setPicks] = useState<Record<number, number | null>>({});

  // Reset picks whenever a new result comes in
  useEffect(() => {
    setPicks({});
  }, [result]);

  if (!result) return null;

  const matchedCount = result.matched.length;
  const ambiguousCount = result.ambiguous.length;
  const unmatchedCount = result.unmatched.length;

  const handleConfirm = () => {
    const out: Array<{ pid: number; qty: number }> = result.matched.map((m) => ({
      pid: m.pid,
      qty: m.qty,
    }));
    result.ambiguous.forEach((row, idx) => {
      const picked = picks[idx];
      if (picked) out.push({ pid: picked, qty: row.qty });
    });
    onConfirm(out);
  };

  // Skip review entirely if there's nothing ambiguous and nothing unmatched —
  // the parent should ideally call onConfirm directly in that case, but we
  // also short-circuit here as a safety net.
  const reviewNeeded = ambiguousCount > 0 || unmatchedCount > 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Review imported rows</DialogTitle>
          <DialogDescription>
            {reviewNeeded
              ? "Resolve ambiguous matches before adding products to your purchase order."
              : "All rows matched successfully."}
          </DialogDescription>
        </DialogHeader>

        {/* Summary cards */}
        <div className="grid grid-cols-3 gap-3 mt-2">
          <div className="border rounded-md p-3 bg-emerald-50 border-emerald-200">
            <div className="flex items-center gap-2 text-emerald-800">
              <CheckCircle2 className="h-4 w-4" />
              <span className="text-xs font-medium">Matched</span>
            </div>
            <div className="text-2xl font-semibold text-emerald-900 mt-1">
              {matchedCount}
            </div>
          </div>
          <div
            className={cn(
              "border rounded-md p-3",
              ambiguousCount > 0
                ? "bg-amber-50 border-amber-200"
                : "bg-muted border-border"
            )}
          >
            <div
              className={cn(
                "flex items-center gap-2",
                ambiguousCount > 0 ? "text-amber-800" : "text-muted-foreground"
              )}
            >
              <HelpCircle className="h-4 w-4" />
              <span className="text-xs font-medium">Ambiguous</span>
            </div>
            <div
              className={cn(
                "text-2xl font-semibold mt-1",
                ambiguousCount > 0 ? "text-amber-900" : "text-muted-foreground"
              )}
            >
              {ambiguousCount}
            </div>
          </div>
          <div
            className={cn(
              "border rounded-md p-3",
              unmatchedCount > 0
                ? "bg-destructive/10 border-destructive/30"
                : "bg-muted border-border"
            )}
          >
            <div
              className={cn(
                "flex items-center gap-2",
                unmatchedCount > 0 ? "text-destructive" : "text-muted-foreground"
              )}
            >
              <AlertCircle className="h-4 w-4" />
              <span className="text-xs font-medium">Unmatched</span>
            </div>
            <div
              className={cn(
                "text-2xl font-semibold mt-1",
                unmatchedCount > 0 ? "text-destructive" : "text-muted-foreground"
              )}
            >
              {unmatchedCount}
            </div>
          </div>
        </div>

        <ScrollArea className="flex-1 mt-4 -mx-6 px-6">
          {ambiguousCount > 0 && (
            <div className="space-y-4">
              <h3 className="text-sm font-semibold">Pick a product for each ambiguous row</h3>
              {result.ambiguous.map((row, idx) => (
                <div
                  key={`ambig-${idx}-${row.identifier}`}
                  className="border rounded-md p-3"
                >
                  <div className="flex items-center justify-between mb-2">
                    <div>
                      <div className="text-xs text-muted-foreground">Pasted value</div>
                      <div className="font-mono text-sm">{row.identifier}</div>
                    </div>
                    <div className="text-right">
                      <div className="text-xs text-muted-foreground">Qty</div>
                      <div className="text-sm font-semibold">{row.qty}</div>
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    {row.candidates.map((c) => {
                      const isPicked = picks[idx] === c.pid;
                      return (
                        <button
                          key={c.pid}
                          type="button"
                          onClick={() =>
                            setPicks((prev) => ({
                              ...prev,
                              [idx]: isPicked ? null : c.pid,
                            }))
                          }
                          className={cn(
                            "w-full text-left flex items-center gap-3 p-2 rounded-md border transition-colors",
                            isPicked
                              ? "border-primary bg-primary/5"
                              : "border-border hover:bg-muted/50"
                          )}
                        >
                          <div
                            className={cn(
                              "h-4 w-4 rounded-full border-2 flex-shrink-0",
                              isPicked
                                ? "border-primary bg-primary"
                                : "border-muted-foreground/40"
                            )}
                          />
                          <div className="flex-1 min-w-0">
                            <div className="text-sm font-medium truncate">
                              {c.title}
                            </div>
                            <div className="text-xs text-muted-foreground flex gap-3">
                              <span>PID {c.pid}</span>
                              {c.sku && <span>SKU {c.sku}</span>}
                              {c.barcode && <span>UPC {c.barcode}</span>}
                              {c.brand && <span>{c.brand}</span>}
                            </div>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}

          {unmatchedCount > 0 && (
            <div className="mt-6">
              <h3 className="text-sm font-semibold mb-2">
                Unmatched (these will be skipped)
              </h3>
              <div className="border rounded-md divide-y">
                {result.unmatched.map((row, idx) => (
                  <div
                    key={`unmatched-${idx}-${row.identifier}`}
                    className="flex items-center justify-between p-2 text-sm"
                  >
                    <span className="font-mono">{row.identifier}</span>
                    <span className="text-muted-foreground text-xs">qty {row.qty}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </ScrollArea>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={handleConfirm}>
            Add{" "}
            {matchedCount + Object.values(picks).filter((p) => p != null).length}{" "}
            products
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
