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) {
                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 getCarImage(filename: string) {
        try {
            const response = await axios.get(`${this.apiUrl}/public/image?filename=${filename}`);
            if (response.status === 200 || response.status === 201) {
                // console.log(response.data.data);
                return response.url;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    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 fetchPriceForCharging() {
        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;
            }
        } 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 fetchAllChargeStations() {
        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;
            } 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;
        }
    }

    async fetchSpecificChargeStation(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) {
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async fetchOngoingChargingData(format_order_id: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/chargestations/resources/equip/status?StartChargeSeq=${format_order_id}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                console.log('received data from fetchOngoingChargingData at chargingStationService', response.data);
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

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

    async startCharging(payload: {
        StartChargeSeq: string;
        ConnectorID: string;
        StopBy: number;
        StopValue: number;
        StartBalance: number;
    }) {
        try {
            const response = await axios.put(`${this.apiUrl}/clients/chargestations/resources/charge/start`, payload, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async stopCharging(payload: { StartChargeSeq: string; ConnectorID: string }) {
        try {
            console.log('stpo charge initialized');
            const response = await axios.put(`${this.apiUrl}/clients/chargestations/resources/charge/stop`, payload, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                console.log('stopCharging success', response);
                return response.data;
            } else {
                console.log('stopCharging fail', response);
            }
        } catch (error) {
            console.log('stopCharging fail here error ', error);
        }
    }

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

    async getProcessedImageUrl(filename: string) {
        try {
            const response = await axios.get(`${this.apiUrl}/public/image?filename=${filename}`, {
                // const response = await axios.get(`${this.apiUrl}/public/image?filename=BENZ-EQA.png`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                // console.log('i am getProcessedImageUrl s resposne', response.data.url);

                return response.data.url;
            }
        } catch (error) {
            console.error('Error fetching image URL:', error);
            return null;
        }
    }

    async getProcessedCarImageUrl(filename: string) {
        try {
            const response = await axios.get(`http://ftp.hkmgt.com/cdn/public/file/crazycharge/${filename}`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                return response.data.detail;
            }
        } catch (error) {
            console.error('Error fetching image URL:', error);
            return null;
        }
    }
}
export const chargeStationService = new ChargeStationService();
