"use client";

import { useState } from "react";
import { CreditCard, ExternalLink } from "lucide-react";
import { Button } from "@/components/ui";
import type { Locale } from "@/lib/i18n";

const labels = {
  en: {
    redirecting: "Redirecting to Stripe...",
    openingPortal: "Opening portal...",
    checkoutError: "Stripe checkout failed.",
    portalError: "Stripe portal failed."
  },
  ar: {
    redirecting: "جاري التحويل إلى Stripe...",
    openingPortal: "جاري فتح بوابة Stripe...",
    checkoutError: "فشل إنشاء جلسة Stripe.",
    portalError: "فشل فتح بوابة Stripe."
  }
} as const;

export function CheckoutButton({
  priceId,
  children,
  disabled = false,
  disabledReason,
  locale
}: {
  priceId: string;
  children: React.ReactNode;
  disabled?: boolean;
  disabledReason?: string;
  locale: Locale;
}) {
  const [loading, setLoading] = useState(false);
  const t = labels[locale];

  async function checkout() {
    if (disabled) {
      if (disabledReason) alert(disabledReason);
      return;
    }

    setLoading(true);
    try {
      const response = await fetch("/api/billing/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ priceId })
      });
      const body = (await response.json()) as { url?: string; error?: string };
      if (body.url) window.location.href = body.url;
      if (body.error) alert(body.error);
    } catch {
      alert(t.checkoutError);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Button onClick={checkout} disabled={loading || disabled} title={disabledReason}>
      <CreditCard size={16} />
      {loading ? t.redirecting : children}
    </Button>
  );
}

export function PortalButton({ disabled = false, disabledReason, locale }: { disabled?: boolean; disabledReason?: string; locale: Locale }) {
  const [loading, setLoading] = useState(false);
  const t = labels[locale];

  async function openPortal() {
    if (disabled) {
      if (disabledReason) alert(disabledReason);
      return;
    }

    setLoading(true);
    try {
      const response = await fetch("/api/billing/portal", { method: "POST" });
      const body = (await response.json()) as { url?: string; error?: string };
      if (body.url) window.location.href = body.url;
      if (body.error) alert(body.error);
    } catch {
      alert(t.portalError);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Button variant="secondary" onClick={openPortal} disabled={loading || disabled} title={disabledReason}>
      <ExternalLink size={16} />
      {loading ? t.openingPortal : locale === "ar" ? "إدارة الاشتراك" : "Manage subscription"}
    </Button>
  );
}
