"use client";
import { useParams } from "next/navigation";
import { useEffect, useState } 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 MaterialAlert from "@mui/material/Alert";
import Textbox from "@components/Textbox/Textbox";
import Button from "@core/app/components/Button/Button";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import { deleteOrganization } from "./advanced.Service";
import { useNavigation } from "@core/app/hooks/goto";

type UrlData = {
    id: string;
};

export default function OrganizationAdvancedEdit() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const confirm = useConfirmStore();
    const [verification, setVerification] = useState("");
    const { goTo } = useNavigation();

    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/wap/" + id,
            title: "Avanzado",
            icon: <OrgConfigIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    const eliminarHandler = () => {
        if (verification === "eliminar-org") {
            confirm.show(
                "Si eliminas una organización se perderán todos los datos relacionados con ella. ¿Estas seguro que queres eliminar la organización?",
                () => {
                    eventHandler.setEventType(EVENT_TYPES.LOADING);
                    deleteOrganization({ companyId: id, sessionUser: SessionInfo.userId })
                        .then(() => {
                            goTo("/admin/org");
                            alert.showSuccess("Organización eliminada con éxito");
                        })
                        .catch((error) => {
                            eventHandler.setEventType(EVENT_TYPES.SLEEP);
                            alert.showError(error.format());
                        })
                        .finally(() => {
                            eventHandler.setEventType(EVENT_TYPES.SLEEP);
                        });
                },
                () => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                }
            );
        } else {
            alert.showError("La confirmación no es correcta");
        }
    };

    return (
        <>
            <Location />
            <div
                style={{
                    marginTop: "20px",
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "start",
                    alignItems: "center",
                }}
            >
                <MaterialAlert severity="info" sx={{ marginTop: "20px", width: "100%" }}>
                    <p>
                        <strong>Atención:</strong> las acciones realizadas en esta sección son
                        irreversibles, es decir, que no se pueden deshacer. Si decide eliminar la
                        organización, se perderán todos los datos relacionados con ella.
                    </p>
                    <p>
                        <strong>Importante:</strong> para dar de baja la organización escribe{" "}
                        <strong>eliminar-org</strong> en la casilla de confirmación.
                    </p>
                </MaterialAlert>
                <Textbox
                    name="verification"
                    placeholder="Confirmación"
                    type="text"
                    value={verification}
                    width="100%"
                    onChange={(e) => {
                        setVerification(e.target.value);
                    }}
                />

                <Button
                    text="Eliminar organización"
                    width="100%"
                    color="error"
                    style={{ height: "42px", marginTop: "10px" }}
                    onClick={eliminarHandler}
                />
            </div>

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