"use client";
import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
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 DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import Textbox from "@components/Textbox/Textbox";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import TextSelect from "@components/TextSelect/TextSelect";
import { refactorFields, TemplateTypes, unRefactorFields } from "@core/Models/Templates.model";
import {
    deleteTemplate,
    getDefaultTemplate,
    getTemplate,
    saveTemplate,
} from "../../Templates.Service";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";
import ButtonMaterial from "@mui/material/Button";
import DefaultTemplateIcon from "@mui/icons-material/Rtt";
import { useConfirmStore } from "@core/Store/Confirm.Store";

type UrlData = {
    id: string;
    templateId: string;
};

export default function TemplateCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const templateId = data.templateId;
    const confirm = useConfirmStore();
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const [name, setName] = useState("");
    const [code, setCode] = useState("");
    const [type, setType] = useState<TemplateTypes>(TemplateTypes.WAP_REMINDER);
    const [template, setTemplate] = useState("");
    const { goTo } = useNavigation();
    const bottomToolbar = useBottomToolbarStore();

    const [seelectClientValue, setSeelectClientValue] = useState("");

    const textboxRef = useRef<HTMLTextAreaElement | null>(null);

    const typeRef = useRef(type);
    useEffect(() => {
        typeRef.current = type;
    }, [type]);

    const insertAtCursor = (
        ref: React.RefObject<HTMLInputElement | HTMLTextAreaElement>,
        insertText: string
    ) => {
        const el = ref.current;
        if (!el) return; // todavía no está montado

        // posición del cursor
        const start = el.selectionStart ?? 0;
        const end = el.selectionEnd ?? 0;

        const newText = template.substring(0, start) + insertText + template.substring(end);
        setTemplate(newText);

        // restaurar cursor
        requestAnimationFrame(() => {
            el.selectionStart = el.selectionEnd = start + insertText.length;
            el.focus();
        });
    };

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

        bottomToolbar.set(
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    width: "100%",
                    height: "60px",
                    color: "var(--white)",
                }}
            >
                <ButtonMaterial
                    variant="text"
                    startIcon={<DefaultTemplateIcon />}
                    sx={{ color: "var(--white)" }}
                    onClick={() => {
                        loadDefaultTemplate();
                    }}
                >
                    Por defecto
                </ButtonMaterial>
                {templateId != "new" && (
                    <ButtonMaterial
                        variant="text"
                        startIcon={<DefaultTemplateIcon />}
                        sx={{ color: "var(--white)" }}
                        onClick={() => {
                            confirm.show(
                                "Si elimina esta plantilla, todas las comunicaciones asociadas  utilizarán la plantilla por defecto. ¿Está seguro que desea eliminar esta plantilla?",
                                () => {
                                    eventHandler.setEventType(EVENT_TYPES.LOADING);
                                    deleteTemplate({
                                        companyId: id,
                                        id: templateId,
                                        sessionUser: SessionInfo.userId,
                                    })
                                        .then(() => {
                                            alert.showSuccess(`La plantilla ha sido eliminada`);
                                            eventHandler.setEventType(EVENT_TYPES.SLEEP);
                                            setTimeout(() => {
                                                goTo("/admin/org/profile/" + id + "/templates");
                                            }, 2000);
                                        })
                                        .catch((error) => {
                                            alert.showError(error.format());
                                            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                                        });
                                },
                                () => {
                                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                                }
                            );
                        }}
                    >
                        Eliminar
                    </ButtonMaterial>
                )}
            </div>
        );

        loadTemplate();

        return () => {
            bottomToolbar.clear();
        };
    }, []);

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

        location.add({
            url: "/admin/org/profile/" + id,
            title: "Origanizacion",
            icon: null,
        });

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

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

    const loadTemplate = () => {
        if (templateId !== "new") {
            eventHandler.setEventType(EVENT_TYPES.LOADING);
            getTemplate({
                companyId: id,
                id: templateId,
                sessionUser: SessionInfo.userId,
            })
                .then((res) => {
                    setName(res.name);
                    setCode(res.code);
                    setType(res.type);
                    setTemplate(unRefactorFields(res.template));
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                })
                .catch((error) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                });
        }
    };

    const loadDefaultTemplate = () => {
        if (!SessionInfo.userId) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        getDefaultTemplate({
            companyId: id,
            type: type,
            sessionUser: SessionInfo.userId,
        })
            .then((res) => {
                setTemplate(unRefactorFields(res));
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
            });
    };

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            saveTemplate({
                templateId: templateId === "new" ? "" : templateId,
                companyId: id,
                name: name,
                code: code,
                type: type,
                template: refactorFields(template),
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess(`La plantilla ha sido guardada`);
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/templates");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.format());
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />

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

            <Textbox
                placeholder="Código"
                type="text"
                value={code}
                width="100%"
                onChange={(e) => {
                    setCode(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <TextSelect
                label="Tipo"
                selectedValue={type}
                data={[
                    { id: TemplateTypes.WAP_REMINDER, text: "WhatsApp - Recordatorio" },
                    { id: TemplateTypes.WAP_NEW_APPOINTMENT, text: "WhatsApp - Nueva reserva" },
                ]}
                setSelectedValue={(value) => {
                    setType(value as TemplateTypes);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
                style={{ width: "100%", marginTop: "15px" }}
            />
            <div
                style={{
                    marginTop: "15px",
                    color: "var(--black)",
                    fontSize: "16px",
                    fontWeight: 700,
                    paddingTop: "0px",
                    paddingLeft: "5px",
                    lineHeight: "40px",
                    marginRight: "8px",
                    textAlign: "left",
                }}
            >
                Lista de Campos
            </div>
            <TextSelect
                label="Campos"
                selectedValue={seelectClientValue}
                data={[
                    { id: "@tx.Cliente", text: "Nombre del cliente" },
                    { id: "@tx.Fecha", text: "Fecha" },
                    { id: "@tx.Horario", text: "Horario" },
                    { id: "@tx.Direccion", text: "Dirección" },
                    { id: "@tx.Professional", text: "Profesional" },
                    { id: "@tx.Servicio", text: "Servicio" },
                    { id: "@tx.Precio", text: "Precio" },
                    { id: "@tx.Organizacion", text: "Organización" },
                    { id: "@tx.Salto", text: "Salto de linea" },
                ]}
                setSelectedValue={(value) => {
                    insertAtCursor(textboxRef, value.toString());
                    setSeelectClientValue("");
                }}
                style={{ width: "100%", marginTop: "1px" }}
            />
            <Textbox
                placeholder="Plantilla"
                type="comments"
                value={template}
                ref={textboxRef}
                width="100%"
                style={{ height: "40%" }}
                onChange={(e) => {
                    setTemplate(e.target.value);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
