"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import DiscountsIcon from "@mui/icons-material/LocalOfferOutlined";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import DataGrid, { DataGridColumn, DataGridRow } from "@components/DataGrid/DataGrid";
import { useSessionStore } from "@store/Sesion.Store";
import {
    ITemplate,
    PaginateTemplatesParams,
    PaginateTemplatesResults,
    TemplateTypes,
    unRefactorFields,
} from "@models/Templates.model";
import { findTemplatesByOrganization } from "./Templates.Service";
import { useNavigation } from "@core/app/hooks/goto";

type UrlData = {
    id: string;
};

export type TemplateRow = DataGridRow & ITemplate;

export default function TemplatesGrid() {
    const data = useParams<UrlData>();
    const oid = data.id;
    const { goTo } = useNavigation();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();

    const formatType = (type: string) => {
        switch (type) {
            case TemplateTypes.WAP_NEW_APPOINTMENT:
                return "WhatsApp - Nueva reserva";
            case TemplateTypes.WAP_REMINDER:
                return "WhatsApp - Recordatorio";
            case TemplateTypes.EMAIL_NEW_APPOINTMENT:
                return "Email - Nueva reserva";
            case TemplateTypes.EMAIL_REMINDER:
                return "Email - Recordatorio";
        }
    };

    //const { goTo } = useNavigation();
    const { userId } = useSessionStore();
    const [dataGridColumns] = useState<DataGridColumn<TemplateRow>[]>([
        {
            field: "name",
            title: "Nombre",
            width: 150,
            render: (value: TemplateRow) => (
                <div>
                    <div style={{ paddingLeft: "10px", paddingTop: "10px", fontWeight: "bold" }}>
                        {value.name + " (" + value.code + ")"}
                    </div>
                    <div style={{ paddingLeft: "10px", color: "var(--gray-dark)" }}>
                        {formatType(value.type)}
                    </div>
                </div>
            ),
        },
        {
            field: "template",
            title: "Plantilla",
            width: null,
            render: (value: TemplateRow) => (
                <div>
                    <div
                        style={{
                            paddingTop: "10px",
                            textAlign: "left",
                            paddingRight: "10px",
                            color: "var(--green-darkestX2)",
                        }}
                    >
                        {unRefactorFields(value.template)}
                    </div>
                </div>
            ),
        },
    ]);

    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE
                : "10"
        )
    );
    const [templates, setTemplates] = useState<PaginateTemplatesResults>();

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

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

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

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

        location.add({
            url: "",
            title: "Plantillas",
            icon: <DiscountsIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        loadTemplates(1, pageSize);
    }, []);

    const loadTemplates = (page: number = 1, pageSize: number = 30) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const filterData: PaginateTemplatesParams = {
            companyId: oid,
            page: page,
            limit: pageSize,
            sessionUser: userId,
        };

        findTemplatesByOrganization(filterData)
            .then((res) => {
                setTemplates(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    };

    const handleTemplateClick = (template: TemplateRow) => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        goTo("/admin/org/profile/" + oid + "/templates/new/" + template._id);
    };

    return (
        <>
            <Location />
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    marginTop: "10px",
                    position: "absolute",
                    left: "0px",
                    right: "0px",
                    top: "60px",
                    bottom: "10px",
                }}
            >
                <DataGrid
                    columns={dataGridColumns}
                    data={templates ? templates.data : []}
                    pagination={true}
                    page={templates?.page}
                    pages={templates?.pages}
                    pageSize={pageSize}
                    handleRefresh={loadTemplates}
                    handleRowClick={handleTemplateClick}
                />
            </div>
        </>
    );
}
