'use client';

import React, { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
// import api from '@/utils/api'; // Previous attempt
import { api } from '@/services/api'; // New attempt, assuming api.ts is in src/services/
import LoadingSpinner from '@/components/LoadingSpinner';

interface ParkingSpot {
    id: number;
    spotUid: string;
    locationDescription?: string;
    status: string; // Expecting "AVAILABLE"
}

export default function RequestChargingPage() {
    const { isAuthenticated, isLoading: authLoading } = useAuth();
    const router = useRouter();

    const [parkingSpots, setParkingSpots] = useState<ParkingSpot[]>([]);
    const [selectedSpotId, setSelectedSpotId] = useState<number | null>(null);
    const [isLoadingSpots, setIsLoadingSpots] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);

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

    useEffect(() => {
        if (isAuthenticated) {
            const fetchAvailableSpots = async () => {
                setIsLoadingSpots(true);
                try {
                    // Corrected path
                    const response = await api.get('/parking-spot/list/available-assignable'); 
                    if (response.data && response.data.code === 0) {
                        setParkingSpots(response.data.data || []);
                    } else {
                        setError(response.data.message || '获取可用车位失败');
                        setParkingSpots([]);
                    }
                } catch (err: any) {
                    setError(err.message || '加载车位列表时发生网络错误');
                    setParkingSpots([]);
                }
                setIsLoadingSpots(false);
            };
            fetchAvailableSpots();
        }
    }, [isAuthenticated]);

    const handleSelectSpot = (spotId: number) => {
        setSelectedSpotId(spotId);
    };

    const handleSubmitRequest = async () => {
        if (!selectedSpotId) {
            setError('请先选择一个车位。');
            return;
        }
        setIsSubmitting(true);
        setError(null);
        try {
            // Corrected path
            const response = await api.post('/session/request', { spotId: selectedSpotId });
            if (response.data && response.data.code === 0) {
                const sessionId = response.data.data;
                // TODO: Navigate to a session status page or show success message
                // For now, navigate to dashboard and show an alert
                alert(`充电请求成功！会话ID: ${sessionId}. 机器人正在前往...`);
                router.push('/dashboard'); 
            } else {
                setError(response.data.message || '发起充电请求失败');
            }
        } catch (err: any) {
            setError(err.response?.data?.message || err.message || '发起充电请求时发生错误');
        }
        setIsSubmitting(false);
    };

    if (authLoading || isLoadingSpots) {
        // Layout will be applied by Next.js, just return the specific loading state for this page
        return (
            <div className="flex items-center justify-center h-[calc(100vh-150px)]"> {/* Adjust height if needed based on header/footer size*/}
                <LoadingSpinner />
            </div>
        );
    }
    
    if (!isAuthenticated) {
        // This case should ideally be handled by redirect in useEffect, 
        // but as a fallback or if redirect hasn't happened yet.
        return (
            <div className="p-4 text-center">
                <p>请先登录后访问此页面。</p>
                <LoadingSpinner /> {/* Or a link to login */}
            </div>
        );
    }

    return (
        <div className="container mx-auto p-4 md:p-8">
            <header className="mb-8">
                <h1 className="text-3xl font-bold text-gray-800">选择充电车位</h1>
                <p className="text-gray-600 mt-1">请从下方选择一个可用的车位开始充电。</p>
            </header>

            {error && (
                <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                    <strong className="font-bold">错误! </strong>
                    <span className="block sm:inline">{error}</span>
                </div>
            )}

            {parkingSpots.length === 0 && !isLoadingSpots && !error && (
                 <div className="text-center text-gray-500 py-10">
                    <p className="text-xl mb-2">当前没有可用的充电车位。</p>
                    <p>请稍后再试。</p>
                </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 mb-8">
                {parkingSpots.map((spot) => (
                    <div
                        key={spot.id}
                        onClick={() => handleSelectSpot(spot.id)}
                        className={`p-6 rounded-xl shadow-lg cursor-pointer transition-all duration-200 ease-in-out 
                                    ${selectedSpotId === spot.id 
                                        ? 'bg-indigo-500 text-white ring-4 ring-indigo-300 scale-105' 
                                        : 'bg-white hover:shadow-xl hover:scale-102'}`}
                    >
                        <h3 className={`text-xl font-semibold mb-2 ${selectedSpotId === spot.id ? 'text-white' : 'text-gray-700'}`}>
                            车位: {spot.spotUid}
                        </h3>
                        {spot.locationDescription && (
                            <p className={`text-sm ${selectedSpotId === spot.id ? 'text-indigo-100' : 'text-gray-500'}`}>
                                位置: {spot.locationDescription}
                            </p>
                        )}
                        <p className={`text-sm font-medium mt-3 ${selectedSpotId === spot.id ? 'text-green-300' : 'text-green-500'}`}>
                            {spot.status === 'AVAILABLE' ? '可用' : spot.status}
                        </p>
                    </div>
                ))}
            </div>

            {parkingSpots.length > 0 && (
                <div className="text-center">
                    <button
                        onClick={handleSubmitRequest}
                        disabled={!selectedSpotId || isSubmitting}
                        className="bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-8 rounded-lg shadow-md transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center mx-auto"
                    >
                        {isSubmitting ? (
                            <>
                                <svg className="animate-spin -ml-1 mr-3 h-5 w-5 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>
                                请求中...
                            </>
                        ) : (
                            '确认选择并请求充电'
                        )}
                    </button>
                </div>
            )}
        </div>
    );
} 