"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import type { DuplicateDocument, DuplicateAction } from "@/types/ocr";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";

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-card text-foreground">
        <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-foreground">{dup.filename}</div>
              <div className="text-xs text-muted-foreground">
                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>
              {/* Native radios draw their own OS dot, so they could not take
                  the brand colour. RadioGroup also gives real arrow-key
                  navigation within the group. */}
              <RadioGroup
                value={choices[dup.filename] ?? ""}
                onValueChange={(value) =>
                  setChoices((prev) => ({
                    ...prev,
                    [dup.filename]: value as DuplicateAction,
                  }))
                }
                className="flex gap-4"
              >
                <div className="flex items-center gap-1.5">
                  <RadioGroupItem value="skip" id={`dup-doc-${idx}-skip`} />
                  <Label htmlFor={`dup-doc-${idx}-skip`} className="text-xs font-normal">
                    Skip
                  </Label>
                </div>
                <div className="flex items-center gap-1.5">
                  <RadioGroupItem value="update" id={`dup-doc-${idx}-update`} />
                  <Label htmlFor={`dup-doc-${idx}-update`} className="text-xs font-normal">
                    Update
                  </Label>
                </div>
              </RadioGroup>
            </div>
          ))}
        </div>

        <DialogFooter className="gap-2">
          <button
            type="button"
            onClick={handleCancel}
            className="px-4 py-2 text-sm border rounded-md hover:bg-muted"
          >
            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-primary text-white rounded-md hover:bg-primary-hover"
          >
            Continue with Choices
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
