"use client";
import { useState, useEffect } from "react";
import Textbox from "@components/Textbox/Textbox";
import { useSessionStore } from "@store/Sesion.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import { loadUserAddress, updateUserAddress } from "./UserAddress.Service";
import { IUserView } from "@models/User.model";
import { useAlert } from "@store/Alert.Store";
import { ApiError } from "@models/Server.Error.model";
import { Grid2 } from "@mui/material";

import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import {
    FindLocalidadesParams,
    FindPartidosParams,
    FindProvinciasParams,
} from "@core/Models/Location.model";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";

export default function EditProfile() {
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const [street, setStreet] = useState("");
    const [streetNumber, setStreetNumber] = useState("");
    const [builingFloor, setBuilingFloor] = useState("");
    const [buildingApartament, setBuildingApartament] = useState("");
    const [country, setCountry] = useState("");
    const [zipCode, setZipCode] = useState("");
    const location = useLocationStore();

    const [state, setState] = useState("");
    const [city, setCity] = useState("");
    const [block, setBlock] = useState("");

    /**
     * FILTRO DE PROVINCIA
     * ===================
     * */

    const [provinciaFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Provincia:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre de la provincia para buscarla.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem
                key={index}
                data={result}
                style={{ textTransform: "capitalize" }}
            />
        ),
    });

    const [provinciaFilterData, setProvinciaFilterData] = useState<TextObjectFilterResult[]>([]);
    const [selectedProvincia, setSelectedProvincia] = useState<string>("");

    /**
     * FILTRO DE PARTIDO
     * =================
     * */

    const [partidoFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Partido:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre del partido para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem
                key={index}
                data={result}
                style={{ textTransform: "capitalize" }}
            />
        ),
    });

    const [partidosFilterData, setPartidosFilterData] = useState<TextObjectFilterResult[]>([]);
    const [selectedPartido, setSelectedPartido] = useState<string>("");

    /**
     * FILTRO DE LOCALIDAD
     * ===================
     * */

    const [localidadFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Localidad:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre de la localidad para buscarla.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem
                key={index}
                data={result}
                style={{ textTransform: "capitalize" }}
            />
        ),
    });

    const [localidadesFilterData, setLocalidadesFilterData] = useState<TextObjectFilterResult[]>(
        []
    );
    const [selectedLocalidad, setSelectedLocalidad] = useState<string>("");

    const cargarProvincias = () => {
        filterObjects<FindProvinciasParams>("location/provincias-filter-all", {}).then((res) => {
            setProvinciaFilterData(res);
        });
    };

    const cargarPartidos = (provincia: string) => {
        filterObjects<FindPartidosParams>("location/partidos-filter-all", {
            provincia,
        }).then((res) => {
            setPartidosFilterData(res);
        });
    };

    const cargarLocalidades = (provincia: string, partido: string) => {
        filterObjects<FindLocalidadesParams>("location/localidades-filter-all", {
            provincia,
            partido,
        }).then((res) => {
            setLocalidadesFilterData(res);
        });
    };

    useEffect(() => {
        setSelectedProvincia(state);
    }, [provinciaFilterData]);

    useEffect(() => {
        setSelectedPartido(city);
    }, [partidosFilterData]);

    useEffect(() => {
        setSelectedLocalidad(block);
    }, [localidadesFilterData]);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/user/profile",
            title: "Perfil de usuario",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        location.add({
            url: "/user/profile/address",
            title: "Editar domicilio",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        if (!SessionInfo.userId) return;
        loadUserAddress(SessionInfo.userId)
            .then((response: IUserView) => {
                setStreet(response.street);
                setStreetNumber(response.streetNumber);
                setBuilingFloor(response.builingFloor);
                setBuildingApartament(response.buildingApartament);
                setState(response.state.toUpperCase());
                setCity(response.city.toUpperCase());
                setBlock(response.block.toUpperCase());
                setCountry(response.country);
                setZipCode(response.zipCode);

                cargarProvincias();
                cargarPartidos(response.state.toUpperCase());
                cargarLocalidades(response.state.toUpperCase(), response.city.toUpperCase());
            })
            .catch(() => {});
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            updateUserAddress({
                id: SessionInfo.userId,
                street: street,
                streetNumber: streetNumber,
                builingFloor: builingFloor,
                buildingApartament: buildingApartament,
                block: block,
                city: city,
                state: state,
                country: country,
                zipCode: zipCode,
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess("Dirección actualizada!");
                })
                .catch((error: ApiError) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />
            <Grid2 container sx={{ marginTop: "10px" }}>
                <Grid2 size={6}>
                    <Textbox
                        name="street"
                        placeholder="Calle"
                        type="text"
                        value={street}
                        width="100%"
                        onChange={(e) => {
                            setStreet(e.target.value);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 size={1}></Grid2>
                <Grid2 size={5}>
                    <Textbox
                        name="streetNumber"
                        placeholder="Nro."
                        type="text"
                        value={streetNumber}
                        width="100%"
                        onChange={(e) => {
                            setStreetNumber(e.target.value);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
            </Grid2>

            <Grid2 container>
                <Grid2 size={6}>
                    <Textbox
                        name="buildingApartament"
                        placeholder="Apartamento"
                        type="text"
                        value={buildingApartament}
                        width="100%"
                        onChange={(e) => {
                            setBuildingApartament(e.target.value);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 size={1}></Grid2>
                <Grid2 size={5}>
                    <Textbox
                        name="builingFloor"
                        placeholder="Piso"
                        type="text"
                        value={builingFloor}
                        width="100%"
                        onChange={(e) => {
                            setBuilingFloor(e.target.value);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
            </Grid2>

            {/* <Textbox
                name="country"
                placeholder="Pais"
                type="text"
                value={country}
                width="100%"
                onChange={(e) => {
                    setCountry(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            /> */}

            <TextObjectFilter
                placeholder="Provincia"
                content={provinciaFilterContent}
                data={provinciaFilterData}
                selectedId={selectedProvincia}
                onChange={(id) => {
                    setState(id);
                    if (id !== "") {
                        cargarPartidos(id);
                    } else {
                        setPartidosFilterData([]);
                    }
                    setCity("");
                    setLocalidadesFilterData([]);
                    setBlock("");
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <TextObjectFilter
                placeholder="Partido"
                content={partidoFilterContent}
                data={partidosFilterData}
                selectedId={selectedPartido}
                onChange={(id) => {
                    setCity(id);
                    if (id !== "") {
                        cargarLocalidades(state, id);
                    } else {
                        setLocalidadesFilterData([]);
                    }
                    setBlock(" ");
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <TextObjectFilter
                placeholder="Localidad"
                content={localidadFilterContent}
                data={localidadesFilterData}
                selectedId={selectedLocalidad}
                onChange={(id) => {
                    setBlock(id);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <Textbox
                name="zipCode"
                placeholder="C.P."
                type="text"
                value={zipCode}
                width="100%"
                onChange={(e) => {
                    setZipCode(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <div style={{ marginBottom: "20px" }}>&nbsp;</div>
        </>
    );
}
