"use client";

import { useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { removeChargepoint } from "./delete-client-api";
import type { Chargepoint } from "./types";

export function DeleteChargepointDialog({ chargepoint, onOpenChange, onDeleted }: {
  chargepoint: Pick<Chargepoint, "id" | "name" | "endpoint">;
  onOpenChange: (open: boolean) => void;
  onDeleted: () => void;
}) {
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState("");
  const pending = useRef(false);
  const cancelButton = useRef<HTMLButtonElement>(null);

  function changeOpen(open: boolean) {
    if (!pending.current) onOpenChange(open);
  }

  async function confirmDelete() {
    if (pending.current) return;
    pending.current = true;
    setDeleting(true);
    setError("");
    try {
      await removeChargepoint(chargepoint.id);
      onDeleted();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Unable to delete this chargepoint.");
    } finally {
      pending.current = false;
      setDeleting(false);
    }
  }

  return <Dialog open onOpenChange={changeOpen}>
    <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-md" showCloseButton={!deleting}
      onOpenAutoFocus={(event) => { event.preventDefault(); cancelButton.current?.focus(); }}>
      <DialogHeader>
        <DialogTitle>Delete chargepoint?</DialogTitle>
        <DialogDescription>This removes the chargepoint from the CSMS. This action cannot be undone here.</DialogDescription>
      </DialogHeader>
      <div className="min-w-0 rounded-lg border bg-muted/40 p-4">
        <p className="break-words font-semibold">{chargepoint.name}</p>
        <p className="mt-1 break-all text-sm text-muted-foreground">{chargepoint.endpoint}</p>
        <p className="mt-2 break-all font-mono text-xs text-muted-foreground">{chargepoint.id}</p>
      </div>
      {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
      {deleting && <p role="status" className="text-sm text-muted-foreground">Deleting chargepoint…</p>}
      <DialogFooter>
        <Button ref={cancelButton} type="button" variant="outline" disabled={deleting} onClick={() => changeOpen(false)}>Cancel</Button>
        <Button type="button" variant="destructive" disabled={deleting} aria-busy={deleting} onClick={confirmDelete}>
          {deleting && <Loader2 aria-hidden="true" className="animate-spin motion-reduce:animate-none" />}
          {deleting ? "Deleting…" : "Delete chargepoint"}
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>;
}
