import React, { useEffect, useState } from 'react';
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';
import { useNavigate } from 'react-router-dom';
import { ClipLoader } from 'react-spinners';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import useCreateLocation from '../operations/commands/useCreateLocation';

const LocationNew = () => {
    const [formData, setFormData] = useState<any>({});
    const navigate = useNavigate();
    
    const [apiKey, setApiKey] = useState("");
    
    useEffect(() => {
        // Fetch the Google Maps API key from the backend
        fetch('/api/config/maps')
            .then(response => response.json())
            .then(data => {
                setApiKey(data.apiKey);
            })
            .catch(error => {
                console.error('Error fetching Google Maps API key:', error);
                toast.error('Erreur lors du chargement de la configuration Google Maps');
            });
    }, []);

    const handleChange = (event) => {
        const { name, type, checked, value } = event.target;

        const inputValue = type === 'checkbox' ? checked : value;

        console.log("name", name);
        console.log("value", inputValue);

        const keys = name.split('.');

        if (keys.length > 1) {
            // Pour les objets imbriqués
            setFormData(prevState => {
                let newState = { ...prevState };
                let current = newState;

                // Traverse jusqu'à l'avant-dernier clé
                for (let i = 0; i < keys.length - 1; i++) {
                    if (!current[keys[i]]) {
                        current[keys[i]] = {};
                    }
                    current = current[keys[i]];
                }

                // Mettez à jour la dernière clé
                current[keys[keys.length - 1]] = inputValue;
                return newState;
            });
        } else {
            // Pour les propriétés de premier niveau
            setFormData({ ...formData, [name]: inputValue });
        }
    };

    const { createLocation, isLoading: isCreateLocationLoading } = useCreateLocation();

    const handleSubmit = async (e) => {
        if (isCreateLocationLoading) return;
        e.preventDefault();

        if (isManualAddressMode) {
            if (!formData?.name) {
                toast.error('Veuillez renseigner le nom du lieu');
                return;
            }
            if (!formData?.lat) {
                toast.error('Veuillez renseigner la latitude du lieu');
                return;
            }
            if (!formData?.lng) {
                toast.error('Veuillez renseigner la longitude du lieu');
                return;
            }
        } else {
            if (isBatchMode) {
                if (!formData?.places) {
                    toast.error('Veuillez remplir le champ texte');
                    return;
                }
            } else if (!formData?.name) {
                toast.error('Veuillez choisir une adresse via les suggestions Google');
                return;
            }
        }

        const data = {
            ...formData,
            isBatchMode,
            isManualAddressMode,
            placesList: extractLocations(formData.places || "")
        }

        console.log('data', data)

        try {
            createLocation(data).then((response) => {
                console.log("responseeeee", response)
                if (response.result === "success") {
                    console.log("response", response)
                    // toast.success('Lieu créé avec succès');
                    // navigate(`/admin/location/${response.locationId}/edit`);
                    if (response.successLocationsCounter > 0) {
                        toast.success(`${response.successLocationsCounter} lieu${response.successLocationsCounter > 1 ? "x" : ""} créé${response.successLocationsCounter > 1 ? "s" : ""} avec succès`, {
                            autoClose: false
                        });
                    }

                } if (response.failedLocations && response.failedLocations.length > 0) {
                    for (let i = 0; i < response.failedLocations.length; i++) {
                        toast.error(response.failedLocations[i]?.name + ", " + response.failedLocations[i]?.address + " : " + response.failedLocations[i]?.error, {
                            autoClose: false
                        });
                    }
                }
            }).catch((e) => {
                toast.error("Erreur lors de l'ajout du/des lieux ", e);
                console.log("response", e)
            });
        } catch (error: any) {
            console.error('Error updating location:', error);
            toast.error("Erreur lors de l'ajout du/des lieux ", error);
        }
    };

    const [isManualAddressMode, setIsManualAddressMode] = useState(false)
    const [isBatchMode, setIsBatchMode] = useState(true)

    function extractLocations(text) {
        if (!text || typeof text !== 'string') return []
        const lines = text.split('\n').filter(line => line.trim() !== '');
        const locations: any = [];

        console.log("lines", lines)

        lines.forEach(line => {
            const nameMatches = line.match(/(mosquée|cimetière|funérarium|salle de prière)[^,]*/ig);
            const addressMatch = line.match(/الله,\s*[^,]*,\s*([^,]*)/i);
            const followMatch = line.match(/cimetière|funérarium/i);
            const address = addressMatch ? addressMatch[1].trim() : null;

            if (nameMatches && address) {
                nameMatches.forEach(locationName => {
                    locations.push({ name: locationName.trim(), address });
                });
            }

            if (followMatch) {
                const followLocationMatch = line.match(/(cimetière|funérarium)[^]*/i);
                if (followLocationMatch) {
                    const followLocationName = followLocationMatch[0].match(/([^,]+)/);
                    const followAddress = followLocationMatch[0].match(/,\s*([^,]+)/i)
                    followAddress && locations.push({ name: followLocationName[0], address: followAddress[1] });
                }
            }
        });

        return locations;
    }

    return (
        <>
            <div className="container">
                <h1 className="mt-5">Ajouter Lieux</h1>
                <form id="editLocationForm" className="mt-3">
                    <div className='mt-4 mb-4' style={{ display: 'flex' }}>
                        <label className="switch">
                            <input
                                type="checkbox"
                                id="isManualAddressMode"
                                name='isManualAddressMode'
                                checked={isManualAddressMode}
                                onChange={() => {
                                    const nextValue = !isManualAddressMode;
                                    setIsManualAddressMode(nextValue);
                                    setIsBatchMode(!nextValue);
                                }}
                            />
                            <span className="slider"></span>
                        </label>
                        <span className="switch-text ml-2">Mode manuel</span>
                    </div>
                    <div className='mt-4 mb-4' style={{ display: 'flex' }}>
                        <label className="switch">
                            <input
                                type="checkbox"
                                id="isBatchMode"
                                name='isBatchMode'
                                checked={isBatchMode}
                                onChange={() => {
                                    const nextValue = !isBatchMode;
                                    setIsBatchMode(nextValue);
                                    setIsManualAddressMode(!nextValue);
                                }}
                            />
                            <span className="slider"></span>
                        </label>
                        <span className="switch-text ml-2">Mode batch</span>
                    </div>
                    {isManualAddressMode ? (
                        <>
                            <div className="mb-3">
                                <label htmlFor="name">Nom du lieu</label>
                                <input id='name' type="text" className="form-control" name="name" placeholder="Nom du lieu" value={formData?.name || ""} onChange={handleChange} />
                            </div>
                            <div className="mb-3">
                                <label htmlFor="lat">Latitude</label>
                                <input id='lat' type="number" className="form-control" name="lat" placeholder="Latitude" value={formData?.lat || ""} onChange={handleChange} />
                            </div>
                            <div className="mb-3">
                                <label htmlFor="lng">Longitude</label>
                                <input id='lng' type="number" className="form-control" name="lng" placeholder="Longitude" value={formData?.lng || ""} onChange={handleChange} />
                            </div>
                        </>) : isBatchMode ? (
                            <div className="mb-3">
                                <label htmlFor="places">Texte</label>
                                <textarea id='places' className="form-control" name="places" rows={15} placeholder="Saisissez votre texte ici..." value={formData?.places || ""} onChange={handleChange} />
                            </div>
                        ) : (
                        <>
                            {apiKey && (
                                <GooglePlacesAutocomplete
                                    apiKey={apiKey}
                                    apiOptions={{
                                        language: "fr",
                                        region: "fr",
                                    }}
                                    autocompletionRequest={{
                                        componentRestrictions: { country: ["fr", "gp", "mq", "gf", "re"] },
                                    }}
                                    minLengthAutocomplete={5}
                                    debounce={300}
                                    onLoadFailed={(err) => console.error(err)}
                                    selectProps={{
                                        placeholder: 'Rechercher une adresse',
                                        value: formData?.location,
                                        onChange: (text) => {
                                            console.log("onChange text", text)
                                            if (!text) return
                                            text = text.value
                                            const formattedItem = {
                                                ...text,
                                                name: text.name ?? text.structured_formatting?.main_text
                                            }
                                            setFormData(formattedItem);
                                        },
                                    }}
                                />
                            )}
                        </>
                    )
                    }
                    <button style={{ backgroundColor: "#000000", width: "100%", height: "50px", marginTop: "30px" }} className="btn btn-primary" type="button" onClick={handleSubmit}>
                        {isCreateLocationLoading ? (
                            <ClipLoader size={20} color={"#fff"} />
                        ) : (
                            "Enregistrer"
                        )}
                    </button>
                </form>
            </div>
            <style>{`
        .switch {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 20px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 14px;
            width: 14px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #000000; /* Changez cette couleur pour ajuster l'accent du switch */
        }
        
        input:checked + .slider:before {
            transform: translateX(20px);
        }
        `}</style>
        </>
    );
}

export default LocationNew;
