import React, { useState, useEffect, useMemo, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import axios from 'axios';
import GooglePlacesAutocomplete from 'react-google-places-autocomplete';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import useGetMosques from '../operations/queries/useGetMosques';
import DateTimePicker from 'react-datetime-picker';

const FuneralEdit = () => {
    const location = useLocation();
    const funeral = location.state;

    funeral && console.log("funeral", funeral);

    const styles: any = {
        pickerContainer: {
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            width: "100%",
            height: "100%",
            position: "absolute",
            top: 0,
            left: 0,
            backgroundColor: "rgba(0,0,0,0.8)",
            zIndex: 9999
        },
        picker: {
            backgroundColor: "#03170C",
            padding: "40px",
            borderWidth: "3px",
            borderColor: "#DDA418",
            justifyContent: "center"
        },
        pickerButton: {
            marginTop: "20px",
            backgroundColor: "#DDA418",
            padding: "10px 20px",
            border: "none",
            cursor: "pointer"
        },
        pickerButtonText: {
            color: "white",
            fontFamily: "MontserratB",
            fontSize: "20px"
        }
    };

    // const queryString = window.location.search;
    // const urlParams = new URLSearchParams(queryString);
    // console.log("queryString", queryString);

    const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toISOString().slice(0, 10); // Retourne le format yyyy-MM-ddThh:mm
    };

    const removeAccentsAndSpaces = (string: string) => {
        if (!string) return string;
        const stringWithoutAccents = string.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
        const stringWithoutAccentsAndSpaces = stringWithoutAccents.replace(/\s/g, "");

        return stringWithoutAccentsAndSpaces;
    }


    const [dropdownVisible, setDropdownVisible] = useState(false);
    const [mosqueSearchInput, setMosqueSearchInput] = useState('');
    const [isAddMosquePopupVisible, setIsAddMosquePopupVisible] = useState(false);

    const [formData, setFormData] = useState<any>(funeral);

    const [isAddFuneralsChecked, setIsAddFuneralsChecked] = useState(funeral?.id ? true : false);
    const [isSelectFuneralTimePopupVisible, setIsSelectFuneralTimePopupVisible] = useState(false);
    const [showFuneralTimePicker, setShowFuneralTimePicker] = useState(false);

    const [selectedFuneralTimeType, setSelectedFuneralTimeType] = useState<"time" | "salat">(funeral?.funeralTimeByPrayerTime ? "salat" : "time")

    const prayerTimes = [
        { label: "Après salat fajr", value: "after_fajr" },
        { label: "Après salat dhuhr", value: "after_dhuhr" },
        { label: "Après salat jumuaa 1er sermon", value: "after_1st_jumuaa" },
        { label: "Après salat jumuaa 2ème sermon", value: "after_2nd_jumuaa" },
        { label: "Après salat asr", value: "after_asr" },
        { label: "Après salat maghreb", value: "after_maghrib" },
        { label: "Après salat isha", value: "after_isha" },
    ];

    const { mosques } = useGetMosques();

    const transformedMosques = useMemo(() => {

        console.log("TRANSFORM Mosques: ")
        if (!mosques) return []

        let finalMosques: any = [...mosques]

        if (mosqueSearchInput && mosqueSearchInput != "") {
            return finalMosques
                .filter(mosque => removeAccentsAndSpaces(mosque.name.toLowerCase()).includes(removeAccentsAndSpaces(mosqueSearchInput?.toLowerCase())))
                .sort((a, b) => {
                    return a.name.localeCompare(b.name);
                });
        } else {
            return finalMosques.sort((a, b) => {
                return a.name.localeCompare(b.name);
            });
        }

    }, [mosques, mosqueSearchInput]);

    const handleChange = (e) => {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        // console.log("allo");

        // try {
        //     const response = await fetch(`/api/edit-funeral/${funeral.id}`, {
        //         method: 'PUT',
        //         headers: {
        //             'Content-Type': 'application/json'
        //         },
        //         body: JSON.stringify({
        //             id: funeral.id,
        //             selectedDeadName: formData.selectedDeadName,
        //             selectedDeadAge: formData.selectedDeadAge,
        //             selectedFuneralDate: formData.selectedFuneralDate,
        //             selectedFuneralDate: formData.selectedFuneralDate,
        //             selectedGender: formData.selectedGender,
        //             selectedFuneralLocation: formData.selectedFuneralLocation,
        //             selectedFuneralLocation: formData.selectedFuneralLocation
        //         })
        //     });
        //     if (response.ok) {
        //         toast.success('Funeral updated successfully'); // Affiche un toast de succès
        //     } else {
        //         toast.error('Failed to update funeral'); // Affiche un toast d'erreur
        //     }
        // } catch (error) {
        //     console.log('Error updating funeral:', error);
        //     toast.error('Error updating funeral'); // Affiche un toast d'erreur en cas d'erreur
        // }
    };

    const [mosqueInputValue, setMosqueInputValue] = useState<any>(null);
    const [funeralInputValue, setFuneralInputValue] = useState<any>(null);

    const onPressItem = (item: any) => {
        console.log("onPressItem", item)
        const formattedItem = {
            ...item,
            name: item.name ?? item.structured_formatting?.main_text
        }

        setFormData({ ...formData, location: formattedItem });
        setMosqueInputValue(null);
        setDropdownVisible(false);
    }

    const toggleSwitch = () => {
        setIsAddFuneralsChecked(previousState => !previousState);

        if (isAddFuneralsChecked && funeral?.id) {
            const confirmResult = window.confirm(
                "Si vous désactivez l'ajout d'un enterrement puis sauvegardez, les informations de l'enterrement seront perdues.\nVoulez-vous continuer ?"
            );

            if (confirmResult) {
                setIsAddFuneralsChecked(false);
            } else {
                setIsAddFuneralsChecked(true);
            }
        }
    };

    console.log("FORM DATA", formData)
    console.log("JANAZA", funeral)

    const formattedDefaultFuneralTimeByPrayerTime = funeral?.funeralTimeByPrayerTime ? prayerTimes.find((prayerTime) => prayerTime.value === funeral?.funeralTimeByPrayerTime)?.label : null

    const defaultFuneralDateTime = funeral?.dateTime ? new Date(funeral?.dateTime) : null;

    const formattedDefaultFuneralDate = defaultFuneralDateTime ? formatDate(funeral?.dateTime) : null;
    const formattedDefaultFuneralTime = defaultFuneralDateTime ? (defaultFuneralDateTime.getHours()?.toString().padStart(2, "0") + "h" + defaultFuneralDateTime.getMinutes()?.toString().padStart(2, "0")) : formattedDefaultFuneralTimeByPrayerTime;
    const updatedFuneralDateTime = formData.funeral?.dateTime ? new Date(formData.funeral?.dateTime) : null;

    const updatedFuneralTimeByPrayerTime = selectedFuneralTimeType === "salat" ? prayerTimes.find((prayerTime) => prayerTime.value === formData.funeral?.funeralTimeByPrayerTime)?.label : null;

    const formattedFuneralDate = updatedFuneralDateTime ? formatDate(formData.funeral?.dateTime) : formattedDefaultFuneralDate;
    const formattedFuneralTime = (formData.funeral?.time && selectedFuneralTimeType === "time") ? formData.funeral?.time : updatedFuneralTimeByPrayerTime ?? formattedDefaultFuneralTime;

    const funeralTimeByPrayerTime = formData.funeral?.funeralTimeByPrayerTime ?? funeral?.funeralTimeByPrayerTime;
    const formattedFuneralTimeOnly = (formData.funeral?.time && selectedFuneralTimeType === "time") ? formData.funeral?.time : !funeralTimeByPrayerTime ? formattedDefaultFuneralTime : null;

    const [isShowFuneralTimeByPrayerPicker, setIsShowFuneralTimeByPrayerPicker] = useState(false)

    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');
            });
    }, []);

    return (
        <>
            <div className="container">
                <h1 className="mt-5">Edition Enterrement</h1>
                <form id="editFuneralForm" className="mt-3" onSubmit={handleSubmit}>
                    <div className="mb-3 mt-3">
                        <label htmlFor="funeralInfos">Adresse de l'enterrement</label>
                        <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={{
                                styles: {
                                    dropdownIndicator: (provided) => ({
                                        ...provided,
                                        isDisabled: true,
                                    }),

                                },
                                placeholder: 'Rechercher une adresse',
                                defaultInputValue: formData.funeral?.location?.name,
                                value: funeralInputValue?.name,
                                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({ ...formData, funeral: { ...formData.funeral, location: formattedItem } });
                                    setFuneralInputValue(text)
                                },
                            }}
                        />
                    </div>
                    <div className="mb-3">
                        <label htmlFor="funeralDate">Date de l'enterrement</label>
                        <input id='funeralDate' type="date" className="form-control" name="funeral.dateTime" placeholder="Date de l'enterrement" value={formattedFuneralDate?.toLocaleString()} onChange={handleChange} />
                    </div>
                    <div className="mb-3">
                        <label htmlFor="funeralTime">Heure de l'enterrement</label>
                        <input id='funeralTime' type="time" className="form-control" name="funeralTime" placeholder="Heure de l'enterrement" value={formData.funeral?.time} onChange={handleChange} />
                    </div>
                    <button style={{ backgroundColor: "#000000", width: "100%", marginTop: "30px" }} type="submit" className="btn btn-primary" onClick={handleSubmit}>
                        Enregistrer
                    </button>
                </form>
            </div>
            {dropdownVisible && (
                <div style={{ position: "fixed", width: "100%", height: "100%", backgroundColor: "rgba(0,0,0,0.8)", zIndex: 1040, top: "0", left: "0", right: "0", bottom: "0", display: "flex", flexDirection: "column", padding: "40px", overflow: "hidden" }}>
                    <div style={{ width: "100%", padding: "40px", justifyContent: "center", alignItems: "center", flex: "1 1 auto", overflowY: "auto", display: "flex", flexDirection: "column", overflow: "hidden" }}>
                        <div onClick={() => setDropdownVisible(false)} style={{ width: "40px", height: "40px", alignItems: "center", justifyContent: "center", display: "flex", cursor: "pointer", alignSelf: "flex-end", marginBottom: "20px" }}>
                            <FontAwesomeIcon icon={"times"} style={{ color: "white", fontSize: "24px" }} />
                        </div>
                        <input
                            placeholder="Rechercher une mosquée"
                            value={mosqueSearchInput}
                            onChange={(e) => setMosqueSearchInput(e.target.value)}
                            style={{
                                backgroundColor: "white",
                                padding: "10px",
                                borderRadius: "5px",
                                width: "920px",
                                marginBottom: "30px",
                            }}
                        />
                        <div style={{ flex: "1 1 auto", overflowY: "scroll", padding: "10px", width: "920px", scrollbarWidth: "none" }}>
                            {transformedMosques.map((mosque) => (
                                <div key={mosque.id} style={{ color: "#000000", backgroundColor: "#FFFFFF", marginBottom: "20px", padding: "10px", cursor: "pointer" }} onClick={() => onPressItem(mosque)}>
                                    {mosque.name}
                                </div>
                            ))}
                        </div>
                        <button onClick={() => {
                            setDropdownVisible(false)
                            setIsAddMosquePopupVisible(true)
                        }}
                            style={{ width: "200px", height: "50px" }}>
                            Ajouter une mosquée
                        </button>
                    </div>
                </div >
            )}
            {isAddMosquePopupVisible && (
                <div style={{ position: "fixed", width: "100%", height: "100%", backgroundColor: "rgba(0,0,0,0.8)", zIndex: 1050, alignItems: "center", justifyContent: "center", top: "0", left: "0", right: "0", bottom: "0" }}>
                    <div style={{ width: "100%", height: "100%", padding: "40px", borderWidth: "3px", borderColor: "#DDA418", justifyContent: "center", alignItems: "center" }}>
                        <div onClick={() => setIsAddMosquePopupVisible(false)} style={{ width: "40px", height: "40px", alignItems: "center", justifyContent: "center", display: "flex", cursor: "pointer" }}>
                            <FontAwesomeIcon icon={"times"} style={{ color: "white", fontSize: "24px" }} />
                        </div>
                        <h3 style={{ color: "white", fontSize: "20px" }}>Ajouter une mosquée</h3>
                        <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: mosqueInputValue?.name,
                                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({ ...formData, selectedFuneralLocation: formattedItem });
                                    setMosqueInputValue(text)
                                },
                            }}
                        />
                        <button onClick={() => {
                            // Logique pour ajouter une mosquée
                            // Vous pouvez appeler une fonction pour envoyer une requête POST à votre API ici
                            setIsAddMosquePopupVisible(false);
                        }} style={{ width: "100%", height: "50px" }}>
                            Fermer
                        </button>
                    </div>
                </div>
            )}
            {isSelectFuneralTimePopupVisible && (
                <div style={{ position: "fixed", width: "100%", height: "100%", backgroundColor: "rgba(0,0,0,0.8)", zIndex: 1050, alignItems: "center", justifyContent: "center", top: 0, left: 0, right: 0, bottom: 0, display: "flex" }}>
                    <div onClick={() => setIsSelectFuneralTimePopupVisible(false)} style={{ width: "40px", height: "40px", alignItems: "center", justifyContent: "center", display: "flex", cursor: "pointer", position: "absolute", top: "30px", right: "30px" }}>
                        <FontAwesomeIcon icon={"times"} style={{ color: "white", fontSize: "24px" }} />
                    </div>
                    <div style={{ width: "100%", height: "600px", backgroundColor: "#03170C", padding: "40px", borderWidth: "3px", borderColor: "#DDA418", justifyContent: "center", display: "flex", flexDirection: "column", alignItems: "center" }}>
                        <p style={{ fontSize: "30px", color: "#FFFFFF", marginBottom: "20px" }}>Heure de la Funeral</p>
                        <input style={{ width: "300px", cursor: "pointer", fontSize: "20px" }} id='time' type="time" key={formData.funeralTimeByPrayerTime} className="form-control" name="time" placeholder="Heure de la funeral" value={formattedFuneralTimeOnly} onChange={(e) => {
                            console.log("eeeeee", e)
                            setFormData({ ...formData, time: e.target.value })
                            setSelectedFuneralTimeType("time")
                        }} />
                        <div style={{ width: "20%", height: "3px", backgroundColor: "#DDA418", marginBottom: "20px", marginTop: "20px" }} />
                        <p style={{ color: "white", fontSize: "20px", marginBottom: "20px" }}>OU définir par rapport aux prières:</p>
                        <div style={{ marginBottom: "20px", width: "300px" }}>
                            <select id='funeralTimeByPrayerTime' key={selectedFuneralTimeType} style={{ color: (!formData.funeralTimeByPrayerTime || selectedFuneralTimeType !== 'salat') ? "lightgrey" : "black", fontSize: "20px" }} className="form-control" name="funeralTimeByPrayerTime"
                                value={
                                    selectedFuneralTimeType === "salat" ? formData.funeralTimeByPrayerTime : !formData.time ? funeralTimeByPrayerTime : null
                                }
                                onChange={(e) => {
                                    setFormData({ ...formData, funeralTimeByPrayerTime: e.target.value })
                                    setSelectedFuneralTimeType("salat")
                                }}>
                                <option value={""}>Choisir</option>
                                {prayerTimes.map((prayerTime, index) => (
                                    <option key={index} value={prayerTime.value}>{prayerTime.label}</option>
                                ))}
                            </select>
                        </div>
                        <div style={{ display: "flex", justifyContent: "space-evenly", width: "100%", marginTop: "20px" }}>
                            <button style={{ width: "150px", height: "45px", backgroundColor: "#DDA418", display: "flex", alignItems: "center", justifyContent: "center" }}
                                onClick={() => setIsSelectFuneralTimePopupVisible(false)}
                            >
                                <p style={{ fontFamily: "MontserratB", fontSize: "20px", color: "white" }}>Fermer</p>
                            </button>
                        </div>
                    </div>
                </div>
            )}
            {(isShowFuneralTimeByPrayerPicker) && (
                <div style={styles.pickerContainer}>
                    <div style={styles.picker}>
                        <select
                            // ref={FuneralTimeByPrayerPickerRef}
                            style={{
                                fontFamily: "MontserratR",
                                width: "100%"
                            }}
                            onFocus={() => document?.activeElement?.blur()}
                            value={selectedFuneralTimeType === "salat" ? formData.funeralTimeByPrayerTime : ""}
                            onChange={(e) => {
                                const itemValue = e.target.value;
                                setFormData({ ...formData, funeralTimeByPrayerTime: itemValue });
                                setSelectedFuneralTimeType("salat");
                            }}
                        >
                            <option style={{ color: "grey", fontFamily: "MontserratR" }} value={undefined}>Choisir</option>
                            {prayerTimes.map((prayerTime, index) => (
                                <option key={index} style={{ color: "black", fontFamily: "MontserratR" }} value={prayerTime.value}>
                                    {prayerTime.label}
                                </option>
                            ))}
                        </select>
                        <button
                            style={styles.pickerButton}
                            onClick={() => {
                                setIsShowFuneralTimeByPrayerPicker(!isShowFuneralTimeByPrayerPicker);
                            }}
                        >
                            <span style={styles.pickerButtonText}>Choisir</span>
                        </button>
                    </div>
                </div>
            )}
        </>
    );
}

export default FuneralEdit;
