import axios from 'axios';
import { Alert } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import { EXPO_PUBLIC_API_URL } from '@env';
import { forgetPasswordFormData } from '../types/signup';
import { CustomerData } from '../types/signUpFormData';

class ChargeStationService {
    private apiUrl: string;

    constructor() {
        this.apiUrl = EXPO_PUBLIC_API_URL;
        if (!this.apiUrl) {
            throw new Error('API URL is not defined in environment variables');
        }
    }

    async fetchCarBrand() {
        try {
            const response = await axios.get(
                `${this.apiUrl}/public/client/car/brand`
            );

            if (response.status === 200 || response.status === 201) {
                // console.log(response.data);
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async getUserCars() {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/customer/car/all`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                // console.log(response.data.data);
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async addCar(
        licensePlate: string,
        carBrandFk: string,
        carTypeFk: string,
        isDefault: boolean
    ) {
        try {
            const response = await axios.post(
                `${this.apiUrl}/clients/customer/car`,
                {
                    licensePlate: licensePlate,
                    carBrandFk: carBrandFk,
                    carTypeFk: carTypeFk,
                    isDefault: isDefault
                },
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                console.log('add car successful');
                return true;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async deleteCar(carID) {
        try {
            // console.log('i receive this carID', carID);
            const response = await axios.delete(
                `${this.apiUrl}/clients/customer/car?carId=${carID}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            // console.log('Full response:', JSON.stringify(response, null, 2));
            if (response.status === 200 || response.status === 201) {
                console.log('delete car successful');
                return true;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }
    async setDefaultCar(carID) {
        try {
            const response = await axios.put(
                `${this.apiUrl}/clients/customer/car/default?carId=${carID}`,
                {},
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                console.log('set default car successful');
                return true;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async fetchChargeStations() {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/chargestations/resources/info`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );

            if (response.status === 200 || response.status === 201) {
                return response.data.data.map((station, index) => {
                    const {
                        Address,
                        StationName,
                        StationID,
                        StationLng,
                        StationLat
                    } = station.snapshot;

                    return {
                        Address,
                        StationName,
                        StationID,
                        StationLng,
                        StationLat
                    };
                });
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'Login error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async fetchChargeStationPrice(stationID: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/promotion/price?id=${stationID}`
            );
            if (response.status === 200 || response.status === 201) {
                return response.data.price;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'Login error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async fetchAvailableDates(stationID: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/reservation/connectors/${stationID}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                const dates = response.data.map((i) => i.date);
                return dates;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'Login error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }

    async fetchAvailableTimeSlots(stationID: string, targetDate: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/reservation/connectors/${stationID}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync(
                            'accessToken'
                        )}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                const times = response.data.find((i) => i.date === targetDate);
                if (times) {
                    const availableTimeSlots = times.range.map((i) => i.start);
                    return availableTimeSlots;
                }
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error(
                    'Login error:',
                    error.response?.data?.message || error.message
                );
            } else {
                console.error('An unexpected error occurred:', error);
            }
            return false;
        }
    }
}
export const chargeStationService = new ChargeStationService();
