"use client";

import { useState, useCallback, useEffect, useRef } from "react";
import { Ban, Loader2 } from "lucide-react";
import type { SourceImpactResponse } from "@/lib/api/types";
import { Button } from "@/components/ui/button";
import { ImpactPreview } from "./impact-preview";

interface BlockDialogProps {
  isOpen: boolean;
  sourceLabel: string;
  impact: SourceImpactResponse | null;
  isLoadingImpact: boolean;
  isProcessing: boolean;
  onBlockNow: (reason: string) => void;
  onReviewFirst: () => void;
  onCancel: () => void;
}

export function BlockDialog({
  isOpen,
  sourceLabel,
  impact,
  isLoadingImpact,
  isProcessing,
  onBlockNow,
  onReviewFirst,
  onCancel,
}: BlockDialogProps) {
  const [reason, setReason] = useState("");
  const [showAnimation, setShowAnimation] = useState(false);
  const dialogRef = useRef<HTMLDivElement>(null);
  const previousActiveElement = useRef<HTMLElement | null>(null);

  // Trigger animation when impact loads
  useEffect(() => {
    if (impact && !isLoadingImpact) {
      setShowAnimation(true);
      const timer = setTimeout(() => setShowAnimation(false), 1000);
      return () => clearTimeout(timer);
    }
  }, [impact, isLoadingImpact]);

  // 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="block-dialog-title"
        className="w-full max-w-lg 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-red-500/10 flex items-center justify-center">
            <Ban className="h-5 w-5 text-red-500" />
          </div>
          <div>
            <h3
              id="block-dialog-title"
              className="text-lg font-semibold text-foreground"
            >
              Block Source
            </h3>
            <p className="text-sm text-muted-foreground">{sourceLabel}</p>
          </div>
        </div>

        {/* Impact Preview */}
        <div className="mb-4">
          {isLoadingImpact ? (
            <div className="flex items-center justify-center p-8">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              <span className="ml-2 text-sm text-muted-foreground">
                Calculating impact...
              </span>
            </div>
          ) : impact ? (
            <ImpactPreview impact={impact} isAnimating={showAnimation} />
          ) : null}
        </div>

        {/* Warning */}
        {impact && impact.assertion_count > 0 && (
          <div className="mb-4 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30">
            <p className="text-sm text-amber-600 dark:text-amber-400">
              <strong>Warning:</strong> This will affect{" "}
              {impact.assertion_count} downstream assertion
              {impact.assertion_count !== 1 ? "s" : ""} and{" "}
              {impact.affected_agents.length} recommendation
              {impact.affected_agents.length !== 1 ? "s" : ""}.
            </p>
          </div>
        )}

        {/* Reason input */}
        <div className="mb-6">
          <label
            htmlFor="block-reason"
            className="block text-sm font-medium text-foreground mb-2"
          >
            Reason for blocking (optional)
          </label>
          <textarea
            id="block-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder="e.g., Study retracted due to data fabrication"
            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 flex-col sm:flex-row gap-3 sm:justify-end">
          <Button
            variant="outline"
            onClick={onCancel}
            disabled={isProcessing}
          >
            Cancel
          </Button>
          <Button
            variant="outline"
            onClick={onReviewFirst}
            disabled={isProcessing || isLoadingImpact}
          >
            Review Affected Items First
          </Button>
          <Button
            variant="destructive"
            onClick={() => onBlockNow(reason)}
            disabled={isProcessing || isLoadingImpact}
          >
            {isProcessing ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Processing...
              </>
            ) : (
              "Block Immediately"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}
