'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, BaseResponse } from '@/utils/axios';
import { FiChevronLeft, FiClock, FiZap, FiDollarSign, FiList, FiHash, FiCalendar, FiCheckCircle, FiXCircle, FiAlertTriangle, FiAlertOctagon } from 'react-icons/fi';

// Interface matching backend ChargingSessionVO
interface ChargingSession {
    id: number;
    spotUidSnapshot: string | null;
    chargeStartTime: string | null;
    chargeEndTime: string | null;
    totalDurationSeconds: number | null;
    cost: number | null;
    status: string;
    statusText?: string;
    energyConsumedKwh?: number | null;
}

// Interface for the Page object from backend
interface Page<T> {
    records: T[];
    total: number;
    size: number;
    current: number;
    pages?: number;
}

// Helper function to format duration
const formatDuration = (seconds: number | null | undefined): string => {
    if (seconds === null || seconds === undefined || seconds < 0) return 'N/A';
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    return `${h > 0 ? `${h}小时 ` : ''}${m}分钟`;
};

// Helper function to get status display
const getStatusDisplay = (status: string | null | undefined) => {
    switch (status) {
        case 'COMPLETED':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"><FiCheckCircle className="mr-1" /> 已完成</span>;
        case 'CANCELLED_BY_USER':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800"><FiXCircle className="mr-1" /> 用户取消</span>;
        case 'CANCELLED_BY_SYSTEM':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"><FiAlertTriangle className="mr-1" /> 系统取消</span>;
        case 'PAYMENT_PENDING':
             return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"><FiClock className="mr-1" /> 待支付</span>;
        case 'CHARGING_IN_PROGRESS':
             return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-teal-100 text-teal-800"><FiZap className="mr-1" /> 充电中</span>;
        case 'ENDED_AWAITING_PAYMENT':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800"><FiDollarSign className="mr-1" /> 待结账</span>;
        case 'ERROR':
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-200 text-red-900"><FiAlertOctagon className="mr-1" /> 错误</span>;
        default:
            return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">{status || '未知'}</span>;
    }
};

export default function MySessionsPage() {
    const { user, isAuthenticated, isLoading: authLoading } = useAuth();
    const router = useRouter();
    
    const [sessions, setSessions] = useState<ChargingSession[]>([]);
    const [sessionsLoading, setSessionsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0);
    const itemsPerPage = 10;

    useEffect(() => {
        if (!authLoading && !isAuthenticated) {
            router.replace('/login');
        }
    }, [authLoading, isAuthenticated, router]);

    const fetchSessions = useCallback(async (page: number) => {
        if (!isAuthenticated || user?.role !== 'user') return;

        setSessionsLoading(true);
        setError(null);
        try {
            const response = await api.post<BaseResponse<Page<ChargingSession>>>('/api/session/my/list/page', {
                current: page,
                pageSize: itemsPerPage,
            });
            
            console.log("充电记录响应：", response.data);

            if (response.data && response.data.code === 0 && response.data.data) {
                const pageData = response.data.data;
                setSessions(pageData.records || []);
                setTotalPages(Math.ceil(pageData.total / itemsPerPage));
                setCurrentPage(pageData.current);
            } else {
                console.warn("获取充电记录失败或数据为空:", response.data?.message);
                setSessions([]);
                setTotalPages(0);
            }
        } catch (err: any) {
            console.error("Error fetching charging sessions:", err);
            setError(err.response?.data?.message || err.message || '获取充电记录失败，请稍后再试。');
            setSessions([]);
            setTotalPages(0);
        }
        setSessionsLoading(false);
    }, [isAuthenticated, user, itemsPerPage]);

    useEffect(() => {
        fetchSessions(currentPage);
    }, [fetchSessions, currentPage]);

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

    if (!user || user.role === 'admin') { 
        return <div className="p-4">此页面仅供普通用户查看自己的充电记录。</div>;
    }
    
    const handlePageChange = (newPage: number) => {
        if (newPage >= 1 && newPage <= totalPages) {
            fetchSessions(newPage);
        }
    };

    return (
        <div className="min-h-screen bg-gray-100 p-4 md:p-6 lg:p-8">
            <div className="max-w-6xl mx-auto">
                <header className="mb-6 md:mb-8">
                    <div className="flex flex-col md:flex-row items-start md:items-center justify-between">
                        <h1 className="text-2xl md:text-3xl font-bold text-gray-800 flex items-center mb-4 md:mb-0">
                            <FiList className="mr-3 text-indigo-600" /> 我的充电记录
                        </h1>
                        <Link href="/dashboard" className="flex items-center text-sm text-indigo-600 hover:text-indigo-800 font-medium">
                            <FiChevronLeft className="mr-1" /> 返回用户中心
                        </Link>
                    </div>
                </header>

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

                {sessionsLoading && !sessions.length ? (
                    <LoadingSpinner />
                ) : !sessionsLoading && sessions.length === 0 && !error ? (
                    <div className="text-center py-12 bg-white rounded-xl shadow-lg">
                        <FiList size={48} className="mx-auto text-gray-400 mb-4" />
                        <h3 className="text-xl font-medium text-gray-700">暂无充电记录</h3>
                        <p className="text-sm text-gray-500 mt-1">您还没有任何充电会话，开始新的充电吧！</p>
                        <Link href="/request-charging" className="mt-4 inline-block bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out">
                            前往充电
                        </Link>
                    </div>
                ) : sessions.length > 0 ? (
                    <div className="bg-white rounded-xl shadow-lg overflow-x-auto">
                        {sessionsLoading && <div className="absolute inset-0 bg-white bg-opacity-50 flex items-center justify-center"><LoadingSpinner /></div>}
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">车位UID</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">开始时间</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">结束时间</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时长</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">费用</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">电量 (kWh)</th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {sessions.map((session) => (
                                    <tr key={session.id}>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900"><FiHash className="inline mr-1 text-gray-400"/>{session.spotUidSnapshot || 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiCalendar className="inline mr-1 text-gray-400"/>{session.chargeStartTime ? new Date(session.chargeStartTime).toLocaleString() : 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiCalendar className="inline mr-1 text-gray-400"/>{session.chargeEndTime ? new Date(session.chargeEndTime).toLocaleString() : 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiClock className="inline mr-1 text-gray-400"/>{formatDuration(session.totalDurationSeconds)}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiDollarSign className="inline mr-1 text-green-500"/>{session.cost !== null ? session.cost.toFixed(2) : 'N/A'}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm">{getStatusDisplay(session.status)}</td>
                                        <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500"><FiZap className="inline mr-1 text-yellow-500"/>{session.energyConsumedKwh !== null && session.energyConsumedKwh !== undefined ? `${session.energyConsumedKwh.toFixed(2)} kWh` : 'N/A'}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                ) : null }

                {totalPages > 1 && (
                    <div className="mt-6 flex justify-center items-center space-x-2">
                        <button
                            onClick={() => handlePageChange(currentPage - 1)}
                            disabled={currentPage === 1 || sessionsLoading}
                            className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            上一页
                        </button>
                        {[...Array(totalPages).keys()].map(number => (
                             <button
                                key={number + 1}
                                onClick={() => handlePageChange(number + 1)}
                                disabled={sessionsLoading}
                                className={`px-3 py-1 text-sm border rounded-md ${currentPage === number + 1 ? 'bg-indigo-600 text-white border-indigo-600' : 'border-gray-300 hover:bg-gray-50'} disabled:opacity-50 disabled:cursor-not-allowed`}
                            >
                                {number + 1}
                            </button>
                        ))}
                        <button
                            onClick={() => handlePageChange(currentPage + 1)}
                            disabled={currentPage === totalPages || sessionsLoading}
                            className="px-3 py-1 text-sm border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            下一页
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
} 