'use client';

import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import LoadingSpinner from '@/components/LoadingSpinner';
import { FiUsers, FiCpu, FiBarChart2, FiGrid, FiUserCheck, FiList, FiTerminal, FiSettings, FiGift } from 'react-icons/fi';
import { api } from '@/services/api';
import { BaseResponse } from '@/types/api';
import { AxiosError, AxiosResponse } from 'axios';

// 匹配后端 AdminDashboardStatsVO
interface AdminStats {
    totalUsers: number;
    totalRobots: number;      // 后端有这个字段
    onlineRobots: number;
    chargingRobots: number;
    idleRobots: number;
    activeSessions: number;   // 后端叫 activeSessions
    totalRevenue: number;     // 后端叫 totalRevenue
    totalParkingSpots?: number; // 新增，设为可选以处理数据可能暂时未返回的情况
    availableParkingSpots?: number; // 新增，设为可选
    // 下面两个字段在当前的后端 AdminDashboardStatsVO 中不存在，但在前端 AdminStats 接口中存在
    // totalChargingSessionsToday: number; 
    // totalRevenueToday: number;
    // 下面这两个字段也需要确认后端VO中是否有对应，暂时先用后端有的字段
    // totalParkingSpots: number;
    // availableParkingSpots: number;
}

const AdminDashboardPage = () => {
    const { user, isLoading, isAuthenticated } = useAuth();
    const router = useRouter();
    const [adminStats, setAdminStats] = useState<AdminStats | null>(null);
    const [statsLoading, setStatsLoading] = useState(true);
    const [statsError, setStatsError] = useState<string | null>(null);

    useEffect(() => {
        if (!isLoading && !isAuthenticated) {
            router.replace('/login');
            return; 
        }
        if (isAuthenticated && user?.role !== 'admin') {
            router.replace('/dashboard');
        }
    }, [isLoading, isAuthenticated, user, router]);

    useEffect(() => {
        if (isAuthenticated && user?.role === 'admin') {
            setStatsLoading(true);
            setStatsError(null);
            api.get<BaseResponse<AdminStats>>('/admin/stats/summary')
                .then((response: AxiosResponse<BaseResponse<AdminStats>>) => {
                    if (response.data && response.data.code === 0 && response.data.data) {
                        setAdminStats(response.data.data);
                    } else {
                        console.error("Failed to fetch admin stats or data is null/malformed:", response.data?.message);
                        setStatsError(response.data?.message || "加载统计数据失败: 数据为空或格式错误。");
                        setAdminStats(null);
                    }
                })
                .catch((error: AxiosError<BaseResponse<unknown>>) => {
                    console.error("Failed to fetch admin stats:", error);
                    const backendMessage = error.response?.data?.message;
                    if (backendMessage) {
                        setStatsError(`加载统计数据失败: ${backendMessage}`);
                    } else if (error.response) {
                        setStatsError(`加载统计数据失败: ${error.response.status} ${error.response.statusText}`);
                    } else if (error.request) {
                        setStatsError("加载统计数据失败: 未收到服务器响应。");
                    } else {
                        setStatsError("加载统计数据失败: 请求设置时出错。");
                    }
                    setAdminStats(null);
                })
                .finally(() => {
                    setStatsLoading(false);
                });
        }
    }, [isAuthenticated, user]);

    if (isLoading || (!isLoading && !isAuthenticated)) {
        return <LoadingSpinner />;
    }
    
    if (isAuthenticated && user?.role !== 'admin') {
        return <LoadingSpinner />;
    }

    if (!user) {
        return <LoadingSpinner />;
    }

    const StatCard = ({ title, value, icon, subValue, unit }: { title: string; value: string | number; icon: React.ReactNode; subValue?: string, unit?: string }) => (
        <div className="bg-white p-5 rounded-xl shadow-lg flex items-start space-x-3 transform transition-all hover:shadow-xl hover:-translate-y-1 min-h-[100px]">
            <div className="p-3 bg-indigo-100 text-indigo-600 rounded-full">
                {icon}
            </div>
            <div>
                <p className="text-sm text-gray-500 font-medium">{title}</p>
                <p className="text-2xl font-bold text-gray-800">
                    {value}
                    {unit && <span className="text-lg ml-1">{unit}</span>}
                </p>
                {subValue && <p className="text-xs text-gray-400 mt-1">{subValue}</p>}
            </div>
        </div>
    );

    const NavCard = ({ title, description, href, icon, disabled }: { title: string; description: string; href: string; icon: React.ReactNode; disabled?: boolean }) => (
        <Link 
            href={disabled ? '#' : href} 
            legacyBehavior={false} 
            className={`block p-6 rounded-lg shadow-lg transform transition-all hover:shadow-xl hover:scale-105 
                ${disabled ? 'bg-gray-200 cursor-not-allowed' : 'bg-gradient-to-br from-indigo-600 to-blue-500 hover:from-indigo-700 hover:to-blue-600 text-white'}
            `}
            onClick={(e) => { 
                if (disabled) { 
                    e.preventDefault(); 
                }
            }}
            aria-disabled={disabled}
        >
            <div className="flex items-center mb-2">
                <span className={disabled ? 'text-gray-500' : 'text-indigo-100'}>{icon}</span>
                <h3 className={`ml-3 text-xl font-semibold ${disabled ? 'text-gray-700' : 'text-white'}`}>{title}</h3>
            </div>
            <p className={`text-sm ${disabled ? 'text-gray-600' : 'opacity-90 text-indigo-50'}`}>{description}</p>
        </Link>
    );

    return (
        <div className="min-h-screen bg-gray-100 py-8 px-4 md:px-6 lg:px-8">
            <div className="max-w-7xl mx-auto">
                
                <h1 className="text-3xl font-bold text-gray-800 mb-8">管理员控制台</h1>

                <div className="mb-10">
                    <h2 className="text-2xl font-semibold text-gray-700 mb-4">系统概览</h2>
                    {statsLoading ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                            {[...Array(4)].map((_, i) => (
                                <div key={i} className="bg-white p-5 rounded-xl shadow-lg h-28 animate-pulse">
                                    <div className="h-6 bg-gray-200 rounded w-1/3 mb-2"></div>
                                    <div className="h-8 bg-gray-300 rounded w-1/2"></div>
                                </div>
                            ))}
                        </div>
                    ) : statsError ? (
                        <p className="text-red-600 bg-red-100 p-4 rounded-md">{statsError}</p>
                    ) : adminStats ? (
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                            <StatCard title="总用户数" value={adminStats.totalUsers ?? '--'} icon={<FiUsers size={24} />} />
                            <StatCard 
                                title="机器人状态 (在线/充电/空闲)" 
                                value={`${adminStats.onlineRobots ?? '--'} / ${adminStats.chargingRobots ?? '--'} / ${adminStats.idleRobots ?? '--'}`}
                                icon={<FiCpu size={24} />}
                            />
                            <StatCard 
                                title="车位统计 (总数/可用)" 
                                value={`${adminStats.totalParkingSpots ?? '--'} / ${adminStats.availableParkingSpots ?? '--'}`}
                                icon={<FiGrid size={24} />}
                            />
                            <StatCard 
                                title="概览 (活动会话/总收入)" 
                                value={`${adminStats.activeSessions ?? '--'} / ¥${(adminStats.totalRevenue ?? 0).toFixed(2)}`}
                                icon={<FiBarChart2 size={24} />}
                            />
                        </div>
                    ) : (
                        <p className="text-gray-600">当前无系统统计数据。</p>
                    )}
                </div>

                <div>
                    <h2 className="text-2xl font-semibold text-gray-700 mb-4">管理模块</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <NavCard 
                            title="车位管理"
                            description="管理充电车位信息、状态等"
                            href="/admin/parking-spots"
                            icon={<FiGrid size={28}/>}
                        />
                        <NavCard 
                            title="机器人管理"
                            description="管理充电机器人、状态、任务分配"
                            href="/admin/robots"
                            icon={<FiTerminal size={28}/>}
                        />
                        <NavCard 
                            title="用户管理"
                            description="查看和管理平台用户列表"
                            href="/admin/user-management"
                            icon={<FiUserCheck size={28}/>}
                        />
                        <NavCard 
                            title="激活码管理"
                            description="生成、查询和管理激活码"
                            href="/admin/activation-codes"
                            icon={<FiGift size={28}/>}
                        />
                        <NavCard 
                            title="MQTT日志"
                            description="查看所有MQTT通信消息"
                            href="/admin/mqtt-logs"
                            icon={<FiList size={28}/>}
                        />
                    </div>
                </div>

            </div>
        </div>
    );
};

export default AdminDashboardPage;