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

const queryClient = new QueryClient();

interface BookingTabViewComponentProps {
    titles: string[];
}

//helper function to fetch reservations and stations
const findStationByConnectorId = (allStations, targetConnectorId) => {
    return allStations.find((station) =>
        station.snapshot.EquipmentInfos?.some((equipment) =>
            equipment.ConnectorInfos?.some((connector) => connector.ConnectorID === targetConnectorId)
        )
    );
};

const fetchReservationsAndStations = async () => {
    const [reservationResponse, allStationsResponse] = await Promise.all([
        chargeStationService.fetchReservationHistories(),
        chargeStationService.fetchAllChargeStations()
    ]);
    return { reservations: reservationResponse, stations: allStationsResponse };
};

const processReservations = (reservations, allStations, isFuture): TabItem[] => {
    const now = new Date();

    return reservations
        .filter((reservation) =>
            isFuture ? new Date(reservation.end_time) > now : new Date(reservation.end_time) <= now
        )
        .sort((a, b) =>
            isFuture ? new Date(a.end_time) - new Date(b.end_time) : new Date(b.end_time) - new Date(a.end_time)
        )
        .slice(0, 10)
        .map((reservation) => {
            const snapshot = JSON.parse(reservation.snapshot);
            let stationInfo;

            if (snapshot.stationID) {
                stationInfo = allStations.find((station) => station.id === snapshot.stationID);
            } else if (snapshot.connector) {
                stationInfo = findStationByConnectorId(allStations, snapshot.connector);
            }

            const endDate = new Date(reservation.book_time);
            return {
                imgURL: require('../../assets/dummyStationPicture.png'),
                date: `${endDate.getMonth() + 1}月${endDate.getDate()}`,
                time: endDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
                chargeStationName: stationInfo ? stationInfo.snapshot.StationName : 'Unknown Station',
                chargeStationAddress: stationInfo ? stationInfo.snapshot.Address : 'Unknown Address',
                stationLng: stationInfo ? stationInfo.snapshot.StationLng : '',
                stationLat: stationInfo ? stationInfo.snapshot.StationLat : '',
                distance: '',
                format_order_id: reservation.format_order_id
            };
            // .map((reservation) => {
            // const snapshot = JSON.parse(reservation.snapshot);
            // const stationInfo = allStations.find((station) => station.id === snapshot.stationID);
            // const endDate = new Date(reservation.book_time);
            // return {
            //     imgURL: require('../../assets/dummyStationPicture.png'),
            //     date: `${endDate.getMonth() + 1}月${endDate.getDate()}`,
            //     time: endDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
            //     chargeStationName: stationInfo ? stationInfo.snapshot.StationName : 'Unknown Station',
            //     chargeStationAddress: stationInfo ? stationInfo.snapshot.Address : 'Unknown Address',
            //     stationLng: stationInfo ? stationInfo.snapshot.StationLng : '',
            //     stationLat: stationInfo ? stationInfo.snapshot.StationLat : '',
            //     distance: ''
            //};
        });
};

const BookingTabViewComponentInner: React.FC<BookingTabViewComponentProps> = ({ titles }) => {
    const { data, isLoading, error } = useQuery('reservationsAndStations', fetchReservationsAndStations, {
        staleTime: 0,
        cacheTime: 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.error('Error fetching data:', error);
        return null;
    }

    if (!data) {
        return null;
    }

    const tabItems = processReservations(data.reservations, data.stations, true);
    console.log('tabItem', tabItems);

    const completedReservationTabItems = processReservations(data.reservations, data.stations, false);

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

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

export default BookingTabViewComponent;
