"use client";
import { useParams } from "next/navigation";
import { useState, useEffect } from "react";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useAlert } from "@store/Alert.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import OrgConfigIcon from "@mui/icons-material/SettingsOutlined";
import Textbox from "@components/Textbox/Textbox";
import { Grid2 } from "@mui/material";
import { loadOrganizationsById, updateOrganizationsById } from "../Org.Service";
import { MyOranizationsView } from "@models/Company.model";
import { ApiError } from "@models/Server.Error.model";

import { TextObjectModalContent } from "@store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@models/TextObjectFilter.model";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import {
    FindLocalidadesParams,
    FindPartidosParams,
    FindProvinciasParams,
} from "@models/Location.model";
import TextObjectFilter from "@components/TextObjectFilter/TextObjectFilter";
import SelectLocationMap, {
    LocationCoordinates,
} from "@core/app/components/SelectLocationMap/SelectLocationMap";

type UrlData = {
    id: string;
};

export default function OrganizationEdit() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const [street, setStreet] = useState("");
    const [streetNumber, setStreetNumber] = useState("");
    const [builingFloor, setBuilingFloor] = useState("");
    const [buildingApartament, setBuildingApartament] = useState("");

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

    const [latitude, setLatitude] = useState<number>(0);
    const [longitude, setLongitude] = useState<number>(0);
    const [initialLatitude, setInitialLatitude] = useState<number>(0);
    const [initialLongitude, setInitialLongitude] = useState<number>(0);

    /**
     * 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);
        });
    };

    const handleLocationChange = (location: LocationCoordinates) => {
        setLatitude(location.latitude);
        setLongitude(location.longitude);
        eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
    };

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

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

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

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

        location.add({
            url: "/admin/org",
            title: "Organizaciones",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Perfil",
            icon: <StorefrontOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Ubicación",
            icon: <OrgConfigIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        if (!SessionInfo.userId) return;

        loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId })
            .then((response: MyOranizationsView) => {
                setStreet(response.street);
                setStreetNumber(response.streetNumber);
                setBuilingFloor(response.builingFloor);
                setBuildingApartament(response.buildingApartament);
                setBlock(response.block.toLocaleUpperCase());
                setCity(response.city.toLocaleUpperCase());
                setState(response.state.toLocaleUpperCase());
                setCountry(response.country);
                setZipCode(response.zipCode);
                setInitialLatitude(response.latitude);
                setInitialLongitude(response.longitude);

                cargarProvincias();
                cargarPartidos(response.state.toUpperCase());
                cargarLocalidades(response.state.toUpperCase(), response.city.toUpperCase());
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            eventHandler.setEventType(EVENT_TYPES.LOADING);

            const data = {
                id: id,
                street: street,
                streetNumber: streetNumber,
                builingFloor: builingFloor,
                buildingApartament: buildingApartament,
                block: block,
                city: city,
                state: state,
                country: country,
                zipCode: zipCode,
                latitude: latitude,
                longitude: longitude,
                sessionUser: SessionInfo.userId,
            };

            updateOrganizationsById(data)
                .then(() => {
                    alert.showSuccess("Organizacion 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);
                }}
            />

            <SelectLocationMap
                onChange={handleLocationChange}
                initialCoordinates={{ latitude: initialLatitude, longitude: initialLongitude }}
            />
            <div style={{ marginBottom: "40px" }}>&nbsp;</div>
        </>
    );
}
