"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import type { DuplicateDocument, DuplicateAction } from "@/types/ocr";

interface DuplicateDocumentDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  duplicates: DuplicateDocument[];
  onResolve: (choices: Record<string, DuplicateAction> | null) => void;
}

export function DuplicateDocumentDialog({
  open,
  onOpenChange,
  duplicates,
  onResolve,
}: DuplicateDocumentDialogProps) {
  const [choices, setChoices] = useState<Record<string, DuplicateAction>>(() => {
    const initial: Record<string, DuplicateAction> = {};
    duplicates.forEach((dup) => {
      initial[dup.filename] = "skip";
    });
    return initial;
  });

  const handleCancel = () => {
    onResolve(null);
    onOpenChange(false);
  };

  const handleSkipAll = () => {
    const skipAll: Record<string, DuplicateAction> = {};
    duplicates.forEach((dup) => {
      skipAll[dup.filename] = "skip";
    });
    onResolve(skipAll);
    onOpenChange(false);
  };

  const handleContinueWithChoices = () => {
    onResolve(choices);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg bg-white text-gray-900">
        <DialogHeader>
          <DialogTitle className="text-amber-600">
            Duplicate Documents Found
          </DialogTitle>
        </DialogHeader>

        <div className="max-h-64 overflow-y-auto space-y-3 py-2">
          {duplicates.map((dup, idx) => (
            <div
              key={idx}
              className="border rounded-lg p-3 text-sm space-y-2"
            >
              <div className="font-medium text-gray-800">{dup.filename}</div>
              <div className="text-xs text-gray-500">
                Existing ID: {dup.existing_record.ocr_data_id}
                {dup.existing_record.extraction_date &&
                  ` | Date: ${dup.existing_record.extraction_date}`}
                {dup.existing_record.total_positions != null &&
                  ` | Positions: ${dup.existing_record.total_positions}`}
              </div>
              <div className="flex gap-4">
                <label className="flex items-center gap-1.5 text-xs cursor-pointer">
                  <input
                    type="radio"
                    name={`dup-doc-${idx}`}
                    checked={choices[dup.filename] === "skip"}
                    onChange={() =>
                      setChoices((prev) => ({
                        ...prev,
                        [dup.filename]: "skip",
                      }))
                    }
                  />
                  Skip
                </label>
                <label className="flex items-center gap-1.5 text-xs cursor-pointer">
                  <input
                    type="radio"
                    name={`dup-doc-${idx}`}
                    checked={choices[dup.filename] === "update"}
                    onChange={() =>
                      setChoices((prev) => ({
                        ...prev,
                        [dup.filename]: "update",
                      }))
                    }
                  />
                  Update
                </label>
              </div>
            </div>
          ))}
        </div>

        <DialogFooter className="gap-2">
          <button
            type="button"
            onClick={handleCancel}
            className="px-4 py-2 text-sm border rounded-md hover:bg-gray-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSkipAll}
            className="px-4 py-2 text-sm bg-amber-500 text-white rounded-md hover:bg-amber-600"
          >
            Skip All & Continue
          </button>
          <button
            type="button"
            onClick={handleContinueWithChoices}
            className="px-4 py-2 text-sm bg-[#428B4D] text-white rounded-md hover:bg-[#357a3f]"
          >
            Continue with Choices
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
