"use client";

import { CreditCard, DollarSign, TrendingUp, TrendingDown, Users, Activity } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatCurrency, cn } from "@/lib/utils";
import { BankingAccount, BankingTransaction } from "@/types/banking";

interface BankingStatsCardsProps {
    readonly accounts: BankingAccount[];
    readonly transactions: BankingTransaction[];
    readonly timeRange?: "today" | "week" | "month" | "year";
    readonly className?: string;
}

export function BankingStatsCards({ accounts, transactions, timeRange = "month", className }: BankingStatsCardsProps) {
    // Filtrer les transactions selon la période
    const getFilteredTransactions = () => {
        const now = new Date();
        const startDate = new Date();

        switch (timeRange) {
            case "today":
                startDate.setHours(0, 0, 0, 0);
                break;
            case "week":
                startDate.setDate(now.getDate() - 7);
                break;
            case "month":
                startDate.setMonth(now.getMonth() - 1);
                break;
            case "year":
                startDate.setFullYear(now.getFullYear() - 1);
                break;
        }

        return transactions.filter((t) => new Date(t.transaction_date) >= startDate);
    };

    const filteredTransactions = getFilteredTransactions();

    // Calculs des statistiques
    const totalBalance = accounts.reduce((sum, account) => sum + account.balance, 0);
    const activeAccounts = accounts.filter((account) => account.status === "active").length;

    const totalDeposits = filteredTransactions
        .filter((t) => ["deposit", "interest"].includes(t.transaction_type) && t.status === "completed")
        .reduce((sum, t) => sum + t.amount, 0);

    const totalWithdrawals = filteredTransactions
        .filter((t) => ["withdrawal", "fee", "loan_payment"].includes(t.transaction_type) && t.status === "completed")
        .reduce((sum, t) => sum + t.amount, 0);

    const netFlow = totalDeposits - totalWithdrawals;
    const transactionVolume = totalDeposits + totalWithdrawals;
    const transactionCount = filteredTransactions.filter((t) => t.status === "completed").length;

    // Comparaison avec la période précédente pour les tendances
    const getPreviousPeriodTransactions = () => {
        const now = new Date();
        const startDate = new Date();
        const endDate = new Date();

        switch (timeRange) {
            case "today":
                startDate.setDate(now.getDate() - 1);
                startDate.setHours(0, 0, 0, 0);
                endDate.setDate(now.getDate() - 1);
                endDate.setHours(23, 59, 59, 999);
                break;
            case "week":
                startDate.setDate(now.getDate() - 14);
                endDate.setDate(now.getDate() - 7);
                break;
            case "month":
                startDate.setMonth(now.getMonth() - 2);
                endDate.setMonth(now.getMonth() - 1);
                break;
            case "year":
                startDate.setFullYear(now.getFullYear() - 2);
                endDate.setFullYear(now.getFullYear() - 1);
                break;
        }

        return transactions.filter((t) => {
            const date = new Date(t.transaction_date);
            return date >= startDate && date <= endDate;
        });
    };

    const previousTransactions = getPreviousPeriodTransactions();
    const previousVolume = previousTransactions
        .filter((t) => t.status === "completed")
        .reduce((sum, t) => sum + t.amount, 0);

    const volumeGrowth = previousVolume > 0 ? ((transactionVolume - previousVolume) / previousVolume) * 100 : 0;

    const averageTransactionAmount = transactionCount > 0 ? transactionVolume / transactionCount : 0;

    // Types de comptes
    const accountTypeDistribution = accounts.reduce(
        (acc, account) => {
            acc[account.account_type] = (acc[account.account_type] || 0) + 1;
            return acc;
        },
        {} as Record<string, number>,
    );

    // Safe property access to avoid Generic Object Injection Sink warnings
    const getTimeRangeLabel = (range: typeof timeRange): string => {
        switch (range) {
            case "today":
                return "aujourd'hui";
            case "week":
                return "cette semaine";
            case "month":
                return "ce mois";
            case "year":
                return "cette année";
            default:
                return range;
        }
    };

    return (
        <div className={cn("grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4", className)}>
            {/* Solde total */}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Solde total</CardTitle>
                    <DollarSign className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="text-2xl font-bold">{formatCurrency(totalBalance)}</div>
                    <p className="text-muted-foreground text-xs">
                        Sur {accounts.length} compte{accounts.length > 1 ? "s" : ""}
                    </p>
                    <div className="mt-2 flex items-center space-x-2">
                        <Badge variant="outline" className="text-xs">
                            {activeAccounts} actif{activeAccounts > 1 ? "s" : ""}
                        </Badge>
                    </div>
                </CardContent>
            </Card>

            {/* Volume des transactions */}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Volume des transactions</CardTitle>
                    <Activity className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="text-2xl font-bold">{formatCurrency(transactionVolume)}</div>
                    <p className="text-muted-foreground text-xs">{getTimeRangeLabel(timeRange)}</p>
                    <div className="mt-2 flex items-center space-x-1">
                        {volumeGrowth >= 0 ? (
                            <TrendingUp className="h-3 w-3 text-green-500" />
                        ) : (
                            <TrendingDown className="h-3 w-3 text-red-500" />
                        )}
                        <span className={cn("text-xs font-medium", volumeGrowth >= 0 ? "text-green-500" : "text-red-500")}>
                            {volumeGrowth >= 0 ? "+" : ""}
                            {volumeGrowth.toFixed(1)}%
                        </span>
                        <span className="text-muted-foreground text-xs">vs période précédente</span>
                    </div>
                </CardContent>
            </Card>

            {/* Flux net */}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Flux net</CardTitle>
                    {netFlow >= 0 ? (
                        <TrendingUp className="h-4 w-4 text-green-500" />
                    ) : (
                        <TrendingDown className="h-4 w-4 text-red-500" />
                    )}
                </CardHeader>
                <CardContent>
                    <div className={cn("text-2xl font-bold", netFlow >= 0 ? "text-green-600" : "text-red-600")}>
                        {netFlow >= 0 ? "+" : ""}
                        {formatCurrency(netFlow)}
                    </div>
                    <p className="text-muted-foreground text-xs">{getTimeRangeLabel(timeRange)}</p>
                    <div className="mt-2 grid grid-cols-2 gap-2 text-xs">
                        <div className="text-green-600">Entrées: {formatCurrency(totalDeposits)}</div>
                        <div className="text-red-600">Sorties: {formatCurrency(totalWithdrawals)}</div>
                    </div>
                </CardContent>
            </Card>

            {/* Nombre de transactions */}
            <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Transactions</CardTitle>
                    <CreditCard className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="text-2xl font-bold">{transactionCount}</div>
                    <p className="text-muted-foreground text-xs">{getTimeRangeLabel(timeRange)}</p>
                    <div className="mt-2">
                        <p className="text-muted-foreground text-xs">Moyenne: {formatCurrency(averageTransactionAmount)}</p>
                    </div>
                </CardContent>
            </Card>

            {/* Répartition par type de compte */}
            <Card className="md:col-span-2 lg:col-span-1">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Types de comptes</CardTitle>
                    <Users className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="space-y-2">
                        {Object.entries(accountTypeDistribution).map(([type, count]) => {
                            const typeLabels = {
                                savings: "Épargne",
                                checking: "Courant",
                                credit: "Crédit",
                                pso: "Parts Sociales",
                                loan: "Prêt",
                            };

                            const typeColors = {
                                savings: "bg-green-100 text-green-700",
                                checking: "bg-blue-100 text-blue-700",
                                credit: "bg-purple-100 text-purple-700",
                                pso: "bg-orange-100 text-orange-700",
                                loan: "bg-red-100 text-red-700",
                            };

                            return (
                                <div key={type} className="flex items-center justify-between">
                                    <Badge variant="secondary" className={cn("text-xs", typeColors[type as keyof typeof typeColors])}>
                                        {typeLabels[type as keyof typeof typeLabels] || type}
                                    </Badge>
                                    <span className="text-sm font-medium">{count}</span>
                                </div>
                            );
                        })}
                    </div>
                </CardContent>
            </Card>

            {/* Statut des comptes */}
            <Card className="md:col-span-2 lg:col-span-1">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Statut des comptes</CardTitle>
                    <Activity className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="space-y-2">
                        {["active", "inactive", "frozen", "closed"].map((status) => {
                            const count = accounts.filter((account) => account.status === status).length;
                            if (count === 0) return null;

                            const statusLabels = {
                                active: "Actifs",
                                inactive: "Inactifs",
                                frozen: "Gelés",
                                closed: "Fermés",
                            };

                            const statusColors = {
                                active: "bg-green-100 text-green-700",
                                inactive: "bg-gray-100 text-gray-700",
                                frozen: "bg-blue-100 text-blue-700",
                                closed: "bg-red-100 text-red-700",
                            };

                            return (
                                <div key={status} className="flex items-center justify-between">
                                    <Badge variant="outline" className={cn("text-xs", statusColors[status as keyof typeof statusColors])}>
                                        {statusLabels[status as keyof typeof statusLabels]}
                                    </Badge>
                                    <span className="text-sm font-medium">{count}</span>
                                </div>
                            );
                        })}
                    </div>
                </CardContent>
            </Card>

            {/* Performance */}
            <Card className="md:col-span-2 lg:col-span-1">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">Performance</CardTitle>
                    <TrendingUp className="text-muted-foreground h-4 w-4" />
                </CardHeader>
                <CardContent>
                    <div className="space-y-2">
                        <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">Taux de croissance</span>
                            <span className={cn("font-medium", volumeGrowth >= 0 ? "text-green-600" : "text-red-600")}>
                                {volumeGrowth >= 0 ? "+" : ""}
                                {volumeGrowth.toFixed(1)}%
                            </span>
                        </div>
                        <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">Tx par compte</span>
                            <span className="font-medium">
                                {accounts.length > 0 ? (transactionCount / accounts.length).toFixed(1) : "0"}
                            </span>
                        </div>
                        <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">Solde moyen</span>
                            <span className="font-medium">
                                {formatCurrency(accounts.length > 0 ? totalBalance / accounts.length : 0)}
                            </span>
                        </div>
                    </div>
                </CardContent>
            </Card>
        </div>
    );
}
