"use client";
import { useMemo, useState, type ElementType } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { AlertCircle, ArrowDownRight, ArrowUpRight, CreditCard, DollarSign, FileText, RefreshCw, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { StatItem } from "@/features/dashboard/api/dashboardApi";
import { DASHBOARD_OVERVIEW_KEY, useDashboardOverview } from "@/features/dashboard/hooks/useDashboard";
import { ANALYTICS_KEY, useAnalyticsCustomers, useAnalyticsProducts } from "@/features/dashboard/hooks/useAnalytics";
import { CustomersSection } from "@/features/dashboard/components/productsCustomersSection";
import { formatNumber } from "@/features/dashboard/components/analyticsFormat";
/**
* KPI register cell dividers: a 2×2 grid on small screens, one row of four on lg.
* Each cell owns its own rules, so the panel never needs a negative-margin trick.
*/
const KPI_CELL_BORDERS = [
"border-b border-r border-border lg:border-b-0",
"border-b border-border lg:border-b-0 lg:border-r",
"border-r border-border",
"",
];
// ─── Stat cell ────────────────────────────────────────────────────────────────
interface StatCellProps {
title: string;
stat?: StatItem;
icon: ElementType;
footnote: string;
comparedTo: string;
className?: string;
}
function StatCell({ title, stat, icon: Icon, footnote, comparedTo, className }: StatCellProps) {
const change = stat?.changePercent;
const hasChange = change !== null && change !== undefined;
const positive = (change ?? 0) >= 0;
return (
{formatNumber(stat?.count ?? 0)}
{hasChange ? (
{positive ? (
) : (
)}
{formatNumber(Math.abs(change), 1)}%
{comparedTo}
) : (
{footnote}
)}
);
}
function StatCellSkeleton({ className }: { className?: string }) {
return (
);
}
// ─── Page ─────────────────────────────────────────────────────────────────────
export default function DashboardPage({ isLoading: propLoading = false }: { isLoading?: boolean }) {
const { t } = useTranslation();
const queryClient = useQueryClient();
const currentYear = new Date().getFullYear();
const [selectedYear, setSelectedYear] = useState(currentYear);
const analyticsParams = useMemo(() => ({ from: `${selectedYear}-01-01`, to: `${selectedYear}-12-31` }), [selectedYear]);
const overview = useDashboardOverview({ year: selectedYear });
const customers = useAnalyticsCustomers(analyticsParams);
const products = useAnalyticsProducts(analyticsParams);
const isFetching = overview.isFetching || customers.isFetching || products.isFetching;
const showStatSkeleton = propLoading || overview.isLoading;
const handleRefresh = () => {
void queryClient.invalidateQueries({ queryKey: [DASHBOARD_OVERVIEW_KEY] });
void queryClient.invalidateQueries({ queryKey: [ANALYTICS_KEY] });
};
const yearOptions = [currentYear - 2, currentYear - 1, currentYear];
const comparedTo = t("dashboard.comparedToLastMonth", "geçen aýa garanyňda");
const stats = overview.data?.stats;
const statCards: Omit[] = [
{
title: t("dashboard.loanOrders", "Karz sargytlary"),
stat: stats?.loanOrders,
icon: FileText,
footnote: t("dashboard.totalLoanOrders", "Jemi karz sargytlar"),
},
{
title: t("dashboard.activeCards", "Işjeň kartlar"),
stat: stats?.activeCards,
icon: CreditCard,
footnote: t("dashboard.totalActiveCards", "Işjeň kartlaryň sany"),
},
{
title: t("dashboard.activeClients", "Işjeň müşderiler"),
stat: stats?.activeCustomers,
icon: Users,
footnote: t("dashboard.totalActiveCustomers", "Hasaba alnan müşderiler"),
},
{
title: t("dashboard.onlinePayments", "Onlaýn tölegler"),
stat: stats?.onlinePayments,
icon: DollarSign,
footnote: t("dashboard.totalOnlinePayments", "Amala aşyrylan tölegler"),
},
];
return (
{/* Header */}
{t("dashboard.title", "Baş sahypa")}
{t("dashboard.overviewSubtitle", "Ähli amallaryň gysgaça görünüşi")}
{/* KPI register */}
{overview.isError && !showStatSkeleton ? (
{t("dashboard.errorTitle", "Maglumatlary ýükläp bolmady")}
{overview.error instanceof Error && overview.error.message
? overview.error.message
: t("dashboard.errorMessage", "Serwer bilen baglanyşykda säwlik ýüze çykdy.")}
) : (
{showStatSkeleton
? Array.from({ length: 4 }, (_, i) => )
: statCards.map((card, i) => )}
)}
{/* Customers analytics */}
customers.refetch()}
products={{
data: products.data,
isLoading: products.isLoading,
isError: products.isError,
onRetry: () => products.refetch(),
}}
/>
);
}