import React, { useState, useEffect } from "react";
import {
    Activity,
    Calendar,
    Refresh,
    TrendUp,
    InfoCircle
} from "iconsax-react";
import Button from "../../components/Button";
import DatePicker from "../../components/DatePicker";
import TitleLine from "../../components/TitleLine";
import PageLoading from "../../components/PageLoading";
// import Error from "../../components/Error"; // Using custom error display
import StatsDashboard from "./components/StatsDashboard";
import { useAccessLogStats } from "./hooks/useAccessLogs";
import { AccessLogStatsQueryDto } from "./types/AccessLogTypes";

const AccessLogsStats: React.FC = () => {
    const { stats, topUsers, loading, error, fetchStats } = useAccessLogStats();

    const [filters, setFilters] = useState<AccessLogStatsQueryDto>({
        startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 30 days ago
        endDate: new Date().toISOString().split('T')[0], // today
        limit: 10,
    });

    const handleFilterChange = (newFilters: Partial<AccessLogStatsQueryDto>) => {
        const updatedFilters = { ...filters, ...newFilters };
        setFilters(updatedFilters);
    };

    const handleRefresh = () => {
        fetchStats(filters);
    };

    const setPresetDateRange = (days: number) => {
        const endDate = new Date().toISOString().split('T')[0];
        const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

        handleFilterChange({ startDate, endDate });
    };

    useEffect(() => {
        fetchStats(filters);
    }, [filters, fetchStats]);

    if (error) {
        return (
            <div className="p-6">
                <TitleLine title="آمار لاگ‌های دسترسی" />
                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="flex items-center justify-between">
                        <p className="text-red-800">{error}</p>
                        <Button
                            onClick={handleRefresh}
                            className="bg-red-600 text-white hover:bg-red-700"
                        >
                            تلاش مجدد
                        </Button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <TitleLine title="آمار لاگ‌های دسترسی" />
                    <p className="text-gray-600 mt-2">
                        تحلیل و بررسی آماری فعالیت‌های سیستم
                    </p>
                </div>

                <Button
                    onClick={handleRefresh}
                    disabled={loading}
                    className="flex items-center gap-2 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                >
                    <Refresh size={16} className={loading ? "animate-spin" : ""} />
                    بروزرسانی
                </Button>
            </div>

            {/* Date Range Filter */}
            <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                        <Calendar size={20} className="text-gray-600" />
                        <h3 className="text-lg font-semibold text-gray-900">بازه زمانی</h3>
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            از تاریخ
                        </label>
                        <DatePicker
                            defaulValue={filters.startDate || ""}
                            onChange={(value: string) => handleFilterChange({ startDate: value })}
                            placeholder="انتخاب تاریخ شروع"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            تا تاریخ
                        </label>
                        <DatePicker
                            defaulValue={filters.endDate || ""}
                            onChange={(value: string) => handleFilterChange({ endDate: value })}
                            placeholder="انتخاب تاریخ پایان"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            حداکثر نتایج
                        </label>
                        <select
                            value={filters.limit || 10}
                            onChange={(e) => handleFilterChange({ limit: parseInt(e.target.value) })}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            disabled={loading}
                        >
                            <option value={5}>5</option>
                            <option value={10}>10</option>
                            <option value={20}>20</option>
                            <option value={50}>50</option>
                        </select>
                    </div>
                </div>

                {/* Quick Date Range Buttons */}
                <div className="flex flex-wrap gap-2">
                    <Button
                        onClick={() => setPresetDateRange(1)}
                        disabled={loading}
                        className="text-sm px-3 py-1 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                    >
                        امروز
                    </Button>
                    <Button
                        onClick={() => setPresetDateRange(7)}
                        disabled={loading}
                        className="text-sm px-3 py-1 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                    >
                        7 روز گذشته
                    </Button>
                    <Button
                        onClick={() => setPresetDateRange(30)}
                        disabled={loading}
                        className="text-sm px-3 py-1 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                    >
                        30 روز گذشته
                    </Button>
                    <Button
                        onClick={() => setPresetDateRange(90)}
                        disabled={loading}
                        className="text-sm px-3 py-1 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                    >
                        3 ماه گذشته
                    </Button>
                    <Button
                        onClick={() => setPresetDateRange(365)}
                        disabled={loading}
                        className="text-sm px-3 py-1 border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                    >
                        سال گذشته
                    </Button>
                </div>
            </div>

            {/* Loading State */}
            {loading && <PageLoading />}

            {/* Stats Dashboard */}
            {!loading && (
                <StatsDashboard
                    stats={stats}
                    topUsers={topUsers}
                    loading={loading}
                />
            )}

            {/* Info Panel */}
            {!loading && (!stats?.operationStats.length || !topUsers?.topUsers.length) && (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
                    <div className="flex items-start gap-3">
                        <InfoCircle size={24} className="text-blue-600 flex-shrink-0 mt-0.5" />
                        <div>
                            <h3 className="text-lg font-medium text-blue-900 mb-2">اطلاعات</h3>
                            <div className="text-blue-700 space-y-2">
                                <p>• آمار بر اساس بازه زمانی انتخاب شده محاسبه می‌شود</p>
                                <p>• برای مشاهده آمار دقیق‌تر، بازه زمانی مناسب انتخاب کنید</p>
                                <p>• امکان خروجی گرفتن از آمار در قالب CSV موجود است</p>
                                <p>• آمار به صورت لحظه‌ای بروزرسانی می‌شود</p>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Additional Stats Info */}
            {!loading && stats && topUsers && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <div className="flex items-center gap-2 mb-4">
                            <Activity size={20} className="text-blue-600" />
                            <h3 className="text-lg font-semibold text-gray-900">خلاصه عملیات</h3>
                        </div>
                        <div className="space-y-3">
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">کل نوع عملیات:</span>
                                <span className="font-semibold text-gray-900">
                                    {(stats?.operationStats?.length || 0).toLocaleString('fa-IR')}
                                </span>
                            </div>
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">کل فعالیت:</span>
                                <span className="font-semibold text-gray-900">
                                    {(stats?.operationStats?.reduce((sum: number, stat: any) => sum + stat.count, 0) || 0).toLocaleString('fa-IR')}
                                </span>
                            </div>
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">میانگین فعالیت روزانه:</span>
                                <span className="font-semibold text-gray-900">
                                    {filters.startDate && filters.endDate ?
                                        Math.round(stats.operationStats.reduce((sum: number, stat: any) => sum + stat.count, 0) /
                                            Math.max(1, Math.ceil((new Date(filters.endDate).getTime() - new Date(filters.startDate).getTime()) / (1000 * 60 * 60 * 24)))).toLocaleString('fa-IR')
                                        : '-'
                                    }
                                </span>
                            </div>
                        </div>
                    </div>

                    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <div className="flex items-center gap-2 mb-4">
                            <TrendUp size={20} className="text-green-600" />
                            <h3 className="text-lg font-semibold text-gray-900">خلاصه کاربران</h3>
                        </div>
                        <div className="space-y-3">
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">کل کاربران فعال:</span>
                                <span className="font-semibold text-gray-900">
                                    {(topUsers?.topUsers?.length || 0).toLocaleString('fa-IR')}
                                </span>
                            </div>
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">بیشترین فعالیت:</span>
                                <span className="font-semibold text-gray-900">
                                    {topUsers.topUsers.length > 0 ?
                                        (topUsers?.topUsers?.[0]?.activityCount || 0).toLocaleString('fa-IR') :
                                        '0'
                                    }
                                </span>
                            </div>
                            <div className="flex justify-between items-center">
                                <span className="text-gray-600">میانگین فعالیت کاربر:</span>
                                <span className="font-semibold text-gray-900">
                                    {topUsers.topUsers.length > 0 ?
                                        Math.round((topUsers?.topUsers?.reduce((sum: number, user: any) => sum + user.activityCount, 0) || 0) / (topUsers?.topUsers?.length || 1)).toLocaleString('fa-IR') :
                                        '0'
                                    }
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default AccessLogsStats;
