import { useBillingConfig } from "@/components/billing/billing-context";
import { PaymentCardInfo } from "@/components/billing/payment-card-info";
import { PaymentMethodFullSetup } from "@/components/billing/payment-method-setup";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { useLocaleFunction } from "@/hooks/use-localed";
import { type UserPaymentMethod } from "@/lib/api/billing";
import { PlusIcon } from "lucide-react";
import { useState } from "react";

export function PaymentMethodsManagement({
  methods,
  onUpdate,
}: {
  methods?: UserPaymentMethod[];
  onUpdate?: () => void;
}) {
  const { stripe } = useBillingConfig();
  const [open, setOpen] = useState(false);
  const t = useLocaleFunction();
  return (
    <div className="grid grid-cols-2 gap-4">
      {methods?.map((method) => (
        <PaymentCardInfo
          key={method.stripe_pm_id}
          card={method}
          onRemoved={() => onUpdate?.()}
        />
      ))}
      {methods && methods.length < stripe.max_payment_methods && (
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger className="rounded-md border border-dashed p-4 flex items-center gap-2 justify-center text-muted-foreground text-lg font-semibold hover:border-muted-foreground transition-colors">
            {t("payment.payment-methods.add")}
            <PlusIcon className="size-4" />
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t("payment.payment-methods.add")}</DialogTitle>
              <DialogDescription>
                {t(
                  "payment.payment-methods.add.description",
                  stripe.max_payment_methods
                )}
              </DialogDescription>
            </DialogHeader>
            <PaymentMethodFullSetup
              onSetupFinished={() => {
                onUpdate?.();
                setOpen(false);
              }}
              submitVariant="default"
            />
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
