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

class ChargeStationService {
    private apiUrl: string;

    constructor() {
        this.apiUrl = process.env.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) {
                return response.url;
            } else {
            }
        } catch (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) {
                return response.data;
            } else {
            }
        } catch (error) {}
    }

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

    async getReservationWithSize(size: number) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/reservation/connectors/2405311022116801000/${size}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
            }
        } catch (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) {
                return true;
            } else {
                return false;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('error:', error.response?.data?.message || error.message);
                return false;
            } else {
                console.error('An unexpected error occurred:', error);
                return false;
            }
        }
    }

    async deleteCar(carID) {
        try {
            const response = await axios.delete(`${this.apiUrl}/clients/customer/car?carId=${carID}`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                return true;
            } else {
            }
        } catch (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) {
                return true;
            } else {
            }
        } catch (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) {}
    }

    async getCurrentPrice() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=2405311022116801000`);
            if (response.status === 200 || response.status === 201) {
                return response.data.price;
            } else {
                throw new Error(`Unexpected response status: ${response.status}`);
            }
        } catch (error) {
            console.error('Error getting current price:', error);
            if (axios.isAxiosError(error)) {
                console.error('Response data:', error.response?.data);
                console.error('Response status:', error.response?.status);
            }
            throw error; // Re-throw the error for the caller to handle
        }
    }
    async getOriginalPrice() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=2405311022116801000`);
            if (response.status === 200 || response.status === 201) {
                return response.data.originalPrice;
            } else {
                throw new Error(`Unexpected response status: ${response.status}`);
            }
        } catch (error) {
            console.error('Error getting original price:', error);
            if (axios.isAxiosError(error)) {
                console.error('Response data:', error.response?.data);
                console.error('Response status:', error.response?.status);
            }
            throw error; // Re-throw the error for the caller to handle
        }
    }

    async NewfetchAvailableConnectors() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/info`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 && response.data.code === 200) {
                return response.data.data.map((station: any) => {
                    // const snapshotData = JSON.parse(station.snapshot);
                    const snapshotData = station.snapshot;

                    const availableConnectors = station?.Equipments?.reduce((count: number, equipment: any) => {
                        return (
                            count +
                            equipment.ConnectorInfos.filter((connector: any) => connector.Status === '待机').length
                        );
                    }, 0);
                    return {
                        stationID: snapshotData.StationID,
                        stationName: snapshotData.StationName,
                        availableConnectors: availableConnectors,
                        address: snapshotData.Address,
                        image: station?.image,
                        stationLng: snapshotData.StationLng,
                        stationLat: snapshotData.StationLat
                    };
                });
            }
            return [];
        } catch (error) {
            console.error('Error fetching available connectors:', error);
            return [];
        }
    }

    async fetchAvailableConnectors(stationID: string) {
        try {
            const response = await axios.get(
                `${this.apiUrl}/clients/chargestations/resources/status?StationIDs=${stationID}`,
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                    }
                }
            );
            if (response.status === 200 || response.status === 201) {
                const stationStatusInfos = response.data.data.StationStatusInfos;
                if (stationStatusInfos && stationStatusInfos.length > 0) {
                    const availableConnectors = stationStatusInfos[0].ConnectorStatusInfos.filter(
                        (connector) => connector.Status === 2
                    ).length;
                    return availableConnectors;
                }
                return 0;
            }
        } catch (error) {
            return 0;
        }
    }
    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;
                    const image = station.image;

                    return {
                        Address,
                        StationName,
                        StationID,
                        StationLng,
                        StationLat,
                        image
                    };
                });
            } else {
            }
        } 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 fetchChargeStationIdByScannedConnectorId(scannedConnectorId: string) {
        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) {
                const station = response.data.data.find((station: any) =>
                    station.snapshot.EquipmentInfos.some((equipment: any) =>
                        equipment.ConnectorInfos.some((connector: any) => connector.ConnectorID === scannedConnectorId)
                    )
                );

                return station?.snapshot.StationID;
            } else {
                return false;
            }
        } 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 noImagefetchChargeStationIdByScannedConnectorId(scannedConnectorId: string) {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/simple/info`, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });

            if (response.status === 200 || response.status === 201) {
                const station = response.data.data.find((station: any) =>
                    station.Equipments.some((equipment: any) =>
                        equipment.ConnectorInfos.some((connector: any) => connector.ConnectorID === scannedConnectorId)
                    )
                );

                return station?.id;
            } else {
                return false;
            }
        } 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 {
            }
        } 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 {
            }
        } 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() {
        const aa = await SecureStore.getItemAsync('accessToken')
        console.log('iiiiiiiqqqqq', aa)
        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) {
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log('ddqqqqqwwww', 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;
        }
    }

    async payPenalty(penaltyData: any) {
        try {
            const response = await axios.post(`${this.apiUrl}/clients/pay/penalty`, penaltyData, {
                headers: {
                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                }
            });
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
                console.log('Invalid response for penalty payment');
                return null;
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error('Penalty payment error:', error.response?.data?.message || error.message);
            } else {
                console.error('An unexpected error occurred during penalty payment:', error);
            }
            return null;
        }
    }

    async getAdvertise() {
        try {
            const response = await axios.get(`${this.apiUrl}/clients/advertise/advertise`);
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async getCurrentPriceInPay(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 {
                throw new Error(`Unexpected response status: ${response.status}`);
            }
        } catch (error) {
            console.error('Error getting current price:', error);
            if (axios.isAxiosError(error)) {
                console.error('Response data:', error.response?.data);
                console.error('Response status:', error.response?.status);
            }
            throw error; // Re-throw the error for the caller to handle
        }
    }
    async getOriginalPriceInPay(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.originalPrice;
                // throw new Error(`Unexpected response status: ${response.status}`);
            } else {
                throw new Error(`Unexpected response status: ${response.status}`);
            }
        } catch (error) {
            console.error('Error getting original price:', error);
            if (axios.isAxiosError(error)) {
                console.error('Response data:', error.response?.data);
                console.error('Response status:', error.response?.status);
            }
            throw error; // Re-throw the error for the caller to handle
        }
    }
    async validateCoupon(couponRecords: string[], orderAmount: number) {
        try {
            const response = await axios.post(
                `${this.apiUrl}/clients/coupon/valid`,
                {
                    couponRecords: couponRecords,
                    orderAmount: orderAmount
                },
                {
                    headers: {
                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
                    }
                }
            );
            if (response.data.is_valid === true) {
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }
    }
}
export const chargeStationService = new ChargeStationService();
