"use client";
import { useState, useEffect } from "react";
import { useSessionStore } from "@store/Sesion.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import Textbox from "@components/Textbox/Textbox";
import { createOrganization } from "../Org.Service";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import * as Yup from "yup";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import categories from "@core/Models/Categories.type";
import { getSlug } from "@core/app/helpers/Slug";

export default function OrgCreate() {
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const [orgName, setOrgName] = useState("");
    const [orgDescription, setOrgDescription] = useState("");
    const [orgSlug, setOrgSlug] = useState("");
    const { goTo } = useNavigation();

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

    const [categoryFilterData, setCategoryFilterData] = useState<TextObjectFilterResult[]>([]);
    const [categoryId, setCategoryId] = useState<string>("");

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

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

        location.add({
            url: "/admin/org",
            title: "Mis organizaciones",
            icon: <StorefrontOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        location.add({
            url: "/admin/org/create",
            title: "Crear",
            icon: <StorefrontOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        loadCategories();
    }, []);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const data = {
                name: orgName,
                description: orgDescription,
                categoryId: Number(categoryId),
                ownerId: SessionInfo.userId,
            };

            const schema = Yup.object().shape({
                name: Yup.string().required("Debe introducir el nombre de la organización."),
                description: Yup.string().required(
                    "Debe introducir la descripción de la organización."
                ),
                categoryId: Yup.number().required(
                    "Para crear una organización debe elegir una categoría."
                ),
                ownerId: Yup.string().required("Para crear una organización debe iniciar sesión."),
            });

            schema.validate(data, { abortEarly: true }).then(() => {
                createOrganization(data)
                    .then((organization) => {
                        alert.showSuccess(
                            `Felicidades!!. La Organización ${organization.name} ha sido creada`
                        );
                        goTo("/admin/org");
                    })
                    .catch((error) => {
                        alert.showError(error.format());
                    })
                    .finally(() => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    });
            });
        }
    }, [eventHandler.eventType]);

    const loadCategories = () => {
        setCategoryFilterData(
            categories.map((category) => ({
                id: category.id.toString(),
                name: category.name,
                description: category.description,
            }))
        );
    };

    return (
        <>
            <Location />
            <p style={{ marginTop: "10px" }}>
                Desde aquí puedes crear una nueva organización, lo que te permitirá comenzar a
                ofrecer reservas a tus clientes a través de nuestra plataforma web de manera
                sencilla y eficiente.
            </p>

            <Textbox
                placeholder="Nombre de la organización"
                type="text"
                value={orgName}
                width="100%"
                onChange={(e) => {
                    setOrgName(e.target.value);
                    setOrgSlug(getSlug(e.target.value));
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <a
                style={{
                    fontSize: "14px",
                    paddingLeft: "10px",
                    fontWeight: "600",
                }}
                href={"https://turnosxpress.com.ar/" + orgSlug}
            >
                https://turnosxpress.com.ar/{orgSlug}
            </a>
            <Textbox
                placeholder="Descripción de la organización"
                type="text"
                value={orgDescription}
                width="100%"
                onChange={(e) => {
                    setOrgDescription(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

            <TextObjectFilter
                placeholder="Categoría"
                content={categoryFilterContent}
                data={categoryFilterData}
                onChange={(id) => {
                    setCategoryId(id);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
        </>
    );
}
