import { PaymentCardInfo } from "@/components/billing/payment-card-info";
import { PaymentMethodsQuickSetup } from "@/components/billing/payment-method-setup";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { useLocaleFunction } from "@/hooks/use-localed";
import type { BillingDetails, UserPaymentMethod } from "@/lib/api/billing";
import { ToggleGroup as ToggleGroupPrimitives } from "radix-ui";

export function PaymentMethodsSelect({
  billingDetails,
  methods,
  value,
  onValueChange,
  onCreated,
  onConfirm,
}: {
  billingDetails: BillingDetails;
  methods?: UserPaymentMethod[];
  value: string | undefined;
  onValueChange: (paymentMethodId: string) => void;
  onCreated: (paymentMethodId: string) => void;
  onConfirm: () => void;
}) {
  const t = useLocaleFunction();
  return (
    <div className="space-y-4">
      <div className="space-y-2">
        <Label>{t("payment.payment-methods.select.title")}</Label>
        {methods && methods.length > 0 && (
          <ToggleGroupPrimitives.Root
            type="single"
            value={value}
            onValueChange={onValueChange}
            className="space-y-4"
          >
            {methods.map((method) => (
              <ToggleGroupPrimitives.Item
                key={method.stripe_pm_id}
                value={method.stripe_pm_id}
                asChild
              >
                <PaymentCardInfo
                  card={method}
                  className="cursor-pointer hover:bg-accent data-[state=on]:ring-offset-1 data-[state=on]:ring-1 data-[state=on]:ring-primary"
                />
              </ToggleGroupPrimitives.Item>
            ))}
          </ToggleGroupPrimitives.Root>
        )}
        {methods && methods.length === 0 && (
          <PaymentMethodsQuickSetup
            billingDetails={billingDetails}
            onSetupFinished={onCreated}
          />
        )}
      </div>
      {methods && methods.length > 0 && (
        <Button className="flex" disabled={!value} onClick={onConfirm}>
          {t("payment.payment-methods.select.confirm")}
        </Button>
      )}
    </div>
  );
}
