"use client";

import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useRouter } from "@/i18n/routing";
import { apiGet, apiPost } from "@/lib/api/client";
import { isCafeOwner } from "@/lib/auth-permissions";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { PageHeader } from "@/components/layout/page-header";
import { PlanComparison } from "@/components/settings/plan-comparison";
import type { AuthTokenResponse } from "@/lib/api/types";
import { Alert } from "@/components/ui/alert";
import { notify } from "@/lib/notify";

type BillingStatus = {
  planTier: string;
  planExpiresAt: string | null;
  ordersToday: number;
  ordersDailyLimit: number | null;
  customersCount: number;
  customersLimit: number | null;
  smsUsedThisMonth: number;
  smsMonthlyLimit: number;
  menu3dEnabled: boolean;
  discoverProfileEnabled: boolean;
  isPlanExpired: boolean;
};

export function SubscriptionScreen() {
  const t = useTranslations("subscription");
  const tSettings = useTranslations("settings");
  const searchParams = useSearchParams();
  const router = useRouter();
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const role = useAuthStore((s) => s.user?.role);
  const setAuth = useAuthStore((s) => s.setAuth);
  const billingRefreshed = useRef(false);
  const [billingBanner, setBillingBanner] = useState<"success" | "failed" | null>(null);

  useEffect(() => {
    const billing = searchParams.get("billing");
    if (billing === "success") {
      notify.success(t("paymentSuccess"));
      setBillingBanner("success");
    }
    if (billing === "failed") {
      notify.error(t("paymentFailed"));
      setBillingBanner("failed");
    }
  }, [searchParams, t]);

  const { data: status, isLoading, refetch } = useQuery({
    queryKey: ["billing-status", cafeId],
    queryFn: () => apiGet<BillingStatus>("/api/billing/status"),
    enabled: !!cafeId,
  });

  useEffect(() => {
    if (searchParams.get("billing") !== "success" || billingRefreshed.current) return;
    const refresh = localStorage.getItem("meezi_refresh_token");
    if (!refresh) return;
    billingRefreshed.current = true;
    apiPost<AuthTokenResponse>("/api/auth/refresh", { refreshToken: refresh })
      .then((tokens) => {
        setAuth(tokens);
        refetch();
      })
      .catch(() => notify.warning(tSettings("profile.reloginHint")));
  }, [searchParams, setAuth, refetch, tSettings]);

  if (!cafeId) return null;

  if (!isCafeOwner(role)) {
    return (
      <div className="space-y-6">
        <PageHeader title={t("title")} subtitle={t("subtitle")} />
        <p className="text-sm text-muted-foreground">{t("ownerOnly")}</p>
      </div>
    );
  }

  const expiry = status?.planExpiresAt
    ? new Date(status.planExpiresAt).toLocaleDateString("fa-IR")
    : t("noExpiry");

  return (
    <div className="space-y-6">
      <PageHeader title={t("title")} subtitle={t("subtitle")} />

      {billingBanner ? (
        <Alert
          variant={billingBanner === "failed" ? "destructive" : "success"}
          onDismiss={() => setBillingBanner(null)}
        >
          {billingBanner === "failed" ? t("paymentFailed") : t("paymentSuccess")}
        </Alert>
      ) : null}

      <Card className="rounded-xl border border-border/80 shadow-sm">
        <CardHeader>
          <CardTitle className="text-base">{t("currentPlan")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {isLoading ? (
            <p className="text-sm text-muted-foreground">{t("loading")}</p>
          ) : status ? (
            <>
              <div className="flex flex-wrap items-center gap-2">
                <Badge>{status.planTier}</Badge>
                {status.isPlanExpired ? (
                  <Badge className="bg-[#A32D2D] text-white hover:bg-[#A32D2D]">
                    {t("planExpired")}
                  </Badge>
                ) : null}
                <span className="text-sm text-muted-foreground">
                  {t("expires")}: {expiry}
                </span>
                <Button size="sm" variant="ghost" onClick={() => refetch()}>
                  {t("refresh")}
                </Button>
              </div>
              <ul className="space-y-1 text-sm text-muted-foreground">
                <li>
                  {t("ordersToday")}: {formatNumber(status.ordersToday)}
                  {status.ordersDailyLimit != null &&
                    ` / ${formatNumber(status.ordersDailyLimit)}`}
                </li>
                <li>
                  {t("customers")}: {formatNumber(status.customersCount)}
                  {status.customersLimit != null &&
                    ` / ${formatNumber(status.customersLimit)}`}
                </li>
                <li>
                  {t("smsUsage")}: {formatNumber(status.smsUsedThisMonth)}
                  {status.smsMonthlyLimit >= 0 &&
                    ` / ${formatNumber(status.smsMonthlyLimit)}`}
                </li>
                <li>
                  {t("featureMenu3d")}:{" "}
                  {status.menu3dEnabled ? t("featureOn") : t("featureOff")}
                </li>
                <li>
                  {t("featureDiscover")}:{" "}
                  {status.discoverProfileEnabled ? t("featureOn") : t("featureOff")}
                </li>
              </ul>
            </>
          ) : null}
        </CardContent>
      </Card>

      <PlanComparison
        currentPlan={status?.planTier ?? "Free"}
        onSubscribe={(planTier) =>
          router.push(`/subscription/checkout?plan=${planTier}`)
        }
      />
    </div>
  );
}
