"use client";

import { useTranslations } from "next-intl";
import { Check, Minus, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatCurrency, formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

export type PlanId = "Free" | "Pro" | "Business" | "Enterprise";

export const PLAN_ORDER: PlanId[] = ["Free", "Pro", "Business", "Enterprise"];

export const PRICES: Record<PlanId, number | null> = {
  Free: 0,
  Pro: 1_490_000,
  Business: 3_490_000,
  Enterprise: null,
};

type CellValue =
  | { kind: "bool"; value: boolean }
  | { kind: "limit"; value: number | null }
  | { kind: "text"; value: string };

type FeatureRow = {
  key: string;
  cells: Record<PlanId, CellValue>;
};

const FEATURE_MATRIX: FeatureRow[] = [
  {
    key: "ordersPerDay",
    cells: {
      Free: { kind: "limit", value: 50 },
      Pro: { kind: "limit", value: null },
      Business: { kind: "limit", value: null },
      Enterprise: { kind: "limit", value: null },
    },
  },
  {
    key: "terminals",
    cells: {
      Free: { kind: "limit", value: 1 },
      Pro: { kind: "limit", value: 3 },
      Business: { kind: "limit", value: null },
      Enterprise: { kind: "limit", value: null },
    },
  },
  {
    key: "crmCustomers",
    cells: {
      Free: { kind: "limit", value: 50 },
      Pro: { kind: "limit", value: null },
      Business: { kind: "limit", value: null },
      Enterprise: { kind: "limit", value: null },
    },
  },
  {
    key: "smsPerMonth",
    cells: {
      Free: { kind: "limit", value: 0 },
      Pro: { kind: "limit", value: 50 },
      Business: { kind: "limit", value: 200 },
      Enterprise: { kind: "limit", value: null },
    },
  },
  {
    key: "branches",
    cells: {
      Free: { kind: "limit", value: 1 },
      Pro: { kind: "limit", value: 1 },
      Business: { kind: "limit", value: 5 },
      Enterprise: { kind: "limit", value: null },
    },
  },
  {
    key: "posKds",
    cells: {
      Free: { kind: "bool", value: true },
      Pro: { kind: "bool", value: true },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "tablesQr",
    cells: {
      Free: { kind: "bool", value: true },
      Pro: { kind: "bool", value: true },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "menuReservations",
    cells: {
      Free: { kind: "bool", value: true },
      Pro: { kind: "bool", value: true },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "reports",
    cells: {
      Free: { kind: "text", value: "basic" },
      Pro: { kind: "text", value: "full" },
      Business: { kind: "text", value: "full" },
      Enterprise: { kind: "text", value: "full" },
    },
  },
  {
    key: "hrModule",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: false },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "snappfoodDelivery",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: false },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "tarazTax",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: true },
      Business: { kind: "bool", value: true },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "badges",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: false },
      Business: { kind: "bool", value: false },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "whiteLabel",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: false },
      Business: { kind: "bool", value: false },
      Enterprise: { kind: "bool", value: true },
    },
  },
  {
    key: "apiAccess",
    cells: {
      Free: { kind: "bool", value: false },
      Pro: { kind: "bool", value: false },
      Business: { kind: "bool", value: false },
      Enterprise: { kind: "bool", value: true },
    },
  },
];

function CellDisplay({
  cell,
  t,
  numberLocale,
}: {
  cell: CellValue;
  t: ReturnType<typeof useTranslations<"settings.plans">>;
  numberLocale: string;
}) {
  if (cell.kind === "bool") {
    return cell.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 />
    );
  }
  if (cell.kind === "limit") {
    if (cell.value === null) {
      return (
        <span className="text-sm font-medium text-[#0F6E56]">{t("unlimited")}</span>
      );
    }
    if (cell.value === 0) {
      return <Minus className="mx-auto h-5 w-5 text-muted-foreground/50" aria-hidden />;
    }
    return (
      <span className="text-sm font-medium">{formatNumber(cell.value, numberLocale)}</span>
    );
  }
  return (
    <span className="text-xs font-medium text-muted-foreground">
      {t(`levels.${cell.value}`)}
    </span>
  );
}

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

export function PlanComparison({
  currentPlan = "Free",
  onSubscribe,
  isSubscribing = false,
}: PlanComparisonProps) {
  const t = useTranslations("settings.plans");
  const tSettings = useTranslations("settings");
  const numberLocale =
    typeof document !== "undefined" && document.documentElement.lang === "en"
      ? "en-US"
      : "fa-IR";

  const normalizedCurrent = currentPlan as PlanId;

  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 — badges in-flow; CTAs outside scroll clip */}
      <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>
                  {PLAN_ORDER.map((plan) => {
                    const isCurrent = plan === normalizedCurrent;
                    const isPopular = plan === "Pro";
                    return (
                      <th
                        key={plan}
                        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">
                            {t(`names.${plan}`)}
                          </div>
                          <p className="font-medium text-[#0F6E56]">
                            {PRICES[plan] === null
                              ? t("customPrice")
                              : PRICES[plan] === 0
                                ? t("freePrice")
                                : formatCurrency(PRICES[plan]!, numberLocale)}
                          </p>
                          <p className="text-[11px] text-muted-foreground">{t("perMonth")}</p>
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {FEATURE_MATRIX.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(`features.${row.key}`)}
                    </td>
                    {PLAN_ORDER.map((plan) => (
                      <td
                        key={plan}
                        className={cn(
                          "px-3 py-3",
                          plan === "Pro" && "bg-[#E1F5EE]/30",
                          plan === normalizedCurrent && "bg-[#E1F5EE]/50"
                        )}
                      >
                        <CellDisplay
                          cell={row.cells[plan]}
                          t={t}
                          numberLocale={numberLocale}
                        />
                      </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] grid-cols-[28%_repeat(4,minmax(0,1fr))] items-center gap-0 px-2 py-5">
            <div className="px-4" aria-hidden />
            {PLAN_ORDER.map((plan) => (
              <div
                key={plan}
                className={cn(
                  "px-3",
                  plan === "Pro" && "bg-[#E1F5EE]/30",
                  plan === normalizedCurrent && "bg-[#E1F5EE]/50"
                )}
              >
                <PlanCta
                  plan={plan}
                  currentPlan={normalizedCurrent}
                  onSubscribe={onSubscribe}
                  isSubscribing={isSubscribing}
                  t={t}
                  fullWidth
                />
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Mobile plan cards */}
      <div className="grid gap-4 lg:hidden">
        {PLAN_ORDER.map((plan) => {
          const isCurrent = plan === normalizedCurrent;
          const isPopular = plan === "Pro";
          return (
            <article
              key={plan}
              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">{t(`names.${plan}`)}</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]">
                {PRICES[plan] === null
                  ? t("customPrice")
                  : PRICES[plan] === 0
                    ? t("freePrice")
                    : formatCurrency(PRICES[plan]!, numberLocale)}
                {PRICES[plan] !== null && PRICES[plan]! > 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">
                {FEATURE_MATRIX.map((row) => (
                  <li
                    key={row.key}
                    className="flex items-center justify-between gap-2 text-sm"
                  >
                    <span className="text-muted-foreground">{t(`features.${row.key}`)}</span>
                    <CellDisplay
                      cell={row.cells[plan]}
                      t={t}
                      numberLocale={numberLocale}
                    />
                  </li>
                ))}
              </ul>
              <PlanCta
                plan={plan}
                currentPlan={normalizedCurrent}
                onSubscribe={onSubscribe}
                isSubscribing={isSubscribing}
                t={t}
                fullWidth
              />
            </article>
          );
        })}
      </div>
    </section>
  );
}

function PlanCta({
  plan,
  currentPlan,
  onSubscribe,
  isSubscribing,
  t,
  fullWidth,
}: {
  plan: PlanId;
  currentPlan: PlanId;
  onSubscribe: (planTier: "Pro" | "Business") => void;
  isSubscribing: boolean;
  t: ReturnType<typeof useTranslations<"settings.plans">>;
  fullWidth?: boolean;
}) {
  const isCurrent = plan === currentPlan;

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

  if (plan === "Enterprise") {
    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)}
    >
      {t("subscribe", { plan: t(`names.${plan}`) })}
    </Button>
  );
}
