import React, { useState, useCallback, useEffect } from 'react';
import { ActivityIndicator, View, RefreshControl } from 'react-native';
import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import TabViewComponent, { TabItem } from './chargingRecord';
import { chargeStationService } from '../../service/chargeStationService';

const queryClient = new QueryClient();

interface BookingTabViewComponentProps {
    titles: string[];
}

// 更新 findStationByConnectorId 函数以增加安全性
const findStationByConnectorId = (allStations, targetConnectorId) => {
    if (!Array.isArray(allStations) || !targetConnectorId) {
        return undefined;
    }

    return allStations.find((station) =>
        station?.snapshot?.EquipmentInfos?.some((equipment) =>
            equipment?.ConnectorInfos?.some((connector) => connector?.ConnectorID === targetConnectorId)
        )
    );
};

const fetchReservationsAndStations = async () => {
    try {
        const [reservationResponse, allStationsResponse] = await Promise.allSettled([
            chargeStationService.fetchReservationHistories(),
            chargeStationService.fetchAllChargeStations()
        ]);

        const reservations = reservationResponse.status === 'fulfilled' ? reservationResponse.value : [];
        const stations = allStationsResponse.status === 'fulfilled' ? allStationsResponse.value : [];

        return {
            reservations: Array.isArray(reservations) ? reservations : [],
            stations: Array.isArray(stations) ? stations : []
        };
    } catch (error) {
        return { reservations: [], stations: [] };
    }
};

const processReservations = (reservations: any [], allStations: string [], isFuture: boolean): TabItem[] => {
    // 确保参数是数组类型
    const validReservations = Array.isArray(reservations) ? reservations : [];
    const validStations = Array.isArray(allStations) ? allStations : [];

    const now = Date.now();
    return validReservations
        .filter((reservation) => {
            // 添加安全检查
            if (!reservation || !reservation.end_time) return false;
            const endTime = Date.parse(reservation.end_time);
            if (isNaN(endTime)) return false;
            return isFuture ? endTime > now : endTime <= now;
        })
        .sort((a, b) => {
            // 添加安全检查
            if (!a?.end_time || !b?.end_time) return 0;
            const aTime = Date.parse(a.end_time);
            const bTime = Date.parse(b.end_time);
            if (isNaN(aTime) || isNaN(bTime)) return 0;
            return isFuture ? aTime - bTime : bTime - aTime;
        })
        .slice(0, 33)
        .map((reservation) => {
            // 添加对 reservation 的安全检查
            if (!reservation) {
                return {} as TabItem; // 返回默认对象
            }

            let snapshot = {} as any;
            let snapshot_price = {} as any;
            try {
                snapshot = reservation.connector.EquipmentID.StationID.snapshot ? JSON.parse(reservation.connector.EquipmentID.StationID.snapshot) : {};
                snapshot_price = reservation.snapshot ? JSON.parse(reservation.snapshot) : {};
            } catch (e) {
                console.warn('Error parsing snapshot:', e);
            }
            let stationInfo = null;
            if (snapshot?.StationID) {
                stationInfo = validStations.find((station) => station?.id === snapshot.StationID);
            } else if (snapshot?.connector) {
                stationInfo = findStationByConnectorId(validStations, snapshot.connector);
            }

            // 确保时间字段存在
            const bookTime = reservation.book_time ? new Date(reservation.book_time) : new Date();
            const actualEndTime = reservation.actual_end_time ? new Date(reservation.actual_end_time) : new Date();
            const img = stationInfo?.image
                ? { uri: stationInfo?.image }
                : require('../../assets/dummyStationPicture.png');
            return {
                imgURL: img,
                date: `${bookTime.getMonth() + 1}月${bookTime.getDate()}`,
                time: bookTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
                actual_end_time: actualEndTime.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                }),
                chargeStationName: stationInfo?.snapshot?.StationName || 'Unknown Station',
                chargeStationAddress: stationInfo?.snapshot?.Address || 'Unknown Address',
                stationLng: stationInfo?.snapshot?.StationLng || '',
                stationLat: stationInfo?.snapshot?.StationLat || '',
                distance: '',
                format_order_id: reservation.format_order_id || '',
                actual_total_power: reservation.actual_total_power || 0,
                total_fee: reservation.total_fee || 0,
                withdraw_fee: reservation.withdraw_fee || 0,
                actual_fee: (reservation.total_fee || 0) - (reservation.withdraw_fee || 0),
                current_price: snapshot_price?.current_price || 0,
                total_power: reservation.total_power || 0
            } as TabItem;
        });
};
const BookingTabViewComponentInner: React.FC<BookingTabViewComponentProps> = ({ titles }) => {
    const { data, isLoading, error } = useQuery({
        queryKey: ['reservationsAndStations'],
        queryFn: fetchReservationsAndStations,
        staleTime: 0,
        gcTime: 0,
        refetchOnMount: true,
        refetchOnWindowFocus: true
    });

    if (isLoading) {
        return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <ActivityIndicator size="large" color="#34657b" />
            </View>
        );
    }

    if (error) {
        console.log('Error fetching data:', error);
        return null;
    }

    if (!data) {
        return null;
    }
    // 确保即使 data 为 undefined 也能安全处理
    const reservations = Array.isArray(data?.reservations) ? data.reservations : [];
    const stations = Array.isArray(data?.stations) ? data.stations : [];

    const futureReservations = processReservations(reservations, stations, true);
    const completedReservations = processReservations(reservations, stations, false);
    const allReservationItems = [...futureReservations, ...completedReservations];
    // const allReservationItems = [...futureReservations];

    return (
        <TabViewComponent
            titles={titles}
            tabItems={allReservationItems}
            isLoading={false}
        />
    );
};

const BookingTabViewComponent: React.FC<BookingTabViewComponentProps> = (props) => (
    <QueryClientProvider client={queryClient}>
        <BookingTabViewComponentInner {...props} />
    </QueryClientProvider>
);

export default BookingTabViewComponent;
