import { useState } from "react";
import {
  CheckCircle,
  RotateCcw,
  AlertTriangle,
  Loader2,
  Shield,
  ShieldCheck,
  FileIcon,
  X,
} from "lucide-react";
import type { Test } from "../../types/models";

// ── Props ──────────────────────────────────────────────────────────

type RedDecision = "approve" | "reopen";
type BlueDecision = "approve" | "reopen" | "gap";

interface ReviewModalProps {
  side: "red" | "blue";
  test: Test;
  isSubmitting: boolean;
  onSubmitRed?: (decision: RedDecision, notes: string) => void;
  onSubmitBlue?: (decision: BlueDecision, notes: string, systemGaps: string) => void;
  onClose: () => void;
}

// ── Component ──────────────────────────────────────────────────────

export default function ReviewModal({
  side,
  test,
  isSubmitting,
  onSubmitRed,
  onSubmitBlue,
  onClose,
}: ReviewModalProps) {
  const isRed = side === "red";
  const [decision, setDecision] = useState<RedDecision | BlueDecision | null>(null);
  const [notes, setNotes] = useState("");
  const [systemGaps, setSystemGaps] = useState("");

  const title = isRed ? "Review Red Team Submission" : "Review Blue Team Submission";
  const accent = isRed ? "orange" : "indigo";
  const evidences = isRed ? test.red_evidences || [] : test.blue_evidences || [];

  const requiresNotes = decision === "reopen" && notes.trim().length === 0;
  const requiresGaps = decision === "gap" && systemGaps.trim().length === 0;

  const canSubmit = decision !== null && !isSubmitting && !requiresNotes && !requiresGaps;

  const handleSubmit = () => {
    if (!decision) return;
    if (isRed) {
      onSubmitRed?.(decision as RedDecision, notes);
    } else {
      onSubmitBlue?.(decision as BlueDecision, notes, systemGaps);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="w-full max-w-lg rounded-xl border border-gray-800 bg-gray-900 shadow-xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-800 px-6 py-4">
          <div className="flex items-center gap-2">
            {isRed ? (
              <Shield className={`h-5 w-5 text-${accent}-400`} />
            ) : (
              <ShieldCheck className={`h-5 w-5 text-${accent}-400`} />
            )}
            <h3 className="text-lg font-semibold text-white">{title}</h3>
          </div>
          <button
            onClick={onClose}
            className="rounded p-1 text-gray-400 hover:bg-gray-800 hover:text-white"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Body */}
        <div className="space-y-5 px-6 py-5">
          {/* Evidence summary */}
          <div>
            <h4 className="mb-2 text-sm font-medium text-gray-300">
              {isRed ? "Red" : "Blue"} Team Evidence ({evidences.length})
            </h4>
            {evidences.length > 0 ? (
              <div className="max-h-32 space-y-1 overflow-y-auto rounded-lg border border-gray-700 bg-gray-800/50 p-2">
                {evidences.map((ev) => (
                  <div key={ev.id} className="flex items-center gap-2 text-xs text-gray-400">
                    <FileIcon className="h-3.5 w-3.5 text-gray-500" />
                    <span className="truncate">{ev.file_name}</span>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-xs text-gray-500">No evidence files uploaded.</p>
            )}
          </div>

          {/* Decision */}
          <div>
            <h4 className="mb-2 text-sm font-medium text-gray-300">Decision</h4>
            <div className="flex gap-3">
              <button
                onClick={() => setDecision("approve")}
                className={`flex flex-1 items-center justify-center gap-2 rounded-lg border p-3 text-sm font-medium transition-colors ${
                  decision === "approve"
                    ? "border-green-500 bg-green-500/10 text-green-400"
                    : "border-gray-700 bg-gray-800 text-gray-400 hover:border-gray-600"
                }`}
              >
                <CheckCircle className="h-4 w-4" />
                Approve
              </button>
              <button
                onClick={() => setDecision("reopen")}
                className={`flex flex-1 items-center justify-center gap-2 rounded-lg border p-3 text-sm font-medium transition-colors ${
                  decision === "reopen"
                    ? "border-amber-500 bg-amber-500/10 text-amber-400"
                    : "border-gray-700 bg-gray-800 text-gray-400 hover:border-gray-600"
                }`}
              >
                <RotateCcw className="h-4 w-4" />
                Reopen
              </button>
              {!isRed && (
                <button
                  onClick={() => setDecision("gap")}
                  className={`flex flex-1 items-center justify-center gap-2 rounded-lg border p-3 text-sm font-medium transition-colors ${
                    decision === "gap"
                      ? "border-purple-500 bg-purple-500/10 text-purple-400"
                      : "border-gray-700 bg-gray-800 text-gray-400 hover:border-gray-600"
                  }`}
                >
                  <AlertTriangle className="h-4 w-4" />
                  System Gap
                </button>
              )}
            </div>
            {decision === "gap" && (
              <p className="mt-2 text-xs text-gray-500">
                Use this when the operator did everything right but Blue Team is missing a
                capability (tooling, visibility) needed to detect/block this technique. The test
                still proceeds to cross-validation.
              </p>
            )}
          </div>

          {/* Notes (reopen) */}
          {decision === "reopen" && (
            <div>
              <label className="mb-1.5 block text-sm font-medium text-gray-300">
                Notes <span className="text-red-400">(required)</span>
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={3}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-amber-500 focus:outline-none focus:ring-1 focus:ring-amber-500"
                placeholder="Explain what needs to be redone..."
              />
              {requiresNotes && (
                <p className="mt-1 text-xs text-red-400">Notes are required when reopening.</p>
              )}
            </div>
          )}

          {/* System gaps (blue gap only) */}
          {decision === "gap" && (
            <div>
              <label className="mb-1.5 block text-sm font-medium text-gray-300">
                System Gaps <span className="text-red-400">(required)</span>
              </label>
              <textarea
                value={systemGaps}
                onChange={(e) => setSystemGaps(e.target.value)}
                rows={3}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-purple-500 focus:outline-none focus:ring-1 focus:ring-purple-500"
                placeholder="What's missing to properly detect/block this technique?"
              />
              {requiresGaps && (
                <p className="mt-1 text-xs text-red-400">
                  Describe the gap before flagging it.
                </p>
              )}
              <label className="mb-1.5 mt-3 block text-sm font-medium text-gray-300">
                Notes (optional)
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={2}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-purple-500 focus:outline-none focus:ring-1 focus:ring-purple-500"
                placeholder="Optional notes..."
              />
            </div>
          )}

          {/* Notes (approve, optional) */}
          {decision === "approve" && (
            <div>
              <label className="mb-1.5 block text-sm font-medium text-gray-300">
                Notes (optional)
              </label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={2}
                className="w-full rounded-lg border border-gray-700 bg-gray-800 px-3 py-2 text-sm text-gray-200 placeholder-gray-500 focus:border-green-500 focus:outline-none focus:ring-1 focus:ring-green-500"
                placeholder="Optional notes..."
              />
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-3 border-t border-gray-800 px-6 py-4">
          <button
            onClick={onClose}
            disabled={isSubmitting}
            className="rounded-lg border border-gray-700 px-4 py-2 text-sm text-gray-400 hover:bg-gray-800 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={!canSubmit}
            className={`flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors disabled:opacity-50 ${
              decision === "reopen"
                ? "bg-amber-600 hover:bg-amber-500"
                : decision === "gap"
                  ? "bg-purple-600 hover:bg-purple-500"
                  : "bg-green-600 hover:bg-green-500"
            }`}
          >
            {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
            {decision === "approve"
              ? "Confirm Approval"
              : decision === "reopen"
                ? "Confirm Reopen"
                : decision === "gap"
                  ? "Confirm System Gap"
                  : "Select a decision"}
          </button>
        </div>
      </div>
    </div>
  );
}
