"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState, type ReactElement, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
  AlertTriangle,
  ClipboardList,
  Diamond,
  FileSearch,
  RefreshCw,
  ScrollText,
  Shield,
  Ticket,
  Wallet,
} from "lucide-react";

import { getAdminDashboard } from "@/api/admin-dashboard";
import { useAdminPlayTypeCatalog } from "@/hooks/use-admin-play-type-catalog";
import { getAdminPlayTypes } from "@/api/admin-config";
import {
  getAdminPlayTypesLoadPromise,
  getCachedAdminPlayTypes,
  resolveAdminPlayTypeDisplayName,
} from "@/lib/admin-play-types";
import { DashboardAnalyticsPanel } from "@/modules/dashboard/dashboard-analytics-panel";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
  CapUsageBar,
  FinanceStructureChart,
  HotUsageBars,
  PayoutCompositionChart,
  ResultBatchProgress,
  SettlementStatusChart,
  SoldOutRing,
} from "@/modules/dashboard/dashboard-visuals";
import { useAdminCurrencyCatalog } from "@/hooks/use-admin-currency-catalog";
import { adminWeekdayKeyForDate, formatAdminCalendarToday } from "@/lib/admin-datetime";
import { normalizeAdminLanguage } from "@/i18n";
import { formatAdminMinorUnits, getAdminCurrencyDecimalPlaces } from "@/lib/money";
import { cn } from "@/lib/utils";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDashboardDrawPanel } from "@/types/api/admin-dashboard";
import type { AdminDrawFinanceSummaryData } from "@/types/api/admin-draw-finance";
import type { AdminRiskPoolRow } from "@/types/api/admin-risk";
import type { DrawCurrentSnapshot } from "@/types/api/public-draw";

type HotPlayTab = "4D" | "3D" | "2D" | "special";

type SoldOutBuckets = {
  d4: number;
  d3: number;
  d2: number;
  special: number;
  other: number;
};

function formatMoneyMinor(minor: number, currencyCode: string | null): string {
  const code = (currencyCode ?? "NPR").toUpperCase();
  const decimals = getAdminCurrencyDecimalPlaces(code);
  const major = minor / 10 ** decimals;
  try {
    return new Intl.NumberFormat("zh-CN", {
      style: "currency",
      currency: code,
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals,
    }).format(major);
  } catch {
    return formatAdminMinorUnits(minor, code, decimals);
  }
}

function poolPlayCategory(normalizedNumber: string): HotPlayTab | "other" {
  const raw = normalizedNumber.trim();
  const digits = raw.replace(/\D/g, "");
  const digitLen = digits.length;
  const hasLetter = /[A-Za-z]/.test(raw);

  if (hasLetter && digitLen < 3) {
    return "special";
  }
  if (digitLen >= 4) {
    return "4D";
  }
  if (digitLen === 3) {
    return "3D";
  }
  if (digitLen === 2) {
    return "2D";
  }
  if (hasLetter) {
    return "special";
  }
  return "other";
}

function topPoolsForTab(pools: AdminRiskPoolRow[], tab: HotPlayTab): AdminRiskPoolRow[] {
  return [...pools]
    .filter((p) => poolPlayCategory(p.normalized_number) === tab)
    .sort((a, b) => (b.usage_ratio ?? 0) - (a.usage_ratio ?? 0))
    .slice(0, 10);
}

export function DashboardConsole(): ReactElement {
  const { t, i18n } = useTranslation(["dashboard", "common"]);
  useAdminCurrencyCatalog();
  useAdminPlayTypeCatalog();
  const todayLabel = useMemo(() => {
    const locale = normalizeAdminLanguage(i18n.resolvedLanguage ?? i18n.language);
    const weekday = t(`date.weekdays.${adminWeekdayKeyForDate()}`, { ns: "common" });

    return formatAdminCalendarToday(locale, weekday);
  }, [i18n.language, i18n.resolvedLanguage, t]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [hall, setHall] = useState<DrawCurrentSnapshot | null>(null);
  const [drawId, setDrawId] = useState<number | null>(null);
  const [drawPanel, setDrawPanel] = useState<AdminDashboardDrawPanel | null>(null);
  const [finance, setFinance] = useState<AdminDrawFinanceSummaryData | null>(null);
  const [capabilities, setCapabilities] = useState<{ draw_finance_risk: boolean; wallet_transfer_view: boolean } | null>(null);
  const [pendingReview, setPendingReview] = useState<number | null>(null);
  const [riskLocked, setRiskLocked] = useState(0);
  const [riskCap, setRiskCap] = useState(0);
  const [hotPoolSample, setHotPoolSample] = useState<AdminRiskPoolRow[]>([]);
  const [soldOutBuckets, setSoldOutBuckets] = useState<SoldOutBuckets | null>(null);
  const [abnormalTransferTotal, setAbnormalTransferTotal] = useState<number | null>(null);
  const [hotTab, setHotTab] = useState<HotPlayTab>("4D");
  const [playOptions, setPlayOptions] = useState<{ code: string; label: string }[]>([]);

  const loadPlayOptions = useCallback(async () => {
    try {
      await getAdminPlayTypesLoadPromise(getAdminPlayTypes);
      setPlayOptions(
        getCachedAdminPlayTypes().map((item) => ({
          code: item.play_code,
          label:
            resolveAdminPlayTypeDisplayName(item.play_code, i18n.language, item) || item.play_code,
        })),
      );
    } catch {
      setPlayOptions([]);
    }
  }, [i18n.language]);

  useEffect(() => {
    void loadPlayOptions();
  }, [loadPlayOptions]);

  const load = useCallback(async (isRefresh = false) => {
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);
    setFinance(null);
    setCapabilities(null);
    setDrawPanel(null);
    setPendingReview(null);
    setDrawId(null);
    setRiskLocked(0);
    setRiskCap(0);
    setHotPoolSample([]);
    setSoldOutBuckets(null);
    setAbnormalTransferTotal(null);

    try {
      const d = await getAdminDashboard();
      setHall(d.hall);

      if (d.resolved_draw != null) {
        setDrawId(d.resolved_draw.id);
      }

      setCapabilities(d.capabilities);
      if (d.finance != null) {
        setFinance(d.finance);
      }
      if (d.draw != null) {
        setDrawPanel(d.draw);
        setPendingReview(d.draw.result_batch_counts.pending_review);
      }
      if (d.risk != null) {
        setRiskLocked(d.risk.locked_amount);
        setRiskCap(d.risk.cap_amount);
        setHotPoolSample(d.risk.hot_pool_rows);
        setSoldOutBuckets(d.risk.sold_out_buckets);
      }
      setAbnormalTransferTotal(d.abnormal_transfer_total);
    } catch (e) {
      const msg =
        e instanceof LotteryApiBizError ? e.message : t("warnings.loadFailed");
      setError(msg);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [t]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void load(false);
    }, 0);
    return () => window.clearTimeout(timer);
  }, [load]);

  const currency = finance?.currency_code ?? null;
  const canFinance = capabilities?.draw_finance_risk ?? false;
  const usagePct = riskCap > 0 ? (riskLocked / riskCap) * 100 : 0;

  const hotRows = useMemo(() => topPoolsForTab(hotPoolSample, hotTab), [hotPoolSample, hotTab]);

  const hallStatusLabel = hall?.status ?? "—";
  const isOpenLike =
    hallStatusLabel.toLowerCase().includes("open") ||
    hallStatusLabel.toLowerCase().includes("sale");

  const quickLinks: { href: string; label: string; icon: ReactNode }[] = [
    { href: "/admin/draws", label: t("quickLinks.createDrawPlan"), icon: <Diamond className="size-5" /> },
    { href: "/admin/draws", label: t("quickLinks.drawSchedule"), icon: <Ticket className="size-5" /> },
    {
      href: drawId != null ? `/admin/draws/${drawId}/results` : "/admin/draws",
      label: t("quickLinks.results"),
      icon: <FileSearch className="size-5" />,
    },
    { href: "/admin/tickets", label: t("quickLinks.tickets"), icon: <Shield className="size-5" /> },
    { href: "/admin/wallet/transactions", label: t("quickLinks.walletTransactions"), icon: <Wallet className="size-5" /> },
    { href: "/admin/audit-logs", label: t("quickLinks.auditLogs"), icon: <ScrollText className="size-5" /> },
  ];

  return (
    <div className="space-y-6 pb-10">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="text-2xl font-bold tracking-tight text-foreground">{t("title")}</h1>
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">{todayLabel}</span>
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={loading || refreshing}
            onClick={() => void load(true)}
          >
            <RefreshCw className={refreshing ? "size-4 animate-spin" : "size-4"} />
            {t("actions.refresh", { ns: "common" })}
          </Button>
        </div>
      </div>

      {error ? (
        <Alert className="border-amber-200 bg-amber-50 dark:border-amber-900/60 dark:bg-amber-950/30">
          <AlertTitle>{t("notice")}</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      ) : null}

      {!loading && capabilities && !capabilities.draw_finance_risk ? (
        <Alert className="border-amber-200 bg-amber-50 dark:border-amber-900/60 dark:bg-amber-950/30">
          <AlertTitle>{t("notice")}</AlertTitle>
          <AlertDescription>{t("warnings.drawPermission")}</AlertDescription>
        </Alert>
      ) : null}

      {!loading && hall ? (
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border/80 bg-card px-4 py-3 shadow-sm">
          <div className="flex flex-wrap items-center gap-3">
            <Ticket className="size-5 text-primary" aria-hidden />
            <div>
              <p className="text-xs text-muted-foreground">{t("sections.currentDraw")}</p>
              <p className="font-mono text-lg font-semibold text-foreground">{hall.draw_no}</p>
            </div>
            <span className="text-sm text-muted-foreground">
              {t("drawSequence", { sequence: hall.sequence_no ?? "—" })}
            </span>
            <span className="inline-flex items-center gap-1.5 text-sm">
              <span
                className={cn(
                  "size-1.5 rounded-full",
                  isOpenLike ? "bg-emerald-500" : "bg-muted-foreground",
                )}
              />
              {hallStatusLabel}
            </span>
          </div>
          {drawId != null ? (
            <Link
              href={`/admin/draws/${drawId}/finance`}
              className={cn(buttonVariants({ variant: "outline", size: "sm" }), "text-xs")}
            >
              {t("drawFinanceDetails")}
            </Link>
          ) : null}
        </div>
      ) : null}

      <DashboardAnalyticsPanel enabled={canFinance} playOptions={playOptions} />

      <h2 className="text-sm font-semibold tracking-wide text-muted-foreground">{t("sections.operations")}</h2>

      <div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
        <Card className="border-border/80 shadow-sm xl:col-span-1">
          <CardHeader className="pb-2">
            <CardTitle className="text-base">{t("financeStructure")}</CardTitle>
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-36 w-full" />
            ) : finance ? (
              <FinanceStructureChart finance={finance} formatMoney={formatMoneyMinor} />
            ) : (
              <p className="py-8 text-center text-sm text-muted-foreground">{t("states.noData", { ns: "common" })}</p>
            )}
          </CardContent>
        </Card>

        <Card className="border-border/80 shadow-sm xl:col-span-1">
          <CardHeader className="pb-2">
            <CardTitle className="text-base">{t("payoutComposition")}</CardTitle>
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-36 w-full" />
            ) : finance ? (
              <PayoutCompositionChart finance={finance} formatMoney={formatMoneyMinor} />
            ) : (
              <p className="py-8 text-center text-sm text-muted-foreground">{t("states.noData", { ns: "common" })}</p>
            )}
          </CardContent>
        </Card>

        <Card className="border-border/80 shadow-sm lg:col-span-2 xl:col-span-1">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-base">{t("riskCapUsage")}</CardTitle>
            {drawId != null ? (
              <Link
                href={`/admin/draws/${drawId}/risk/occupancy`}
                className={cn(
                  buttonVariants({ variant: "outline", size: "sm" }),
                  "h-7 px-2 text-xs",
                )}
              >
                {t("occupancyDetails")}
              </Link>
            ) : null}
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-24 w-full" />
            ) : (
              <CapUsageBar
                locked={riskLocked}
                cap={riskCap}
                usagePct={usagePct}
                formatMoney={formatMoneyMinor}
                currency={currency}
              />
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row flex-wrap items-end justify-between gap-2 space-y-0 pb-2">
            <CardTitle className="text-base">{t("hotNumbersTop10")}</CardTitle>
            <div className="flex items-center gap-2">
              <div role="tablist" aria-label={t("playDimension")} className="flex gap-1">
                {([
                  { value: "4D", label: t("tabs.4d") },
                  { value: "3D", label: t("tabs.3d") },
                  { value: "2D", label: t("tabs.2d") },
                  { value: "special", label: t("tabs.special") },
                ] as const).map((tab) => (
                  <button
                    key={tab.value}
                    type="button"
                    role="tab"
                    aria-selected={hotTab === tab.value}
                    className={cn(
                      "rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
                      hotTab === tab.value
                        ? "bg-primary text-primary-foreground"
                        : "text-muted-foreground hover:bg-muted",
                    )}
                    onClick={() => setHotTab(tab.value)}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>
              {drawId != null ? (
                <Link
                  href={`/admin/draws/${drawId}/risk/hot`}
                  className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 px-2 text-xs")}
                >
                  {t("actions.viewAll", { ns: "common" })}
                </Link>
              ) : null}
            </div>
          </CardHeader>
          <CardContent>
            {loading ? <Skeleton className="h-64 w-full" /> : <HotUsageBars rows={hotRows} />}
          </CardContent>
        </Card>

        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-base">{t("soldOutDistribution")}</CardTitle>
            {drawId != null ? (
              <Link
                href={`/admin/draws/${drawId}/risk/sold-out`}
                className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 px-2 text-xs")}
              >
                {t("actions.viewAll", { ns: "common" })}
              </Link>
            ) : null}
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-64 w-full" />
            ) : soldOutBuckets ? (
              <SoldOutRing buckets={soldOutBuckets} />
            ) : (
              <p className="py-10 text-center text-sm text-muted-foreground">{t("states.noData", { ns: "common" })}</p>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-base">{t("resultBatches")}</CardTitle>
            {drawId != null ? (
              <Link
                href={`/admin/draws/${drawId}`}
                className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 px-2 text-xs")}
              >
                {t("drawDetails")}
              </Link>
            ) : null}
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-28 w-full" />
            ) : drawPanel ? (
              <ResultBatchProgress draw={drawPanel} />
            ) : (
              <p className="py-6 text-center text-sm text-muted-foreground">{t("states.noData", { ns: "common" })}</p>
            )}
          </CardContent>
        </Card>

        <Card className="border-border/80 shadow-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-base">{t("settlementOverview")}</CardTitle>
            {drawId != null ? (
              <Link
                href="/admin/settlement-batches"
                className={cn(buttonVariants({ variant: "outline", size: "sm" }), "h-7 px-2 text-xs")}
              >
                {t("actions.viewAll", { ns: "common" })}
              </Link>
            ) : null}
          </CardHeader>
          <CardContent>
            {loading ? (
              <Skeleton className="h-28 w-full" />
            ) : finance ? (
              <SettlementStatusChart finance={finance} />
            ) : (
              <p className="py-6 text-center text-sm text-muted-foreground">{t("states.noData", { ns: "common" })}</p>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <div className="flex flex-col justify-between gap-4 rounded-xl border border-border/80 bg-card p-5 shadow-sm sm:flex-row sm:items-center">
          <div className="flex gap-4">
            <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-destructive text-destructive-foreground shadow-sm">
              <ClipboardList className="size-5" aria-hidden />
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">{t("pendingReviewResults")}</p>
              <p className="mt-1 text-4xl font-bold tabular-nums text-destructive">{pendingReview ?? "—"}</p>
            </div>
          </div>
          {drawId != null ? (
            <Link
              href={`/admin/draws/${drawId}/review`}
              className={cn(buttonVariants({ variant: "outline" }), "shrink-0")}
            >
              {t("actions.reviewNow", { ns: "common" })}
            </Link>
          ) : null}
        </div>
        <div className="flex flex-col justify-between gap-4 rounded-xl border border-border/80 bg-card p-5 shadow-sm sm:flex-row sm:items-center">
          <div className="flex gap-4">
            <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-amber-500 text-white shadow-sm">
              <AlertTriangle className="size-5" aria-hidden />
            </div>
            <div>
              <p className="text-sm font-medium text-muted-foreground">{t("abnormalTransferOrders")}</p>
              <p className="mt-1 text-4xl font-bold tabular-nums text-amber-600">{abnormalTransferTotal ?? "—"}</p>
            </div>
          </div>
          <Link
            href="/admin/wallet/transfer-orders"
            className={cn(buttonVariants({ variant: "outline" }), "shrink-0")}
          >
            {t("viewTransferOrders")}
          </Link>
        </div>
      </div>

      <Card className="border-border/80 shadow-sm">
        <CardHeader className="pb-2">
          <CardTitle className="text-base">{t("quickLinksTitle")}</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap justify-center gap-3 py-2 sm:gap-5">
          {quickLinks.map((q) => (
            <Link
              key={q.label}
              href={q.href}
              className="flex w-24 flex-col items-center gap-2 rounded-lg border border-transparent p-2 text-center text-xs font-medium text-foreground transition-colors hover:border-border hover:bg-muted/50"
            >
              <span className="flex size-11 items-center justify-center rounded-full border border-border bg-card text-foreground shadow-sm">
                {q.icon}
              </span>
              {q.label}
            </Link>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
