"use client";

import { useCallback, useMemo, useState, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { BarChart3, RefreshCw, TrendingUp, Users, Wallet } from "lucide-react";

import { getAdminDashboard } from "@/api/admin-dashboard";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { useTranslationRef } from "@/hooks/use-translation-ref";
import { useCachedPlayTypeOptions } from "@/hooks/use-cached-play-type-options";
import { useAdminCurrencyCatalog } from "@/hooks/use-admin-currency-catalog";
import { normalizeAdminLanguage } from "@/i18n";
import { adminWeekdayKeyForDate, formatAdminCalendarToday } from "@/lib/admin-datetime";
import { signedMoneyClass } from "@/lib/admin-signed-money";
import { cn } from "@/lib/utils";
import { useAdminProfile } from "@/stores/admin-session";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { DashboardCurrentDrawCard } from "@/modules/dashboard/dashboard-current-draw-card";
import { DashboardAnalyticsPanel } from "@/modules/dashboard/dashboard-analytics-panel";
import { DashboardKpiCard } from "@/modules/dashboard/dashboard-visuals";
import {
  formatDashboardCreditMajor,
  formatDashboardMoneyMinor,
  formatDashboardSignedMoneyMinor,
} from "@/modules/dashboard/use-dashboard-analytics";
import type { AdminDashboardAgentOverview } from "@/types/api/admin-dashboard";
import type { DrawCurrentSnapshot } from "@/types/api/public-draw";
import { LotteryApiBizError } from "@/types/api/errors";

function AgentMetric({
  label,
  value,
}: {
  label: string;
  value: string;
}): ReactElement {
  return (
    <div className="rounded-lg border bg-muted/30 px-3 py-2.5">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="mt-1 text-base font-semibold tabular-nums text-foreground">{value}</p>
    </div>
  );
}

export function AgentDashboardConsole(): ReactElement {
  const { t, i18n } = useTranslation(["dashboard", "common", "agents"]);
  const tRef = useTranslationRef(["dashboard", "common"]);
  const formatDt = useAdminDateTimeFormatter();
  const profile = useAdminProfile();
  const agent = profile?.agent ?? null;
  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]);

  useAdminCurrencyCatalog();
  const playOptions = useCachedPlayTypeOptions();

  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 [overview, setOverview] = useState<AdminDashboardAgentOverview | null>(null);
  const [canFinance, setCanFinance] = useState(false);

  const analyticsScope = useMemo(
    () => ({
      siteCode: agent?.site_code ?? "",
      agentNodeId: agent?.id,
    }),
    [agent?.id, agent?.site_code],
  );

  const load = useCallback(async (isRefresh = false) => {
    if (isRefresh) {
      setRefreshing(true);
    } else {
      setLoading(true);
    }
    setError(null);

    try {
      const d = await getAdminDashboard();
      setHall(d.hall);
      setOverview(d.agent_overview);
      setCanFinance(d.capabilities.draw_finance_risk);
      if (d.resolved_draw != null) {
        setDrawId(d.resolved_draw.id);
      } else {
        setDrawId(null);
      }
    } catch (e) {
      const msg =
        e instanceof LotteryApiBizError ? e.message : tRef.current("warnings.loadFailed");
      setError(msg);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [tRef]);

  useAsyncEffect(() => {
    void load(false);
  }, []);

  const currency = "NPR";
  const displayCurrency = overview?.currency_code ?? currency;

  return (
    <div className="flex min-w-0 w-full max-w-none flex-col gap-5">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="min-w-0">
          <h1 className="admin-list-title">{t("agent.title")}</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">
            {agent
              ? t("agent.subtitle", { name: agent.name || agent.code })
              : todayLabel}
          </p>
        </div>
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="h-8"
          disabled={loading || refreshing}
          onClick={() => void load(true)}
        >
          <RefreshCw className={cn("size-3.5", refreshing && "animate-spin")} />
          {t("actions.refresh", { ns: "common" })}
        </Button>
      </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 ? (
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-24 rounded-xl" />
          ))}
        </div>
      ) : overview ? (
        <section className="space-y-4">
          <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <DashboardKpiCard
              label={t("agent.todayBet")}
              value={formatDashboardMoneyMinor(overview.today_bet_minor, displayCurrency)}
              icon={<TrendingUp className="size-4" />}
              hint={
                overview.latest_bet_at
                  ? t("agent.latestBetAt", { time: formatDt(overview.latest_bet_at) })
                  : t("agent.noBetToday")
              }
            />
            <DashboardKpiCard
              label={t("agent.todayShareProfit")}
              value={formatDashboardSignedMoneyMinor(overview.today_profit_minor, displayCurrency)}
              icon={<BarChart3 className="size-4" />}
              hint={t("agent.shareRate", { rate: overview.total_share_rate })}
              valueClassName={signedMoneyClass(overview.today_profit_minor, true)}
            />
            <DashboardKpiCard
              label={t("agent.activePlayersToday")}
              value={overview.active_player_count_today}
              icon={<Users className="size-4" />}
              hint={t("agent.betOrdersTodayHint", { count: overview.bet_order_count_today })}
            />
            <DashboardKpiCard
              label={t("agent.pendingBills")}
              value={overview.pending_bill_count}
              icon={<Wallet className="size-4" />}
              hint={t("agent.pendingUnpaid", {
                amount: formatDashboardMoneyMinor(overview.pending_unpaid_minor, displayCurrency),
              })}
              accent={overview.pending_bill_count > 0 ? "destructive" : "muted"}
            />
          </div>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold">{t("agent.creditTitle")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div>
                <p className="text-2xl font-semibold tabular-nums">
                  {formatDashboardCreditMajor(overview.credit_limit, displayCurrency)}
                </p>
                <p className="mt-1 text-xs text-muted-foreground">
                  {t("agent.creditAvailable", {
                    amount: formatDashboardCreditMajor(overview.available_credit, displayCurrency),
                  })}
                </p>
              </div>
              <div className="grid gap-3 sm:grid-cols-3">
                <AgentMetric
                  label={t("agent.creditAllocatedLabel")}
                  value={formatDashboardCreditMajor(overview.allocated_credit, displayCurrency)}
                />
                <AgentMetric
                  label={t("agent.creditUsedLabel")}
                  value={formatDashboardCreditMajor(overview.used_credit, displayCurrency)}
                />
                <AgentMetric
                  label={t("agent.pendingBills")}
                  value={String(overview.pending_bill_count)}
                />
              </div>
              <p className="text-xs text-muted-foreground">
                {t("agent.lineMeta", {
                  depth: overview.depth,
                  childAgent: overview.can_create_child_agent ? t("agent.yes") : t("agent.no"),
                  player: overview.can_create_player ? t("agent.yes") : t("agent.no"),
                })}
              </p>
            </CardContent>
          </Card>

          <div className="grid gap-3 md:grid-cols-2">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-semibold">{t("agent.sevenDayTitle")}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                <div className="flex items-center justify-between gap-3">
                  <span className="text-muted-foreground">{t("agent.todayBet")}</span>
                  <span className="font-semibold tabular-nums">
                    {formatDashboardMoneyMinor(overview.seven_day_bet_minor, displayCurrency)}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-3">
                  <span className="text-muted-foreground">{t("agent.todayShareProfit")}</span>
                  <span
                    className={cn(
                      "font-semibold tabular-nums",
                      signedMoneyClass(overview.seven_day_profit_minor, true),
                    )}
                  >
                    {formatDashboardSignedMoneyMinor(overview.seven_day_profit_minor, displayCurrency)}
                  </span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-semibold">{t("agent.teamTitle")}</CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-3 text-sm">
                <AgentMetric
                  label={t("agent.directChildren")}
                  value={String(overview.direct_child_count)}
                />
                <AgentMetric
                  label={t("agent.directPlayers")}
                  value={String(overview.direct_player_count)}
                />
                <AgentMetric
                  label={t("agent.subtreeAgents")}
                  value={String(overview.subtree_agent_count)}
                />
                <AgentMetric
                  label={t("agent.teamPlayers")}
                  value={String(overview.team_player_count)}
                />
              </CardContent>
            </Card>
          </div>
        </section>
      ) : null}

      <DashboardCurrentDrawCard
        key={`${hall?.draw_no ?? "empty"}:${loading ? "loading" : "ready"}`}
        hall={hall}
        drawId={drawId}
        loading={loading}
      />

      {canFinance ? (
        <DashboardAnalyticsPanel
          enabled={canFinance}
          playOptions={playOptions}
          scope={analyticsScope}
        />
      ) : (
        <Alert className="border-muted">
          <AlertTitle>{t("notice")}</AlertTitle>
          <AlertDescription>{t("warnings.drawPermission")}</AlertDescription>
        </Alert>
      )}
    </div>
  );
}
