"use client";

import { useMemo } from "react";
import { useLocale, useTranslations } from "next-intl";
import { Check, Loader2, Minus, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatCurrency, formatNumber } from "@/lib/format";
import { useAuthStore } from "@/lib/stores/auth.store";
import {
  UNLIMITED,
  featureDisplayName,
  planDisplayName,
  usePlatformFeaturesCatalog,
  usePlatformPlans,
  type PlanLimits,
  type PlatformPlan,
} from "@/lib/api/platform-plans";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

/** Limit rows shown at the top of the comparison, in display order. */
// NOTE: no SMS row — marketing SMS is bring-your-own-provider, not a plan limit.
const LIMIT_ROWS: { key: keyof PlanLimits; zeroAsDash?: boolean }[] = [
  { key: "maxOrdersPerDay" },
  { key: "maxBranches" },
  { key: "maxTerminals" },
  { key: "maxTables" },
  { key: "maxCustomers" },
  { key: "maxMenuItems" },
  { key: "maxReportHistoryDays" },
  { key: "maxMenuAi3dPerMonth", zeroAsDash: true },
];

function LimitCell({
  value,
  zeroAsDash,
  unlimitedLabel,
  numberLocale,
}: {
  value: number;
  zeroAsDash?: boolean;
  unlimitedLabel: string;
  numberLocale: string;
}) {
  if (value >= UNLIMITED) {
    return <span className="text-sm font-medium text-[#0F6E56]">{unlimitedLabel}</span>;
  }
  if (value === 0 && zeroAsDash) {
    return <Minus className="mx-auto h-5 w-5 text-muted-foreground/50" aria-hidden />;
  }
  return (
    <span className="text-sm font-medium">{formatNumber(value, numberLocale)}</span>
  );
}

function BoolCell({ value }: { value: boolean }) {
  return value ? (
    <Check className="mx-auto h-5 w-5 text-[#0F6E56]" aria-hidden />
  ) : (
    <X className="mx-auto h-5 w-5 text-muted-foreground/50" aria-hidden />
  );
}

function PriceLine({
  plan,
  t,
  numberLocale,
}: {
  plan: PlatformPlan;
  t: ReturnType<typeof useTranslations<"settings.plans">>;
  numberLocale: string;
}) {
  if (plan.monthlyPriceToman === 0 && !plan.isBillableOnline && plan.tier !== "Free") {
    return <>{t("customPrice")}</>;
  }
  if (plan.monthlyPriceToman === 0) {
    return <>{t("freePrice")}</>;
  }
  return <>{formatCurrency(plan.monthlyPriceToman, numberLocale)}</>;
}

type PlanComparisonProps = {
  currentPlan?: string;
  onSubscribe: (planTier: string) => void;
  isSubscribing?: boolean;
};

/**
 * Live plan comparison — plans, prices, limits and features all come from the
 * admin-editable platform catalog (`/platform/plans` + `/platform/features-catalog`),
 * so this table never drifts from what billing actually enforces.
 */
export function PlanComparison({
  currentPlan = "Free",
  onSubscribe,
  isSubscribing = false,
}: PlanComparisonProps) {
  const t = useTranslations("settings.plans");
  const tSettings = useTranslations("settings");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);

  const { data: plans = [], isLoading: plansLoading } = usePlatformPlans(cafeId);
  const { data: catalog = [] } = usePlatformFeaturesCatalog(cafeId);

  // Only catalog features that at least one plan includes — hides retired keys.
  const featureRows = useMemo(() => {
    const used = new Set(plans.flatMap((p) => p.featureKeys));
    return catalog.filter((f) => f.isEnabledGlobally && used.has(f.key));
  }, [plans, catalog]);

  const popularTier = useMemo(() => {
    // "Popular" = the cheapest online-billable paid plan above Free.
    const billable = plans.filter((p) => p.isBillableOnline && p.monthlyPriceToman > 0);
    return billable.length > 0 ? billable[0]!.tier : null;
  }, [plans]);

  if (plansLoading) {
    return (
      <div className="flex items-center justify-center rounded-xl border border-border/80 bg-card py-12 text-muted-foreground">
        <Loader2 className="size-5 animate-spin" />
      </div>
    );
  }
  if (plans.length === 0) return null;

  const gridCols = `28%_repeat(${plans.length},minmax(0,1fr))`;

  return (
    <section className="relative z-0 mb-8 space-y-4 scroll-mt-6">
      <div>
        <p className="text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
          {t("compareLabel")}
        </p>
        <h3 className="text-lg font-medium text-foreground">{tSettings("upgrade")}</h3>
        <p className="mt-1 text-sm text-muted-foreground">{t("compareHint")}</p>
      </div>

      {/* Desktop comparison table */}
      <div className="relative z-0 mb-2 hidden overflow-hidden rounded-xl border border-border/80 bg-card shadow-sm lg:block">
        <div className="overflow-x-auto overscroll-x-contain">
          <div className="min-w-[720px] px-2 pb-2 pt-4">
            <table className="w-full border-collapse text-center text-sm">
              <thead>
                <tr className="border-b border-border/80">
                  <th className="w-[28%] bg-muted/30 px-4 pb-4 pt-2 text-start text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
                    {t("featureColumn")}
                  </th>
                  {plans.map((plan) => {
                    const isCurrent = plan.tier === currentPlan;
                    const isPopular = plan.tier === popularTier;
                    return (
                      <th
                        key={plan.tier}
                        className={cn(
                          "px-3 pb-4 pt-2 align-top",
                          isPopular && "bg-[#E1F5EE]/60",
                          isCurrent && "ring-2 ring-inset ring-[#0F6E56]/40"
                        )}
                      >
                        <div className="flex flex-col items-center gap-2">
                          <div className="flex min-h-[1.375rem] flex-wrap items-center justify-center gap-1.5">
                            {isPopular ? (
                              <Badge className="whitespace-nowrap border-[#0F6E56]/30 bg-[#0F6E56] px-2.5 py-0.5 text-[10px] text-white hover:bg-[#0F6E56]">
                                {t("popular")}
                              </Badge>
                            ) : null}
                            {isCurrent ? (
                              <Badge
                                variant="outline"
                                className="whitespace-nowrap border-[#0F6E56]/30 bg-white px-2.5 py-0.5 text-[10px] text-[#0F6E56]"
                              >
                                {t("current")}
                              </Badge>
                            ) : null}
                          </div>
                          <div className="text-base font-semibold text-foreground">
                            {planDisplayName(plan, locale)}
                          </div>
                          <p className="font-medium text-[#0F6E56]">
                            <PriceLine plan={plan} t={t} numberLocale={numberLocale} />
                          </p>
                          <p className="text-[11px] text-muted-foreground">{t("perMonth")}</p>
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {LIMIT_ROWS.map((row, idx) => (
                  <tr
                    key={row.key}
                    className={cn(
                      "border-b border-border/60",
                      idx % 2 === 0 ? "bg-background" : "bg-muted/20"
                    )}
                  >
                    <td className="px-4 py-3 text-start text-sm text-foreground">
                      {t(`limits.${row.key}`)}
                    </td>
                    {plans.map((plan) => (
                      <td
                        key={plan.tier}
                        className={cn(
                          "px-3 py-3",
                          plan.tier === popularTier && "bg-[#E1F5EE]/30",
                          plan.tier === currentPlan && "bg-[#E1F5EE]/50"
                        )}
                      >
                        <LimitCell
                          value={plan.limits[row.key]}
                          zeroAsDash={row.zeroAsDash}
                          unlimitedLabel={t("unlimited")}
                          numberLocale={numberLocale}
                        />
                      </td>
                    ))}
                  </tr>
                ))}
                {featureRows.map((feature, idx) => (
                  <tr
                    key={feature.key}
                    className={cn(
                      "border-b border-border/60",
                      (LIMIT_ROWS.length + idx) % 2 === 0 ? "bg-background" : "bg-muted/20"
                    )}
                  >
                    <td className="px-4 py-3 text-start text-sm text-foreground">
                      {featureDisplayName(feature, locale)}
                    </td>
                    {plans.map((plan) => (
                      <td
                        key={plan.tier}
                        className={cn(
                          "px-3 py-3",
                          plan.tier === popularTier && "bg-[#E1F5EE]/30",
                          plan.tier === currentPlan && "bg-[#E1F5EE]/50"
                        )}
                      >
                        <BoolCell value={plan.featureKeys.includes(feature.key)} />
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="overflow-x-auto overscroll-x-contain border-t border-border/80 bg-muted/10">
          <div
            className="grid min-w-[720px] items-center gap-0 px-2 py-5"
            style={{ gridTemplateColumns: gridCols.replace(/_/g, " ") }}
          >
            <div className="px-4" aria-hidden />
            {plans.map((plan) => (
              <div
                key={plan.tier}
                className={cn(
                  "px-3",
                  plan.tier === popularTier && "bg-[#E1F5EE]/30",
                  plan.tier === currentPlan && "bg-[#E1F5EE]/50"
                )}
              >
                <PlanCta
                  plan={plan}
                  locale={locale}
                  currentPlan={currentPlan}
                  onSubscribe={onSubscribe}
                  isSubscribing={isSubscribing}
                  t={t}
                  fullWidth
                />
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Mobile plan cards */}
      <div className="grid gap-4 lg:hidden">
        {plans.map((plan) => {
          const isCurrent = plan.tier === currentPlan;
          const isPopular = plan.tier === popularTier;
          return (
            <article
              key={plan.tier}
              className={cn(
                "relative rounded-xl border bg-card p-4 shadow-sm",
                isPopular ? "border-[#0F6E56] ring-1 ring-[#0F6E56]/30" : "border-border/80",
                isCurrent && "ring-2 ring-[#0F6E56]/50"
              )}
            >
              <div className="mb-3 flex flex-wrap items-center gap-2">
                <h4 className="text-base font-semibold">{planDisplayName(plan, locale)}</h4>
                {isPopular && (
                  <Badge className="bg-[#0F6E56] text-white hover:bg-[#0F6E56]">
                    {t("popular")}
                  </Badge>
                )}
                {isCurrent && (
                  <Badge variant="outline" className="border-[#0F6E56]/30 text-[#0F6E56]">
                    {t("current")}
                  </Badge>
                )}
              </div>
              <p className="mb-4 text-lg font-medium text-[#0F6E56]">
                <PriceLine plan={plan} t={t} numberLocale={numberLocale} />
                {plan.monthlyPriceToman > 0 && (
                  <span className="ms-1 text-xs font-normal text-muted-foreground">
                    {t("perMonth")}
                  </span>
                )}
              </p>
              <ul className="mb-4 space-y-2 border-t border-border/60 pt-3">
                {LIMIT_ROWS.map((row) => (
                  <li
                    key={row.key}
                    className="flex items-center justify-between gap-2 text-sm"
                  >
                    <span className="text-muted-foreground">{t(`limits.${row.key}`)}</span>
                    <LimitCell
                      value={plan.limits[row.key]}
                      zeroAsDash={row.zeroAsDash}
                      unlimitedLabel={t("unlimited")}
                      numberLocale={numberLocale}
                    />
                  </li>
                ))}
                {featureRows.map((feature) => (
                  <li
                    key={feature.key}
                    className="flex items-center justify-between gap-2 text-sm"
                  >
                    <span className="text-muted-foreground">
                      {featureDisplayName(feature, locale)}
                    </span>
                    <BoolCell value={plan.featureKeys.includes(feature.key)} />
                  </li>
                ))}
              </ul>
              <PlanCta
                plan={plan}
                locale={locale}
                currentPlan={currentPlan}
                onSubscribe={onSubscribe}
                isSubscribing={isSubscribing}
                t={t}
                fullWidth
              />
            </article>
          );
        })}
      </div>
    </section>
  );
}

function PlanCta({
  plan,
  locale,
  currentPlan,
  onSubscribe,
  isSubscribing,
  t,
  fullWidth,
}: {
  plan: PlatformPlan;
  locale: string;
  currentPlan: string;
  onSubscribe: (planTier: string) => void;
  isSubscribing: boolean;
  t: ReturnType<typeof useTranslations<"settings.plans">>;
  fullWidth?: boolean;
}) {
  const isCurrent = plan.tier === currentPlan;

  if (plan.monthlyPriceToman === 0 && plan.tier === "Free") {
    return (
      <Button variant="outline" disabled className={fullWidth ? "w-full" : ""} size="sm">
        {isCurrent ? t("currentPlanBtn") : t("included")}
      </Button>
    );
  }

  if (!plan.isBillableOnline) {
    return (
      <Button variant="outline" className={fullWidth ? "w-full" : ""} size="sm" asChild>
        <a href="mailto:sales@meezi.ir">{t("contactSales")}</a>
      </Button>
    );
  }

  if (isCurrent) {
    return (
      <Button variant="secondary" disabled className={fullWidth ? "w-full" : ""} size="sm">
        {t("currentPlanBtn")}
      </Button>
    );
  }

  return (
    <Button
      className={cn("bg-[#0F6E56] hover:bg-[#0c5a46]", fullWidth ? "w-full" : "")}
      size="sm"
      disabled={isSubscribing}
      onClick={() => onSubscribe(plan.tier)}
    >
      {t("subscribe", { plan: planDisplayName(plan, locale) })}
    </Button>
  );
}
