"use client";

import { useState, useTransition } from "react";
import { Loader2, BellRing } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { triggerAlertAction } from "./actions";

export function AlertButton({
  assignmentId,
}: {
  assignmentId: string;
}) {
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [isPending, startTransition] = useTransition();

  const handleAlert = () => {
    startTransition(async () => {
      const result = await triggerAlertAction(assignmentId);
      if ("error" in result && result.error) {
        toast.error(result.error);
      } else {
        toast.success("Alarm erfolgreich ausgelöst. E-Mail wurde versendet.");
      }
    });
  };

  return (
    <ConfirmDialog
      open={confirmOpen}
      onOpenChange={setConfirmOpen}
      title="Notdienst-Alarm auslösen?"
      description="Der Alarm informiert die hinterlegten Kontakte per E-Mail über den Notdienst."
      confirmLabel="Alarm auslösen"
      pendingLabel="Alarm wird ausgelöst..."
      isPending={isPending}
      onConfirm={handleAlert}
    >
      <Button variant="destructive" disabled={isPending}>
        {isPending ? (
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        ) : (
          <BellRing className="mr-2 h-4 w-4" />
        )}
        Alarm auslösen
      </Button>
    </ConfirmDialog>
  );
}
