import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { useLocaleFunction } from "@/hooks/use-localed";
import { toast } from "@/hooks/use-toast";
import {
  detachUserPaymentMethod,
  type UserPaymentCardMethod,
} from "@/lib/api/billing";
import { getErrorMessage } from "@/lib/errors";
import { cn } from "@/lib/utils";
import { Loader2Icon } from "lucide-react";
import { type ComponentProps, useState } from "react";
import { PaymentIcon } from "react-svg-credit-card-payment-icons";

export function PaymentCardInfo({
  card,
  className,
  onRemoved,
  ...props
}: {
  card: UserPaymentCardMethod;
  onRemoved?: () => void;
} & ComponentProps<"div">) {
  const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
  const [removing, setRemoving] = useState<boolean>(false);
  const [removingError, setRemovingError] = useState();

  const t = useLocaleFunction();

  const handleRemove = () => {
    setRemoving(true);
    detachUserPaymentMethod(card.stripe_pm_id)
      .then(() => {
        toast({
          title: t("payment.toasts.succeed-to-remove-payment-method"),
        });
        setRemoveDialogOpen(false);
        onRemoved?.();
      })
      .catch((e) => {
        setRemovingError(e);
      })
      .finally(() => {
        setRemoving(false);
      });
  };

  return (
    <div
      className={cn("rounded-md border p-4 group/card", className)}
      {...props}
    >
      <div className="flex items-end justify-between">
        <PaymentIcon type={card.card_brand as never} format="logo" />
        <Checkbox
          className="group-data-state/card:block hidden"
          checked={(props as any)["data-state"] === "on"}
        />
      </div>
      <div className="mt-2 font-mono text-lg text-muted-foreground flex items-center justify-between">
        <span>******{card.last4}</span>
        <span className="ml-auto">
          {card.exp_month.toString().padStart(2, "0")}/
          {card.exp_year.toString().slice(-2)}
        </span>
      </div>

      {onRemoved && (
        <AlertDialog open={removeDialogOpen} onOpenChange={setRemoveDialogOpen}>
          <AlertDialogTrigger asChild>
            <Button variant="secondary" className="ml-auto mt-4 flex">
              {t("payment.payment-methods.remove")}
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>
                {t("payment.payment-methods.remove.confirm.title")}
              </AlertDialogTitle>
              <AlertDialogDescription>
                {t("payment.payment-methods.remove.confirm.description")}
              </AlertDialogDescription>
            </AlertDialogHeader>
            {removingError != null && (
              <Alert variant="destructive">
                <AlertTitle>
                  {t("payment.alerts.failed-to-remove-payment-method.title")}
                </AlertTitle>
                <AlertDescription>
                  {getErrorMessage(removingError)}
                </AlertDescription>
              </Alert>
            )}
            <AlertDialogFooter>
              <AlertDialogAction onClick={handleRemove} disabled={removing}>
                {t("common.confirm")}
                {removing && (
                  <Loader2Icon className="animate-spin repeat-infinite" />
                )}
              </AlertDialogAction>
              <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
    </div>
  );
}
