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();
    // console.log('reservations', reservations);r
    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, 33)
        .map((reservation) => {
            const snapshot = JSON.parse(reservation.snapshot);
            console.log(
                'reservationreservationreservationreservationreservationreservationreservationreservationreservationreservationreservation',
                snapshot.current_price
            );
            let stationInfo;
            // console.log(
            //     'snapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshotsnapshot',
            //     snapshot
            // );

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

            //this is book_time, not end_time
            const endDate = new Date(reservation.book_time);
            //this is actual_end_time for record
            const actualEndDate = new Date(reservation.actual_end_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 }),
                actual_end_time: actualEndDate.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,
                actual_total_power: reservation.actual_total_power,
                total_fee: reservation.total_fee,
                withdraw_fee: reservation.withdraw_fee,
                actual_fee: reservation.total_fee - reservation.withdraw_fee,
                current_price: snapshot.current_price,
                total_power: reservation.total_power,
                
            };
            // .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);

    const completedReservationTabItems = processReservations(data.reservations, data.stations, false);
    console.log('completedReservationTabItems', completedReservationTabItems);
    // console.log('completedReservationTabItems', completedReservationTabItems);
    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;
