"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { CheckCircle2, RotateCcw } from "lucide-react";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { closeTicketAction, reopenTicketAction } from "@/lib/actions/tickets";
import { commonTexts } from "@/lib/i18n/common";
import { ticketsTexts as tx } from "@/lib/i18n/tickets";
import type { TicketActionState } from "@/lib/validation/tickets";

function useTicketMutation(ticketId: string) {
  const router = useRouter();
  const [pending, startTransition] = React.useTransition();

  const run = React.useCallback(
    (
      action: (prev: TicketActionState, formData: FormData) => Promise<TicketActionState>,
      successMessage: string,
    ) => {
      startTransition(async () => {
        const formData = new FormData();
        formData.set("ticketId", ticketId);
        const result = await action(null, formData);
        if (result && result.ok) {
          toast.success(successMessage);
          router.refresh();
        } else {
          toast.error(result && !result.ok ? result.error : tx.errGeneric);
        }
      });
    },
    [ticketId, router],
  );

  return { pending, run };
}

export function CloseTicketButton({
  ticketId,
  className,
}: {
  ticketId: string;
  className?: string;
}) {
  const { pending, run } = useTicketMutation(ticketId);

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <Button
          type="button"
          variant="outline"
          disabled={pending}
          aria-busy={pending}
          className={className}
        >
          {pending ? (
            <Spinner className="size-4" />
          ) : (
            <CheckCircle2 className="size-4" />
          )}
          {pending ? tx.closeTicketPending : tx.closeTicket}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{tx.closeTicketConfirmTitle}</AlertDialogTitle>
          <AlertDialogDescription>{tx.closeTicketConfirmBody}</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>{commonTexts.cancel}</AlertDialogCancel>
          <AlertDialogAction
            onClick={() => run(closeTicketAction, tx.ticketClosed)}
          >
            {tx.closeTicket}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}

export function ReopenTicketButton({
  ticketId,
  className,
}: {
  ticketId: string;
  className?: string;
}) {
  const { pending, run } = useTicketMutation(ticketId);

  return (
    <Button
      type="button"
      disabled={pending}
      aria-busy={pending}
      className={className}
      onClick={() => run(reopenTicketAction, tx.ticketReopened)}
    >
      {pending ? <Spinner className="size-4" /> : <RotateCcw className="size-4" />}
      {pending ? tx.reopenTicketPending : tx.reopenTicket}
    </Button>
  );
}
