import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";
import { PageHeader } from "../components/layout/PageHeader";
import { PlanPricingGrid } from "../components/usage/PlanPricingGrid";
import { useRepos } from "../data/DataContext";
import { useI18n } from "../i18n/I18nContext";
import { billingErrorMessage, isSafeBillingUrl, startBillingRedirect } from "../lib/billingCheckout";
import { getPlanRights } from "../lib/planRights";
import type { PlanId } from "../lib/usageMeter";
import { PLANS } from "../lib/usageMeter";

/**
 * 變更方案：標準 SaaS 比價頁 → 結帳。
 */
export function PlansPage() {
  const repos = useRepos();
  const { member } = useAuth();
  const { t, formatPlanPrice } = useI18n();
  const navigate = useNavigate();
  const [currentId, setCurrentId] = useState<PlanId | null>(null);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [redirecting, setRedirecting] = useState(false);

  useEffect(() => {
    void repos.usage
      .getBillingSubscription()
      .then((subscription) => {
        setCurrentId(subscription.plan_id);
        setError("");
      })
      .catch((e: unknown) => setError(billingErrorMessage(e, t, "plans.loadFail")));
  }, [repos.usage, t]);

  if (!member) return null;

  async function openPortal() {
    setBusy(true);
    setError("");
    try {
      const portal = await repos.usage.createBillingPortalSession();
      if (!isSafeBillingUrl(portal.url)) {
        setError(t("checkout.invalidUrl"));
        setBusy(false);
        return;
      }
      setRedirecting(true);
      startBillingRedirect(
        () => window.location.assign(portal.url),
        () => {
          setRedirecting(false);
          setBusy(false);
          setError(t("checkout.redirectFailed"));
        },
      );
    } catch (e) {
      setError(billingErrorMessage(e, t, "checkout.fail"));
      setBusy(false);
    }
  }

  function choosePlan(id: PlanId) {
    if (!currentId) return;
    if ((id === "free" && currentId !== "free") || (id === currentId && id !== "free")) {
      void openPortal();
      return;
    }
    if (id !== currentId) navigate(`/app/usage/checkout?plan=${id}`);
  }

  if (!currentId) {
    return (
      <>
        <PageHeader title={t("plans.title")} />
        {error ? (
          <p className="hb-form-error" role="alert">{error}</p>
        ) : (
          <p className="text-muted">{t("common.loading")}</p>
        )}
      </>
    );
  }

  const current = currentId;
  const currentRights = getPlanRights(current, t, formatPlanPrice);

  return (
    <>
      <PageHeader title={t("plans.title")} />

      {error ? <p className="hb-form-error" role="alert">{error}</p> : null}
      {redirecting ? <p role="status">{t("checkout.redirectingPortal")}</p> : null}

      <div className="hb-stack hb-plans-page">
        <div className="hb-plans-page__current">
          <span className="text-muted">{t("plans.current")}</span>
          <strong>{PLANS[current].name}</strong>
          <span className="text-muted">
            {formatPlanPrice(PLANS[current].price_twd)}
            {t("plans.perMonth")}
          </span>
          <span className="text-muted">
            {t("plans.monthlyCredits", { n: PLANS[current].monthly_credits })}
          </span>
          <span className="text-muted hb-plans-page__caps">{currentRights.approxCallsLine}</span>
          <Link to="/app/usage" className="hb-plans-page__back">
            {t("plans.usageLink")}
          </Link>
        </div>

        <PlanPricingGrid
          currentId={current}
          busy={busy}
          formatPrice={formatPlanPrice}
          onChoose={choosePlan}
        />
      </div>
    </>
  );
}
