'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import LoadingSpinner from '@/components/LoadingSpinner';
import { api } from '@/services/api'; // 新的API实例导入
import { BaseResponse } from '@/types/api';   // 新的BaseResponse导入
import { FiDollarSign, FiZap, FiClock, FiList, FiChevronRight, FiInfo, FiPower, FiAlertCircle, FiGift } from 'react-icons/fi';
import { Button, Modal, message } from 'antd'; // 确保Button和Modal已导入
import RedeemCodeForm from '@/components/RedeemCodeForm'; // 导入兑换表单组件

// Interface for active charging session (matches ChargingSessionVO fields used)
interface ActiveChargingSession {
    id: number;
    spotUidSnapshot: string | null;
    chargeStartTime: string | null; // 后端是 Date 类型，前端收到的是 string
    status: string; // 例如 "CHARGING_STARTED"
    // 可以按需添加其他来自后端 ChargingSession 实体的字段
    robotUidSnapshot?: string | null;
    requestTime?: string | null;
}

// Interface for user dashboard statistics from backend
interface UserDashboardStats {
    monthlySessions: number; // 后端返回的可能是 monthlyCharges 字段
    monthlySpending: number;
}

export default function DashboardPage() {
    const { user, isAuthenticated, isLoading: authLoading, logout, checkAuth } = useAuth();
    const router = useRouter();

    const [activeSession, setActiveSession] = useState<ActiveChargingSession | null | undefined>(undefined);
    const [userStats, setUserStats] = useState<UserDashboardStats | null | undefined>(undefined);
    const [dataLoading, setDataLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [isStopping, setIsStopping] = useState(false);
    const [isRedeemModalVisible, setIsRedeemModalVisible] = useState(false); // Modal状态

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

    const fetchData = useCallback(async () => {
        if (!isAuthenticated || user?.role !== 'user') return;

        setDataLoading(true);
        setError(null);
        try {
            const [sessionResult, statsResult] = await Promise.all([
                api.get<BaseResponse<ActiveChargingSession | null>>('/session/my/active'),
                api.get<BaseResponse<UserDashboardStats>>('/user/stats/mine')
            ]);

            if (sessionResult.data && sessionResult.data.code === 0) {
                setActiveSession(sessionResult.data.data);
            } else {
                setActiveSession(null);
            }

            if (statsResult.data && statsResult.data.code === 0 && statsResult.data.data) {
                const statsData = statsResult.data.data;
                setUserStats({
                    monthlySessions: (statsData as any).monthlyCharges !== undefined ? (statsData as any).monthlyCharges : statsData.monthlySessions,
                    monthlySpending: statsData.monthlySpending
                });
            } else {
                setUserStats(null);
            }

        } catch (err: any) {
            console.error("Error fetching dashboard data:", err);
            const errorMessage = err.response?.data?.message || err.message || '获取仪表盘数据失败';
            setError(prevError => prevError ? `${prevError}\n${errorMessage}` : errorMessage);
            setActiveSession(null);
            setUserStats(null);
        }
        setDataLoading(false);
    }, [isAuthenticated, user]);

    useEffect(() => {
        if (isAuthenticated && user?.role === 'user') {
            fetchData();
        } else if (!authLoading && !isAuthenticated) {
            setDataLoading(false);
        }
    }, [fetchData, isAuthenticated, user, authLoading]);

    // 直接从仪表盘停止充电
    const handleStopCharging = async () => {
        if (!activeSession || !activeSession.id) {
            message.error("无法停止充电：无效的会话信息。"); // 使用 antd message
            return;
        }
        setIsStopping(true);
        setError(null);
        try {
            const response = await api.post<BaseResponse<any>>(`/session/stop`, { sessionId: activeSession.id });
            if (response.data && response.data.code === 0) {
                fetchData();
                message.success('已成功发送停止充电请求。');
            } else {
                setError(response.data?.message || "停止充电请求失败");
                message.error(response.data?.message || "停止充电请求失败");
            }
        } catch (err: any) {
            console.error("Error stopping charging session:", err);
            const msg = err.response?.data?.message || err.message || "停止充电时发生错误";
            setError(msg);
            message.error(msg);
        } finally {
            setIsStopping(false);
        }
    };

    if (authLoading || (dataLoading && user?.role === 'user')) {
        return <LoadingSpinner />;
    }

    if (!isAuthenticated || !user) {
        return <LoadingSpinner />; // Or a specific message, though redirect should handle
    }
    
    if (user.role !== 'user') {
        // This case should ideally be handled by the redirect in the first useEffect
        // but as a fallback:
        return <div className="p-4 text-center">非用户角色，正在尝试重定向...</div>;
    }

    const StatCard = ({ title, value, icon, unit, isLoading }: { title: string; value: string | number; icon: React.ReactNode; unit?: string; isLoading?: boolean }) => (
        <div className={`bg-white p-6 rounded-xl shadow-lg flex items-center space-x-4 ${isLoading ? 'animate-pulse' : ''}`}>
            <div className={`p-3 rounded-full ${isLoading ? 'bg-gray-200' : 'bg-indigo-100 text-indigo-600'}`}>
                {!isLoading && icon}
            </div>
            <div>
                <p className="text-sm text-gray-500">{title}</p>
                {isLoading ? (
                    <div className="h-6 bg-gray-200 rounded w-20 mt-1"></div>
                ) : (
                    <p className="text-2xl font-semibold text-gray-800">
                        {value} {unit && <span className="text-sm text-gray-500">{unit}</span>}
                    </p>
                )}
            </div>
        </div>
    );

    const formatMonthlySpending = (spending: number | undefined | null): string => {
        if (typeof spending === 'number') {
            return `¥${spending.toFixed(2)}`;
        }
        return '--';
    };

    const handleRedeemSuccess = () => {
        setIsRedeemModalVisible(false);
        checkAuth(); // 刷新用户数据，尤其是余额
        // fetchData(); // 也可以选择刷新整个仪表盘数据，如果余额不通过checkAuth更新
        message.success('激活码已成功兑换，余额已更新!');
    };

    return (
        <div className="min-h-screen bg-gray-100 p-4 md:p-8">
            <div className="max-w-4xl mx-auto">
                <header className="mb-8 flex justify-between items-center">
                    <h1 className="text-3xl font-bold text-gray-800">用户中心</h1>
                    <Button 
                        type="primary"
                        icon={<FiGift className="mr-2" />}
                        onClick={() => setIsRedeemModalVisible(true)}
                    >
                        兑换激活码
                    </Button>
                </header>

                <div className="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h2 className="text-2xl font-semibold text-gray-700 mb-2">欢迎, {user.username}!</h2>
                    <p className="text-gray-600 mb-1"><span className="font-medium">用户ID:</span> {user.id}</p>
                    <p className="text-gray-600 mb-1"><span className="font-medium">角色:</span> {user.role === 'user' ? '普通用户' : user.role}</p>
                    <p className="text-gray-600"><span className="font-medium">账户余额:</span> <span className="text-lg font-semibold text-green-600">¥{user.balance?.toFixed(2) ?? 'N/A'}</span></p>
                </div>

                {error && (
                    <div className="mb-4 p-4 bg-red-100 text-red-700 border border-red-300 rounded-md whitespace-pre-line">
                        <p>{error}</p>
                    </div>
                )}

                {/* Statistics Section */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                    <StatCard 
                        title="本月充电次数" 
                        value={userStats?.monthlySessions ?? '--'} 
                        icon={<FiZap size={24} />} 
                        unit="次" 
                        isLoading={dataLoading || userStats === undefined}
                    />
                    <StatCard 
                        title="本月总消费" 
                        value={formatMonthlySpending(userStats?.monthlySpending)} 
                        icon={<FiDollarSign size={24} />} 
                        isLoading={dataLoading || userStats === undefined}
                    />
                </div>
                
                {/* Current Charging Session Status */}
                <div className="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 className="text-xl font-semibold text-gray-700 mb-3 flex items-center">
                        <span className="mr-2 text-indigo-600"><FiClock size={22} /></span> 当前充电状态
                    </h3>
                    {dataLoading || activeSession === undefined ? (
                         <div className="animate-pulse">
                            <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
                            <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                         </div>
                    ) : activeSession ? (
                        <div>
                            <p className="text-gray-700"><span className="font-medium">状态:</span> <span className="text-green-500 font-semibold">{activeSession.status || '进行中'}</span></p>
                            <p className="text-gray-600"><span className="font-medium">车位:</span> {activeSession.spotUidSnapshot || 'N/A'}</p>
                            <p className="text-gray-600"><span className="font-medium">开始时间:</span> {activeSession.chargeStartTime ? new Date(activeSession.chargeStartTime).toLocaleString() : 'N/A'}</p>
                            
                            {/* 操作按钮区域 */}
                            <div className="mt-6 flex flex-col md:flex-row gap-3">
                                {/* 前往充电状态详情页的按钮 */}
                                <Link href={`/charging-status?id=${activeSession.id}`} className="inline-block bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 px-4 rounded-md shadow-sm transition duration-150 ease-in-out text-center">
                                    查看详细状态
                                </Link>
                                
                                {/* 仅在特定状态下显示停止充电按钮 */}
                                {(activeSession.status === 'CHARGING_STARTED' || 
                                  activeSession.status === 'CHARGING_IN_PROGRESS' || 
                                  activeSession.status === 'ROBOT_ARRIVED' || 
                                  activeSession.status === 'ROBOT_ASSIGNED') && (
                                    <button
                                        onClick={handleStopCharging}
                                        disabled={isStopping}
                                        className="bg-red-500 hover:bg-red-600 text-white font-semibold py-2 px-4 rounded-md shadow-sm transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
                                    >
                                        {isStopping ? (
                                            <>
                                                <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                </svg>
                                                处理中...
                                            </>
                                        ) : (
                                            <><FiPower className="mr-2" />停止充电</>
                                        )}
                                    </button>
                                )}
                            </div>
                            
                            {error && (
                                <div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-md text-sm text-red-700 flex items-center">
                                    <FiAlertCircle className="mr-2" />
                                    {error}
                                </div>
                            )}
                            
                            <p className="text-xs text-gray-500 mt-3">您可以查看充电详情或直接停止充电</p>
                        </div>
                    ) : (
                        <p className="text-gray-600 flex items-center"><FiInfo className="mr-2 text-blue-500" />暂无正在进行的充电。</p>
                    )}
                </div>

                {/* Action Card/Button to Start New Charging Session */}
                <div className="bg-gradient-to-r from-blue-500 to-indigo-600 p-6 md:p-8 rounded-xl shadow-xl text-white text-center">
                    <h3 className="text-2xl font-bold mb-4">开始新的充电之旅</h3>
                    <p className="mb-6 text-blue-100">
                        选择一个可用的车位，让我们的智能机器人为您服务。
                    </p>
                    <Link href="/request-charging" className="inline-block bg-white hover:bg-gray-100 text-indigo-600 font-bold py-3 px-8 rounded-lg shadow-md transform hover:scale-105 transition duration-300 ease-in-out">
                        查找车位并充电
                    </Link>
                </div>

                {/* Link to view charging history */}
                <div className="mt-8 text-center">
                    <Link href="/my-sessions" className="text-indigo-600 hover:text-indigo-800 font-medium flex items-center justify-center">
                       <span className="mr-2"><FiList size={20}/></span> 查看我的充电记录
                    </Link>
                </div>
            </div>

            <Modal
                title="兑换激活码"
                open={isRedeemModalVisible}
                onCancel={() => setIsRedeemModalVisible(false)}
                footer={null} // RedeemCodeForm 内部有自己的提交和取消逻辑
                destroyOnClose // 关闭时销毁内部组件状态
            >
                <RedeemCodeForm 
                    onSuccess={handleRedeemSuccess}
                    onCancel={() => setIsRedeemModalVisible(false)} // Modal 的取消按钮也调用此 handler
                />
            </Modal>

        </div>
    );
} 