"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentSession } from "@mosaic/shared";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiPost } from "@/lib/api/client";

const CONFIRM_TEXT = "KILL ALL";
const AUTO_CLOSE_DELAY_MS = 2_000;

type KillScope = "internal" | "all";

export interface KillAllDialogProps {
  sessions: AgentSession[];
  onComplete?: () => void;
}

export function KillAllDialog({ sessions, onComplete }: KillAllDialogProps): React.JSX.Element {
  const [open, setOpen] = useState(false);
  const [scope, setScope] = useState<KillScope>("internal");
  const [confirmationInput, setConfirmationInput] = useState("");
  const [isKilling, setIsKilling] = useState(false);
  const [completedCount, setCompletedCount] = useState(0);
  const [targetCount, setTargetCount] = useState(0);
  const [successCount, setSuccessCount] = useState<number | null>(null);
  const closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const internalSessions = useMemo(
    () => sessions.filter((session) => session.providerType.toLowerCase() === "internal"),
    [sessions]
  );

  const scopedSessions = useMemo(
    () => (scope === "all" ? sessions : internalSessions),
    [scope, sessions, internalSessions]
  );

  const hasConfirmation = confirmationInput === CONFIRM_TEXT;
  const isConfirmDisabled =
    isKilling || successCount !== null || !hasConfirmation || scopedSessions.length === 0;

  useEffect((): (() => void) => {
    return (): void => {
      if (closeTimeoutRef.current !== null) {
        clearTimeout(closeTimeoutRef.current);
      }
    };
  }, []);

  const resetState = (): void => {
    setScope("internal");
    setConfirmationInput("");
    setIsKilling(false);
    setCompletedCount(0);
    setTargetCount(0);
    setSuccessCount(null);
  };

  const handleOpenChange = (nextOpen: boolean): void => {
    if (!nextOpen && isKilling) {
      return;
    }

    if (!nextOpen) {
      if (closeTimeoutRef.current !== null) {
        clearTimeout(closeTimeoutRef.current);
      }
      resetState();
    }

    setOpen(nextOpen);
  };

  const handleKillAll = async (): Promise<void> => {
    if (isConfirmDisabled) {
      return;
    }

    const targetSessions = [...scopedSessions];
    setIsKilling(true);
    setCompletedCount(0);
    setTargetCount(targetSessions.length);
    setSuccessCount(null);

    const killRequests = targetSessions.map(async (session) => {
      try {
        await apiPost<{ message: string }>(`/api/mission-control/sessions/${session.id}/kill`, {
          force: true,
        });
        return true;
      } catch {
        return false;
      } finally {
        setCompletedCount((currentCount) => currentCount + 1);
      }
    });

    const results = await Promise.all(killRequests);
    const successfulKills = results.filter(Boolean).length;

    setIsKilling(false);
    setSuccessCount(successfulKills);
    onComplete?.();

    closeTimeoutRef.current = setTimeout(() => {
      setOpen(false);
      resetState();
    }, AUTO_CLOSE_DELAY_MS);
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button variant="danger" size="sm">
          Kill All
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[520px]">
        <DialogHeader>
          <DialogTitle>Kill All Agents</DialogTitle>
          <DialogDescription>
            This force-kills every selected agent session. This action cannot be undone.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <fieldset className="space-y-2">
            <legend className="text-sm font-medium">Scope</legend>
            <label className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
              <input
                type="radio"
                name="kill-all-scope"
                checked={scope === "internal"}
                disabled={isKilling}
                onChange={() => {
                  setScope("internal");
                }}
              />
              <span>Internal provider only ({internalSessions.length})</span>
            </label>
            <label className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
              <input
                type="radio"
                name="kill-all-scope"
                checked={scope === "all"}
                disabled={isKilling}
                onChange={() => {
                  setScope("all");
                }}
              />
              <span>All providers ({sessions.length})</span>
            </label>
          </fieldset>

          <div className="space-y-2">
            <Label htmlFor="kill-all-confirmation-input">Type KILL ALL to confirm</Label>
            <Input
              id="kill-all-confirmation-input"
              value={confirmationInput}
              onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                setConfirmationInput(event.target.value);
              }}
              placeholder={CONFIRM_TEXT}
              autoComplete="off"
              disabled={isKilling}
            />
          </div>

          {scopedSessions.length === 0 ? (
            <p className="text-sm text-red-500">No sessions in the selected scope.</p>
          ) : null}

          {isKilling ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
              <span>
                Killing {completedCount} of {targetCount} agents...
              </span>
            </div>
          ) : successCount !== null ? (
            <p className="text-sm text-muted-foreground">
              Killed {successCount} of {targetCount} agents. Closing...
            </p>
          ) : null}
        </div>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            disabled={isKilling}
            onClick={() => {
              setOpen(false);
            }}
          >
            Cancel
          </Button>
          <Button
            type="button"
            variant="danger"
            disabled={isConfirmDisabled}
            onClick={() => {
              void handleKillAll();
            }}
          >
            Kill All Agents
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
