"use client";

import type { BillablePlan } from "@/lib/billing/plans";

import { useTranslations } from "next-intl";
import { useTransition } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { createCheckoutSession } from "@/lib/actions/billing";

export type QuotaKind = "tests" | "sites" | "seats";

export type QuotaExhaustedDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  kind: QuotaKind;
  used: number;
  limit: number;
  plan: string;
};

const SUGGESTED_TIER: Record<string, BillablePlan> = {
  free: "starter",
  starter: "pro",
  pro: "business",
  business: "business",
  enterprise: "business",
};

const TIER_LABEL: Record<BillablePlan, string> = {
  starter: "Starter",
  pro: "Pro",
  business: "Business",
};

export function QuotaExhaustedDialog(props: QuotaExhaustedDialogProps) {
  const t = useTranslations("Quota");
  const tBilling = useTranslations("Settings.billing");
  const [isPending, startTransition] = useTransition();
  const suggested = SUGGESTED_TIER[props.plan] ?? "starter";
  const tier = TIER_LABEL[suggested];

  function onUpgrade() {
    startTransition(async () => {
      try {
        const { url } = await createCheckoutSession({
          plan: suggested,
          interval: "month",
          currency: "eur",
        });
        window.location.href = url;
      } catch {
        toast.error(tBilling("checkoutError"));
      }
    });
  }

  return (
    <Dialog open={props.open} onOpenChange={props.onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t(`exhausted.${props.kind}.title`)}</DialogTitle>
          <DialogDescription>
            {t(`exhausted.${props.kind}.description`, {
              used: props.used,
              limit: props.limit,
              plan: props.plan,
              tier,
            })}
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button variant="outline" onClick={() => props.onOpenChange(false)} disabled={isPending}>
            {t("close")}
          </Button>
          <Button onClick={onUpgrade} disabled={isPending}>
            {tBilling("ctaUpgrade", { tier })}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
