"use client";

import { useBillingConfig } from "@/components/billing/billing-context";
import {
  useCalculateCreditsPrice,
  useUserBillingProfile,
} from "@/components/billing/hooks";
import { PaymentCheckoutDialog } from "@/components/billing/payment-checkout/payment-checkout-dialog";
import {
  createPaymentCheckout,
  type PaymentCheckoutState,
} from "@/components/billing/store";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useLocaleFunction } from "@/hooks/use-localed";
import { useThrottledValue } from "@/hooks/use-throttled-value";
import type { CalculatedPrice } from "@/lib/api/billing";
import { cn } from "@/lib/utils";
import { useMemo, useState } from "react";
import type { StoreApi } from "zustand/vanilla";

const nf = new Intl.NumberFormat(["en-US"]);

export function PurchaseCredits() {
  const t = useLocaleFunction();

  const { buy_credits } = useBillingConfig();
  const [credits, setCredits] = useState<number>(buy_credits.default_quantity);
  const throttledCredits = useThrottledValue(credits);
  const invalid =
    credits < buy_credits.min_quantity ||
    credits > buy_credits.max_quantity ||
    !Number.isInteger(credits);
  const [paymentCheckoutDialogOpen, setPaymentCheckoutDialogOpen] =
    useState(false);
  const [paymentCheckout, setPaymentCheckout] =
    useState<StoreApi<PaymentCheckoutState>>();
  const { data: profile } = useUserBillingProfile();

  const { data: calculatedPrice } = useCalculateCreditsPrice(throttledCredits);

  return (
    <section className="space-y-6 p-4 rounded-lg bg-card shadow-xl border">
      <div className="space-y-2">
        <label htmlFor="credits-input" className="space-y-4 text-lg ">
          {t("credits.buy.title")}
        </label>
        <div className="flex items-center gap-2">
          <Input
            id="credits-input"
            className={cn(
              "flex-1",
              invalid &&
                "ring-destructive ring-1 focus-visible:ring-destructive"
            )}
            name="amount"
            type="number"
            min={buy_credits.min_quantity}
            max={buy_credits.max_quantity}
            step={1}
            value={isNaN(credits) ? "" : credits}
            onChange={(ev) => setCredits(ev.target.valueAsNumber)}
            onBlur={() =>
              setCredits(
                Math.max(
                  Math.min(credits, buy_credits.max_quantity),
                  buy_credits.min_quantity
                )
              )
            }
            onWheel={(ev) => {
              ev.preventDefault();
              ev.currentTarget.blur();
            }}
            aria-invalid={invalid}
          />
          <Button
            className="shrink-0 gap-0"
            disabled={invalid || !calculatedPrice}
            type="submit"
            onClick={() => {
              setPaymentCheckout(
                createPaymentCheckout({
                  quantity: credits,
                  billingDetails: profile?.billing_details ?? undefined,
                  paymentMethod: profile?.stripe_payment_methods?.[0],
                })
              );
              setPaymentCheckoutDialogOpen(true);
            }}
          >
            {invalid
              ? t("credits.buy.form.submit.invalid")
              : calculatedPrice
                ? t(
                    "credits.buy.form.submit",
                    credits,
                    <Currency calculatedPrice={calculatedPrice} />
                  )
                : t("credits.buy.form.submit.calculating-price")}
          </Button>
          {paymentCheckout && (
            <PaymentCheckoutDialog
              paymentCheckout={paymentCheckout}
              open={paymentCheckoutDialogOpen}
              onClose={() => setPaymentCheckoutDialogOpen(false)}
            />
          )}
        </div>
        <p
          className={cn(
            "text-sm text-muted-foreground",
            invalid && "text-destructive"
          )}
        >
          {invalid
            ? t(
                "credits.buy.form.amount.description.invalid",
                nf.format(buy_credits.min_quantity),
                nf.format(buy_credits.max_quantity)
              )
            : calculatedPrice
              ? calculatedPrice.discount
                ? t(
                    "credits.buy.form.amount.description.discount",
                    100 * (calculatedPrice?.discount ?? 0) + "%"
                  )
                : t("credits.buy.form.amount.description.no-discount")
              : t("credits.buy.form.amount.description.calculating-discount")}
        </p>
        <p className="text-sm text-muted-foreground">
          {t("credits.buy.description", buy_credits.min_quantity)}
        </p>
      </div>
    </section>
  );
}

function Currency({
  calculatedPrice,
}: {
  calculatedPrice: CalculatedPrice | undefined;
}) {
  const formatter = useMemo(() => {
    if (!calculatedPrice?.currency) return undefined;
    return Intl.NumberFormat(["en-US"], {
      style: "currency",
      currency: calculatedPrice.currency,
    });
  }, [calculatedPrice?.currency]);

  return <>{formatter?.format(Number(calculatedPrice?.amount_total))}</>;
}
