"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 { loadOrganizationsById, updateOrganizationsById, uploadHeaderImage } from "../Org.Service";
import { MyOranizationsView, UpdateCompanyParams } from "@models/Company.model";
import { PopoverPicker } from "@core/app/components/ColorPicker/ColorPicker";
import { useOrganizationHeaderStore } from "@core/Store/OrganizationHeader.Store";
import { Grid2 } from "@mui/material";
import ImagePicker from "@core/app/components/ImagePicker/ImagePicker";

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 organizationHeader = useOrganizationHeaderStore();
    const alert = useAlert();
    const [headerImage, setHeaderImage] = useState("");
    const [headerColor, setHeaderColor] = useState("");
    const [headerFontColor, setHeaderFontColor] = useState("");
    const [headerFontShadowColor, setHeaderFontShadowColor] = useState("");

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

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

        location.add({
            url: "/admin/org",
            title: "Organizacion",
            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: "Perzonalización",
            icon: <OrgConfigIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadOrganizationsById({ id: id, sessionUser: SessionInfo.userId })
            .then((response: MyOranizationsView) => {
                setHeaderImage(response.headerFile);
                setHeaderColor(response.headerColor);
                setHeaderFontColor(response.headerFontColor);
                setHeaderFontShadowColor(response.headerFontShadowColor);
                organizationHeader.setHeaderColor(response.headerColor);
                organizationHeader.setHeaderFontColor(response.headerFontColor);
                organizationHeader.setHeaderFontShadowColor(response.headerFontShadowColor);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    }, []);

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

            const updData: UpdateCompanyParams = {
                id: id,
                headerColor: headerColor,
                headerFontColor: headerFontColor,
                headerFontShadowColor: headerFontShadowColor,
                sessionUser: SessionInfo.userId,
            };

            updateOrganizationsById(updData)
                .then(() => {
                    alert.showSuccess("Color del encabezado actualizado");
                })
                .catch((error) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    const handleHeaderImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        e.preventDefault();

        const file = e.target.files?.[0];

        if (!file) {
            return;
        }

        const formData = new FormData();
        formData.append("companyId", id);
        formData.append("sessionUser", SessionInfo.userId); // Añade el ID del usuario
        formData.append("file", file);

        uploadHeaderImage(formData)
            .then((res) => {
                if (res.success) {
                    alert.showSuccess("Header actualizado");
                }
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />

            <div style={{ marginTop: "20px", color: "var(--black)", fontWeight: "bold" }}>
                Colores
            </div>
            <Grid2 container>
                <Grid2>
                    <PopoverPicker
                        placeholder="Fondo"
                        color={headerColor}
                        onChange={(color: string) => {
                            setHeaderColor(color);
                            organizationHeader.setHeaderColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 sx={{ width: "40px" }}></Grid2>
                <Grid2>
                    <PopoverPicker
                        placeholder="Fuente"
                        color={headerFontColor}
                        onChange={(color: string) => {
                            setHeaderFontColor(color);
                            organizationHeader.setHeaderFontColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
                <Grid2 sx={{ width: "40px" }}></Grid2>
                <Grid2>
                    <PopoverPicker
                        placeholder="Sombra"
                        color={headerFontShadowColor}
                        onChange={(color: string) => {
                            setHeaderFontShadowColor(color);
                            organizationHeader.setHeaderFontShadowColor(color);
                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                        }}
                    />
                </Grid2>
            </Grid2>

            <div
                style={{
                    marginTop: "20px",
                    color: "var(--black)",
                    fontWeight: "bold",
                    paddingTop: "5px",
                    paddingBottom: "10px",
                }}
            >
                Imagen
            </div>
            <ImagePicker
                src={headerImage}
                alt="Logo"
                style={{ width: "100%", height: "150px" }}
                readOnly={false}
                onChange={handleHeaderImageChange}
                imageSizeSrc="/org-header-size.webp"
                mbLimit={5}
            />

            <div style={{ marginBottom: "10px" }}>&nbsp;</div>
        </>
    );
}
