import React from "react";
import {
    Activity,
    User,
    TrendUp,
    DocumentText,
    Warning2
} from "iconsax-react";
import StatusCircle from "../../../components/StatusCircle";
import {
    OperationStatsResponse,
    TopUsersResponse,
    OperationType,
    UserType,
    OperationTypeLabels,
    UserTypeLabels,
} from "../types/AccessLogTypes";

interface StatsDashboardProps {
    stats: OperationStatsResponse | null;
    topUsers: TopUsersResponse | null;
    loading: boolean;
}

const StatsDashboard: React.FC<StatsDashboardProps> = ({
    stats,
    topUsers,
    loading,
}) => {
    const getOperationTypeColor = (type: OperationType): string => {
        const colors = {
            CREATE: "green",
            UPDATE: "blue",
            DELETE: "red",
            READ: "gray",
            LOGIN: "purple",
            LOGOUT: "orange",
            APPROVE: "green",
            REJECT: "red",
            ACTIVATE: "green",
            DEACTIVATE: "red",
            EXPORT: "blue",
            IMPORT: "blue",
            BULK_UPDATE: "blue",
            BULK_DELETE: "red",
        };
        return colors[type as keyof typeof colors] || "gray";
    };

    const getUserTypeBadgeColor = (type: UserType): string => {
        const colors = {
            SYSTEM: "bg-gray-100 text-gray-800",
            ADMIN: "bg-red-100 text-red-800",
            USER: "bg-blue-100 text-blue-800",
        };
        return colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800";
    };

    // Calculate totals
    const totalOperations = stats?.operationStats.reduce((sum: number, stat: any) => sum + stat.count, 0) || 0;
    const totalUsers = topUsers?.topUsers.length || 0;

    // Group stats by operation type
    const operationTypeTotals = stats?.operationStats.reduce((acc: Record<OperationType, number>, stat: any) => {
        acc[stat.operationType as OperationType] = (acc[stat.operationType as OperationType] || 0) + stat.count;
        return acc;
    }, {} as Record<OperationType, number>) || {};

    // Group stats by user type
    const userTypeTotals = stats?.operationStats.reduce((acc: Record<UserType, number>, stat: any) => {
        acc[stat.userType as UserType] = (acc[stat.userType as UserType] || 0) + stat.count;
        return acc;
    }, {} as Record<UserType, number>) || {};

    const StatCard: React.FC<{
        icon: React.ReactNode;
        title: string;
        value: string | number;
        color: string;
        subtitle?: string;
    }> = ({ icon, title, value, color, subtitle }) => (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="flex items-center">
                <div className={`flex-shrink-0 p-3 rounded-lg bg-${color}-100`}>
                    <div className={`text-${color}-600`}>
                        {icon}
                    </div>
                </div>
                <div className="mr-4 flex-1">
                    <p className="text-sm font-medium text-gray-600">{title}</p>
                    <p className="text-2xl font-bold text-gray-900">{(value || 0).toLocaleString('fa-IR')}</p>
                    {subtitle && (
                        <p className="text-xs text-gray-500 mt-1">{subtitle}</p>
                    )}
                </div>
            </div>
        </div>
    );

    if (loading) {
        return (
            <div className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[...Array(4)].map((_, i) => (
                        <div key={i} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 animate-pulse">
                            <div className="flex items-center">
                                <div className="flex-shrink-0 p-3 rounded-lg bg-gray-200 w-12 h-12"></div>
                                <div className="mr-4 flex-1">
                                    <div className="h-4 bg-gray-200 rounded w-20 mb-2"></div>
                                    <div className="h-8 bg-gray-200 rounded w-16"></div>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <StatCard
                    icon={<Activity size={24} />}
                    title="کل عملیات"
                    value={totalOperations}
                    color="blue"
                    subtitle="در بازه زمانی انتخاب شده"
                />

                <StatCard
                    icon={<User size={24} />}
                    title="کاربران فعال"
                    value={totalUsers}
                    color="green"
                    subtitle="کاربران با فعالیت"
                />

                <StatCard
                    icon={<Activity size={24} />}
                    title="عملیات ایجاد"
                    value={(operationTypeTotals as any)[OperationType.CREATE] || 0}
                    color="green"
                    subtitle="عملیات جدید"
                />

                <StatCard
                    icon={<Warning2 size={24} />}
                    title="عملیات حذف"
                    value={(operationTypeTotals as any)[OperationType.DELETE] || 0}
                    color="red"
                    subtitle="عملیات حذف شده"
                />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Operation Types Chart */}
                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                            <Activity size={20} />
                            توزیع نوع عملیات
                        </h3>
                        <span className="text-sm text-gray-500">
                            {totalOperations.toLocaleString('fa-IR')} کل
                        </span>
                    </div>

                    <div className="space-y-4">
                        {Object.entries(operationTypeTotals)
                            .sort(([, a], [, b]) => (b as number) - (a as number))
                            .slice(0, 8)
                            .map(([type, count]) => {
                                const percentage = totalOperations > 0 ? ((count as number) / totalOperations) * 100 : 0;
                                return (
                                    <div key={type} className="flex items-center justify-between">
                                        <div className="flex items-center gap-3 flex-1">
                                            <StatusCircle
                                                color={getOperationTypeColor(type as OperationType)}
                                                text=""
                                                size="sm"
                                            />
                                            <span className="text-sm font-medium text-gray-700">
                                                {OperationTypeLabels[type as OperationType]}
                                            </span>
                                        </div>
                                        <div className="flex items-center gap-3">
                                            <div className="w-24 bg-gray-200 rounded-full h-2">
                                                <div
                                                    className={`h-2 rounded-full bg-${getOperationTypeColor(type as OperationType)}-500`}
                                                    style={{ width: `${percentage}%` }}
                                                />
                                            </div>
                                            <span className="text-sm font-semibold text-gray-900 min-w-[3rem] text-left">
                                                {(count as number).toLocaleString('fa-IR')}
                                            </span>
                                            <span className="text-xs text-gray-500 min-w-[3rem] text-left">
                                                {percentage.toFixed(1)}%
                                            </span>
                                        </div>
                                    </div>
                                );
                            })}
                    </div>
                </div>

                {/* User Types Distribution */}
                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                            <User size={20} />
                            توزیع نوع کاربر
                        </h3>
                        <span className="text-sm text-gray-500">
                            {totalOperations.toLocaleString('fa-IR')} کل
                        </span>
                    </div>

                    <div className="space-y-4">
                        {Object.entries(userTypeTotals)
                            .sort(([, a], [, b]) => (b as number) - (a as number))
                            .map(([type, count]) => {
                                const percentage = totalOperations > 0 ? ((count as number) / totalOperations) * 100 : 0;
                                return (
                                    <div key={type} className="flex items-center justify-between">
                                        <div className="flex items-center gap-3 flex-1">
                                            <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getUserTypeBadgeColor(type as UserType)}`}>
                                                {UserTypeLabels[type as UserType]}
                                            </span>
                                        </div>
                                        <div className="flex items-center gap-3">
                                            <div className="w-32 bg-gray-200 rounded-full h-3">
                                                <div
                                                    className="h-3 rounded-full bg-blue-500"
                                                    style={{ width: `${percentage}%` }}
                                                />
                                            </div>
                                            <span className="text-sm font-semibold text-gray-900 min-w-[3rem] text-left">
                                                {(count as number).toLocaleString('fa-IR')}
                                            </span>
                                            <span className="text-xs text-gray-500 min-w-[3rem] text-left">
                                                {percentage.toFixed(1)}%
                                            </span>
                                        </div>
                                    </div>
                                );
                            })}
                    </div>
                </div>
            </div>

            {/* Top Users Table */}
            {topUsers && topUsers.topUsers.length > 0 && (
                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                            <TrendUp size={20} />
                            فعال‌ترین کاربران
                        </h3>
                        <span className="text-sm text-gray-500">
                            {topUsers.topUsers.length} کاربر
                        </span>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        رتبه
                                    </th>
                                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        کاربر
                                    </th>
                                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        ایمیل
                                    </th>
                                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        تعداد فعالیت
                                    </th>
                                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        درصد
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {topUsers.topUsers.map((user, index) => {
                                    const percentage = totalOperations > 0 ? (user.activityCount / totalOperations) * 100 : 0;
                                    return (
                                        <tr key={user.userId} className="hover:bg-gray-50">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-100 text-blue-800 font-bold">
                                                    {index + 1}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <div className="flex items-center gap-3">
                                                    <div className="flex-shrink-0 w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
                                                        <User size={20} className="text-gray-600" />
                                                    </div>
                                                    <div>
                                                        <div className="text-sm font-medium text-gray-900">
                                                            {user.firstName} {user.lastName}
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                {user.email}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900">
                                                {(user.activityCount || 0).toLocaleString('fa-IR')}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <div className="flex items-center gap-2">
                                                    <div className="w-16 bg-gray-200 rounded-full h-2">
                                                        <div
                                                            className="h-2 rounded-full bg-blue-500"
                                                            style={{ width: `${percentage}%` }}
                                                        />
                                                    </div>
                                                    <span className="text-xs text-gray-500">
                                                        {percentage.toFixed(1)}%
                                                    </span>
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}

            {/* Entity Activity */}
            {stats && stats.operationStats.length > 0 && (
                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                            <DocumentText size={20} />
                            فعالیت موجودیت‌ها
                        </h3>
                        <span className="text-sm text-gray-500">
                            {stats.operationStats.length} نوع موجودیت
                        </span>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        {stats.operationStats
                            .reduce((acc: Array<{ entityName: string; count: number }>, stat: any) => {
                                const existing = acc.find((item: any) => item.entityName === stat.entityName);
                                if (existing) {
                                    existing.count += stat.count;
                                } else {
                                    acc.push({ entityName: stat.entityName, count: stat.count });
                                }
                                return acc;
                            }, [] as { entityName: string; count: number }[])
                            .sort((a: any, b: any) => b.count - a.count)
                            .slice(0, 9)
                            .map((entity: any) => {
                                const percentage = totalOperations > 0 ? (entity.count / totalOperations) * 100 : 0;
                                return (
                                    <div key={entity.entityName} className="bg-gray-50 rounded-lg p-4">
                                        <div className="flex items-center justify-between mb-2">
                                            <h4 className="font-medium text-gray-900">{entity.entityName}</h4>
                                            <span className="text-sm font-semibold text-gray-700">
                                                {(entity.count || 0).toLocaleString('fa-IR')}
                                            </span>
                                        </div>
                                        <div className="w-full bg-gray-200 rounded-full h-2">
                                            <div
                                                className="h-2 rounded-full bg-green-500"
                                                style={{ width: `${percentage}%` }}
                                            />
                                        </div>
                                        <p className="text-xs text-gray-500 mt-1">
                                            {percentage.toFixed(1)}% از کل فعالیت‌ها
                                        </p>
                                    </div>
                                );
                            })}
                    </div>
                </div>
            )}
        </div>
    );
};

export default StatsDashboard;
