"use client";

import Link from "next/link";
import { useCallback, useMemo, useState, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { AlertTriangle, ClipboardList, RefreshCw, Scale, Users, Wallet } from "lucide-react";

import { getAdminDashboard } from "@/api/admin-dashboard";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";
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 { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import {
  AbnormalTransferPanelFooter,
  DashboardKpiCard,
  DashboardQuickLinksCard,
} from "@/modules/dashboard/dashboard-visuals";
import { settlementCenterScopeHref } from "@/modules/settlement/settlement-center-nav";
import { formatDashboardMoneyMinor } from "@/modules/dashboard/use-dashboard-analytics";
import { cn } from "@/lib/utils";
import { useAdminProfile } from "@/stores/admin-session";
import type {
  AdminDashboardSiteFinanceOverview,
  AdminDashboardWarning,
} from "@/types/api/admin-dashboard";
import { LotteryApiBizError } from "@/types/api/errors";

export function SiteFinanceDashboardConsole(): ReactElement {
  const { t } = useTranslation(["dashboard", "common"]);
  const tRef = useTranslationRef(["dashboard", "common"]);
  const profile = useAdminProfile();
  const site = profile?.site ?? null;

  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<AdminDashboardSiteFinanceOverview | null>(null);
  const [walletPermission, setWalletPermission] = useState(false);

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

    try {
      const d = await getAdminDashboard();
      setOverview(d.site_finance_overview);
      setApiWarnings(d.warnings ?? []);
      setWalletPermission(d.capabilities?.wallet_transfer_view ?? false);
    } 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";
  const abnormalCount = overview?.abnormal_transfer_count ?? null;
  const abnormalHref = "/admin/wallet/transfer-orders?abnormal=1";

  const quickLinks = useMemo(
    () => [
      { href: "/admin/reconcile", label: t("finance.quickLinks.reconcile") },
      { href: "/admin/wallet/transfer-orders", label: t("finance.quickLinks.transfers") },
      {
        href: settlementCenterScopeHref(site?.id, "awaiting_payment"),
        label: t("finance.quickLinks.bills"),
      },
      { href: "/admin/reports", label: t("finance.quickLinks.reports") },
    ],
    [site?.id, t],
  );

  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("finance.title")}</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">
            {site
              ? t("finance.subtitle", { name: site.name || site.code })
              : t("finance.subtitleFallback")}
          </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("finance.abnormalTransfers")}
              value={abnormalCount ?? "—"}
              icon={<AlertTriangle className="size-4" />}
              hint={t("abnormalTransferScope")}
              accent={(abnormalCount ?? 0) > 0 ? "destructive" : "muted"}
              href={abnormalHref}
            />
            <DashboardKpiCard
              label={t("finance.pendingConfirmBills")}
              value={overview.pending_confirm_bill_count}
              icon={<ClipboardList className="size-4" />}
              hint={t("finance.pendingConfirmHint")}
              accent={overview.pending_confirm_bill_count > 0 ? "primary" : "muted"}
              href={settlementCenterScopeHref(site?.id, "pending_confirm")}
            />
            <DashboardKpiCard
              label={t("finance.payableBills")}
              value={overview.payable_bill_count}
              icon={<Scale className="size-4" />}
              hint={t("finance.payableUnpaid", {
                amount: formatDashboardMoneyMinor(overview.payable_unpaid_minor, displayCurrency),
              })}
              accent={overview.payable_bill_count > 0 ? "destructive" : "muted"}
              href={settlementCenterScopeHref(site?.id, "awaiting_payment")}
            />
            <DashboardKpiCard
              label={t("finance.walletPlayers")}
              value={overview.wallet_player_count}
              icon={<Users className="size-4" />}
              hint={t("finance.creditPlayersHint", { count: overview.credit_player_count })}
              href="/admin/players"
            />
          </div>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold">{t("finance.reconcileTitle")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <AbnormalTransferPanelFooter
                total={abnormalCount}
                walletPermission={walletPermission}
              />
              <Link
                href={abnormalHref}
                className={buttonVariants({ variant: "outline", size: "sm", className: "w-full" })}
              >
                <Wallet className="size-3.5" />
                {t("viewTransferOrders")}
              </Link>
            </CardContent>
          </Card>

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