import { PaymentCheckout } from "@/components/billing/payment-checkout/payment-checkout";
import {
  isFinalState,
  type PaymentCheckoutState,
  PaymentCheckoutStep,
} from "@/components/billing/store";
import { AlertDescription } from "@/components/ui/alert";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogDescription,
  DialogHeader,
  DialogOverlay,
  DialogPortal,
  DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { useLocaleFunction } from "@/hooks/use-localed";
import { client } from "@/lib/api-client";
import { cn } from "@/lib/utils";
import { X } from "lucide-react";
import { Dialog as DialogPrimitive } from "radix-ui";
import { useEffect, useRef } from "react";
import { useStore } from "zustand/react";
import type { StoreApi } from "zustand/vanilla";

export function PaymentCheckoutDialog({
  open,
  onClose,
  paymentCheckout,
}: {
  open: boolean;
  onClose: () => void;
  paymentCheckout: StoreApi<PaymentCheckoutState>;
}) {
  const quantity = useStore(paymentCheckout, (state) => state.quantity);
  const t = useLocaleFunction();
  const onCloseRef = useRef(onClose);
  onCloseRef.current = onClose;

  useEffect(() => {
    if (!open) {
      return;
    }
    return paymentCheckout.subscribe((state) => {
      if (state.step === PaymentCheckoutStep.succeed) {
        toast({
          title: t("payment.toasts.succeed-to-purchase-credits", state.quantity),
        });
        onCloseRef.current();
        void client.refetchQueries({
          queryKey: ["credits.transactions"],
        });
        void client.refetchQueries({
          queryKey: ["user.me"],
        });
        void client.refetchQueries({
          queryKey: ["credits.balance"],
        });
      }
    });
  }, [paymentCheckout, open]);

  return (
    <Dialog open={open}>
      <DialogPortal>
        <DialogOverlay />
        <DialogPrimitive.Content
          className={cn(
            "fixed left-[50%] top-[50%] z-50 grid w-full max-w-2xl translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg"
          )}
        >
          <DialogHeader className="sr-only">
            <DialogTitle>{t("payment.checkout.dialog.title", quantity)}</DialogTitle>
            <DialogDescription />
          </DialogHeader>
          <CloseDialogAlert
            onClose={onClose}
            paymentCheckout={paymentCheckout}
          />
          <PaymentCheckout paymentCheckout={paymentCheckout} />
        </DialogPrimitive.Content>
      </DialogPortal>
    </Dialog>
  );
}

function CloseDialogAlert({
  paymentCheckout,
  onClose,
}: {
  paymentCheckout: StoreApi<PaymentCheckoutState>;
  onClose: () => void;
}) {
  const state = useStore(paymentCheckout);
  const t = useLocaleFunction();

  const closeButtonClassname =
    "absolute right-3 top-3 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-hidden focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground";

  if (isFinalState(state)) {
    return (
      <button className={closeButtonClassname} onClick={onClose}>
        <X className="h-4 w-4" />
        <span className="sr-only">{t("common.close")}</span>
      </button>
    );
  }

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <button className={closeButtonClassname}>
          <X className="h-4 w-4" />
          <span className="sr-only">{t("common.close")}</span>
        </button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t("payment.checkout.dialog.abort.confirm.title")}</AlertDialogTitle>
          <AlertDescription>
            {t("payment.checkout.dialog.abort.confirm.description")}
          </AlertDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogAction
            onClick={() => {
              onClose();
              if (!isFinalState(state)) {
                setTimeout(() => {
                  state.fail("User abort");
                }, 1000);
              }
            }}
          >
            {t("payment.checkout.dialog.abort.confirm.action")}
          </AlertDialogAction>
          <AlertDialogCancel>{t("payment.checkout.dialog.abort.cancel")}</AlertDialogCancel>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
