"use client";

import { useCallback, useMemo, useState, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import {
  BarChart3,
  ClipboardList,
  Network,
  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 { useAdminCurrencyCatalog } from "@/hooks/use-admin-currency-catalog";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_DASHBOARD_ANALYTICS_ACCESS_ANY, PRD_REPORT_VIEW } from "@/lib/admin-prd";
import { normalizeAdminLanguage } from "@/i18n";
import { adminWeekdayKeyForDate, formatAdminBusinessDateIso, formatAdminCalendarToday } from "@/lib/admin-datetime";
import { cn } from "@/lib/utils";
import { useAdminProfile } from "@/stores/admin-session";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminMoneyDisplay } from "@/components/admin/admin-money-display";
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 {
  DashboardKpiCard,
  DashboardQuickLinksCard,
  DashboardReportsTeaser,
  DashboardScopeMetric,
  DashboardSignedStatRow,
  DashboardStatRow,
} from "@/modules/dashboard/dashboard-visuals";
import { settlementCenterScopeHref } from "@/modules/settlement/settlement-center-nav";
import {
  formatDashboardCreditMajor,
  formatDashboardMoneyMinor,
} from "@/modules/dashboard/use-dashboard-analytics";
import type { AdminDashboardAgentOverview, AdminDashboardWarning } from "@/types/api/admin-dashboard";
import { LotteryApiBizError } from "@/types/api/errors";

function buildTodayBetHint(
  businessDate: string,
  latestBetAt: string | null,
  t: (key: string, opts?: Record<string, unknown>) => string,
  formatDt: (iso: string) => string,
): string {
  const dateHint = t("todayBusinessDateHint", { date: businessDate });
  if (latestBetAt) {
    return `${dateHint} · ${t("agent.latestBetAt", { time: formatDt(latestBetAt) })}`;
  }

  return `${dateHint} · ${t("agent.noBetToday")}`;
}

function agentLineHref(agentNodeId: number | null | undefined): string {
  if (agentNodeId != null && agentNodeId > 0) {
    return `/admin/agents?agent_node_id=${agentNodeId}`;
  }
  return "/admin/agents";
}

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 permissions = useMemo(() => profile?.permissions ?? [], [profile?.permissions]);
  const businessDateToday = useMemo(() => formatAdminBusinessDateIso(), []);

  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 [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [apiWarnings, setApiWarnings] = useState<AdminDashboardWarning[]>([]);
  const [overview, setOverview] = useState<AdminDashboardAgentOverview | null>(null);

  const canReports = adminHasAnyPermission(permissions, [PRD_REPORT_VIEW]);
  const canAnalytics = adminHasAnyPermission(permissions, [...PRD_DASHBOARD_ANALYTICS_ACCESS_ANY]);
  const lineHref = agentLineHref(agent?.id);

  const quickLinks = useMemo(
    () => [
      { href: "/admin/tickets", label: t("agent.quickLinks.tickets"), icon: ClipboardList },
      { href: lineHref, label: t("agent.quickLinks.players"), icon: Users },
      { href: lineHref, label: t("agent.quickLinks.agents"), icon: Network },
      {
        href: settlementCenterScopeHref(undefined, "awaiting_payment"),
        label: t("agent.quickLinks.bills"),
        icon: Wallet,
      },
      ...(canReports
        ? [{ href: "/admin/reports", label: t("agent.quickLinks.reports"), icon: BarChart3 }]
        : []),
    ],
    [canReports, lineHref, t],
  );

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

    try {
      const d = await getAdminDashboard();
      setOverview(d.agent_overview);
      setApiWarnings(d.warnings ?? []);
    } 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 displayCurrency = overview?.currency_code ?? "NPR";

  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 && apiWarnings.length > 0 ? (
        <Alert className="border-amber-200 bg-amber-50 dark:border-amber-900/60 dark:bg-amber-950/30">
          <AlertTitle>{t("notice")}</AlertTitle>
          <AlertDescription>{apiWarnings.map((w) => w.message).join(" ")}</AlertDescription>
        </Alert>
      ) : null}

      {loading ? (
        <div className="grid gap-3 sm:grid-cols-2 lg: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 lg:grid-cols-4">
            <DashboardKpiCard
              label={t("agent.todayBet")}
              value={formatDashboardMoneyMinor(overview.today_bet_minor, displayCurrency)}
              icon={<TrendingUp className="size-4" />}
              hint={buildTodayBetHint(businessDateToday, overview.latest_bet_at, t, formatDt)}
              href="/admin/tickets"
            />
            <DashboardKpiCard
              label={t("agent.todayShareProfit")}
              signedAmountMinor={overview.today_profit_minor}
              currencyCode={displayCurrency}
              icon={<BarChart3 className="size-4" />}
              hint={`${t("agent.shareRate", { rate: overview.total_share_rate })} · ${t("todayPayoutHint", {
                amount: formatDashboardMoneyMinor(overview.today_payout_minor, displayCurrency),
              })}`}
              href={canReports ? "/admin/reports" : undefined}
            />
            <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 })}
              href={lineHref}
            />
            <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"}
              href={settlementCenterScopeHref(undefined, "awaiting_payment")}
            />
          </div>

          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold">{t("agent.creditTitle")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div>
                <AdminMoneyDisplay
                  as="p"
                  value={formatDashboardCreditMajor(overview.credit_limit, displayCurrency)}
                  size="xl"
                  className="text-foreground"
                >
                  {formatDashboardCreditMajor(overview.credit_limit, displayCurrency)}
                </AdminMoneyDisplay>
                <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-2">
                <DashboardScopeMetric
                  label={t("agent.creditAllocatedLabel")}
                  value={formatDashboardCreditMajor(overview.allocated_credit, displayCurrency)}
                />
                <DashboardScopeMetric
                  label={t("agent.creditUsedLabel")}
                  value={formatDashboardCreditMajor(overview.used_credit, displayCurrency)}
                />
              </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">
                <DashboardStatRow
                  label={t("agent.sevenDayBet")}
                  value={formatDashboardMoneyMinor(overview.seven_day_bet_minor, displayCurrency)}
                />
                <DashboardStatRow
                  label={t("agent.sevenDayPayoutLabel")}
                  value={formatDashboardMoneyMinor(overview.seven_day_payout_minor, displayCurrency)}
                />
                <DashboardSignedStatRow
                  label={t("agent.sevenDayShareProfitLabel")}
                  amountMinor={overview.seven_day_profit_minor}
                  currencyCode={displayCurrency}
                />
                <p className="pt-1 text-xs text-muted-foreground">{t("agent.shareProfitScopeHint")}</p>
              </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">
                <DashboardScopeMetric
                  label={t("agent.directChildren")}
                  value={String(overview.direct_child_count)}
                />
                <DashboardScopeMetric
                  label={t("agent.directPlayers")}
                  value={String(overview.direct_player_count)}
                />
                <DashboardScopeMetric
                  label={t("agent.subtreeAgents")}
                  value={String(overview.subtree_agent_count)}
                />
                <DashboardScopeMetric
                  label={t("agent.teamPlayers")}
                  value={String(overview.team_player_count)}
                />
              </CardContent>
            </Card>
          </div>

          <DashboardQuickLinksCard title={t("quickLinksTitle")} links={quickLinks} variant="buttons" />
        </section>
      ) : (
        <AdminNoResourceState className="py-12 text-sm text-muted-foreground">
          {t("agent.overviewEmpty")}
        </AdminNoResourceState>
      )}

      {canAnalytics ? (
        <DashboardReportsTeaser
          title={t("analytics.title")}
          description={t("agent.shareProfitScopeHint")}
        />
      ) : !loading ? (
        <p className="text-xs text-muted-foreground">{t("warnings.analyticsUnavailable")}</p>
      ) : null}
    </div>
  );
}