import axios, { isAxiosError } from 'axios';
import { Alert } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import {apiClient} from './requets'
import { ChargingDetails, ElectricityPrice } from './type/chargeStationType';
class ChargeStationService {

    async fetchCarBrand() {
        try {
            const response = await apiClient.instance.get(`/public/client/car/brand`);

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

    async getUserCars() {
        try {
            const response = await apiClient.instance.get(`/clients/customer/car/all`);
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
            }
        } catch (error) {}
    }

    async getUserDefaultCars() {
        try {
            const response = await apiClient.instance.get(`/clients/customer/car/all?queryDefault=true`);
            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 apiClient.instance.get(
                `/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 apiClient.instance.post(
                `/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 (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: string) {
        try {
            const response = await apiClient.instance.delete(`/clients/customer/car?carId=${carID}`);
            if (response.status === 200 || response.status === 201) {
                return true;
            } else {
            }
        } catch (error) {}
    }
    async setDefaultCar(carID: string) {
        try {
            const response = await apiClient.instance.put(
                `/clients/customer/car/default?carId=${carID}`,
                {},
            );
            if (response.status === 200 || response.status === 201) {
                return true;
            } else {
            }
        } catch (error) {}
    }

    async fetchPriceForCharging() {
        try {
            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);
            if (response.status === 200 || response.status === 201) {
                return response.data;
            }
        } catch (error) {}
    }

    async getCurrentPrice() {
        try {
            const response = await apiClient.instance.get(`/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 (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 apiClient.instance.get(`/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 (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 apiClient.instance.get(`/clients/chargestations/resources/local/info`);
            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,
                        pricemodel_id: station.pricemodel_id,
                    };
                });
            }
            return [];
        } catch (error) {
            console.error('Error fetching available connectors:', error);
            return [];
        }
    }

    async fetchAvailableConnectors(stationID: string) {
        try {
            const response = await apiClient.instance.get(
                `/clients/chargestations/resources/status?StationIDs=${stationID}`,
            );
            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: any) => connector.Status === 2
                    ).length;
                    return availableConnectors;
                }
                return 0;
            }
        } catch (error) {
            return 0;
        }
    }
    async fetchChargeStations() {
        try {
            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);

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

                    return {
                        Address,
                        StationName,
                        StationID,
                        StationLng,
                        StationLat,
                        image
                    };
                });
            } else {
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/clients/chargestations/resources/info`);

            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 (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 apiClient.instance.get(`/clients/chargestations/resources/local/simple/info`);

            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 (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 apiClient.instance.get(`/clients/chargestations/resources/info`);
            if (response.status === 200 || response.status === 201) {
                return response.data.data;
            } else {
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/clients/promotion/price?id=${stationID}`);
            if (response.status === 200 || response.status === 201) {
                return response.data.price;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
            if (response.status === 200 || response.status === 201) {
                const dates = response.data.map((i: any) => i.date);
                return dates;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
            if (response.status === 200 || response.status === 201) {
                const times = response.data.find((i: any) => i.date === targetDate);
                if (times) {
                    const availableTimeSlots = times.range.map((i: any) => i.start);
                    return availableTimeSlots;
                }
            } else {
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
            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 apiClient.instance.get(
                `/clients/chargestations/resources/equip/status?StartChargeSeq=${format_order_id}`,
            );
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
            console.log(error);
        }
    }

    async fetchReservationHistories() {
        try {
            const response = await apiClient.instance.get(`/clients/reservation/all`);
            if (response.status === 200 || response.status === 201) {

                return response.data;
            } else {
                console.log('invalid response');
            }
        } catch (error) {
        }
    }

    async startCharging(payload: {
        StartChargeSeq: string;
        ConnectorID: string;
        StopBy: number;
        StopValue: number;
        StartBalance: number;
    }) {
        try {
            const response = await apiClient.instance.put(`/clients/chargestations/resources/charge/start`, payload);
            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 apiClient.instance.put(`/clients/chargestations/resources/charge/stop`, payload);
            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 apiClient.instance.get(`/clients/reservation/today`);
            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 apiClient.instance.get(`/public/image?filename=${filename}`)
            if (response.status === 200 || response.status === 201) {
                return response.data.url;
            }
        } catch (error) {
            console.error('Error fetching image URL:', error);
            return null;
        }
    }

    async getProcessedCarImageUrl(filename: string) {
        try {
            const response = await apiClient.instance.get(`http://ftp.hkmgt.com/cdn/public/file/crazycharge/${filename}`);
            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 apiClient.instance.post(`/clients/pay/penalty`, penaltyData);
            if (response.status === 200 || response.status === 201) {
                return response.data;
            } else {
                console.log('Invalid response for penalty payment');
                return null;
            }
        } catch (error) {
            if (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 apiClient.instance.get(`/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 apiClient.instance.get(`/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 (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 apiClient.instance.get(`/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 (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 apiClient.instance.post(
                `/clients/coupon/valid`,
                {
                    couponRecords: couponRecords,
                    orderAmount: orderAmount
                },
            );
            if (response.data.is_valid === true) {
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }
    }
    async fetchChargingDetails(recordID: string) {
        try {
            const response = await apiClient.instance.get(`/clients/reservation/getRecordById/${recordID}`);
            if (response.status === 200 || response.status === 201) {
                return response.data as ChargingDetails [];
            } else {
                return []
            }
        } catch (error) {
            console.log(error);
        }
    }
    async fetchElectricityPrice(id: string) {
        try {
            const response = await apiClient.instance.get(`/clients/promotion/business_hourGroup?pricemodel_id=${id}`);
            if (response.status === 200 || response.status === 201) {
                return response.data as ElectricityPrice [];
            } else {
                return [] as ElectricityPrice []
            }
        } catch (error) {
            console.log(error);
        }

    }
}
export const chargeStationService = new ChargeStationService();
