"use client";

import { useState, useCallback, useEffect, useRef } from "react";
import { RotateCcw, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";

interface RestoreDialogProps {
  isOpen: boolean;
  sourceLabel: string;
  isProcessing: boolean;
  onRestore: (reason: string) => void;
  onCancel: () => void;
}

export function RestoreDialog({
  isOpen,
  sourceLabel,
  isProcessing,
  onRestore,
  onCancel,
}: RestoreDialogProps) {
  const [reason, setReason] = useState("");
  const dialogRef = useRef<HTMLDivElement>(null);
  const previousActiveElement = useRef<HTMLElement | null>(null);

  // Reset reason when dialog opens
  useEffect(() => {
    if (isOpen) {
      setReason("");
    }
  }, [isOpen]);

  // Focus management
  useEffect(() => {
    if (isOpen) {
      previousActiveElement.current = document.activeElement as HTMLElement;
      dialogRef.current?.focus();
    } else if (previousActiveElement.current) {
      previousActiveElement.current.focus();
    }
  }, [isOpen]);

  const handleBackdropClick = useCallback(
    (e: React.MouseEvent) => {
      if (e.target === e.currentTarget && !isProcessing) {
        onCancel();
      }
    },
    [onCancel, isProcessing]
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "Escape" && !isProcessing) {
        onCancel();
      }
    },
    [onCancel, isProcessing]
  );

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={handleBackdropClick}
      onKeyDown={handleKeyDown}
      role="presentation"
    >
      <div
        ref={dialogRef}
        tabIndex={-1}
        role="dialog"
        aria-modal="true"
        aria-labelledby="restore-dialog-title"
        className="w-full max-w-md mx-4 rounded-lg border border-border bg-card p-6 shadow-lg outline-none"
      >
        {/* Header */}
        <div className="flex items-center gap-3 mb-4">
          <div className="w-10 h-10 rounded-full bg-emerald-500/10 flex items-center justify-center">
            <RotateCcw className="h-5 w-5 text-emerald-500" />
          </div>
          <div>
            <h3
              id="restore-dialog-title"
              className="text-lg font-semibold text-foreground"
            >
              Restore Source
            </h3>
            <p className="text-sm text-muted-foreground">{sourceLabel}</p>
          </div>
        </div>

        {/* Description */}
        <p className="mb-4 text-sm text-muted-foreground">
          Restoring this source will reactivate all associated assertions and
          they will once again be included in query results.
        </p>

        {/* Reason input */}
        <div className="mb-6">
          <label
            htmlFor="restore-reason"
            className="block text-sm font-medium text-foreground mb-2"
          >
            Reason for restore (optional)
          </label>
          <textarea
            id="restore-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder="e.g., Investigation complete, source verified"
            className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring resize-none"
            rows={2}
            disabled={isProcessing}
          />
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-3">
          <Button variant="outline" onClick={onCancel} disabled={isProcessing}>
            Cancel
          </Button>
          <Button onClick={() => onRestore(reason)} disabled={isProcessing}>
            {isProcessing ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Restoring...
              </>
            ) : (
              "Restore Source"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}
