"use client";
import { useState, useEffect } 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 TextDate from "@core/app/components/TextDate/TextDate";

import TextObjectFilter from "@components/TextObjectFilter/TextObjectFilter";
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import { FindDiscountsParams } from "@core/Models/Discounts.model";

import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";

import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/es";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import { createDiscountEmail } from "../DiscountsEmail.Service";

dayjs.locale("es");

type UrlData = {
    id: string;
};

export default function DiscountCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const [email, setEmail] = useState("");
    const [dateStart, setDateStart] = useState<Dayjs>(dayjs());
    const [dateEnd, setDateEnd] = useState<Dayjs>(dayjs());
    const { goTo } = useNavigation();

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

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

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

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

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

    const [discountFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Descuento:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre del descuento para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });
    const [discountFilterData, setDiscountFilterData] = useState<TextObjectFilterResult[]>([]);
    const [discountId, setDiscountId] = useState<string>("");

    useEffect(() => {
        if (!SessionInfo.userId) return;

        const filter: FindDiscountsParams = {
            companyId: id,
            sessionUser: SessionInfo.userId,
        };
        filterObjects<FindDiscountsParams>("discounts/filter-all", filter).then((res) => {
            setDiscountFilterData(res);
        });
    }, [SessionInfo.userId]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            createDiscountEmail({
                companyId: id,
                email: email,
                discountId: discountId,
                startDate: dateStart.toDate(),
                endDate: dateEnd.toDate(),
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess(`El descuento ha sido creado`);
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/discounts-email");
                    }, 2000);
                })
                .catch((error) => {
                    alert.showError(error.format());
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                });
        }
    }, [eventHandler.eventType]);

    return (
        <>
            <Location />

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

            <TextObjectFilter
                placeholder="Descuento"
                content={discountFilterContent}
                data={discountFilterData}
                onChange={(id) => {
                    setDiscountId(id);
                }}
                selectedId={discountId}
            />

            <div>
                <TextDate
                    placeholder="Desde"
                    selectedDate={dateStart}
                    onChange={(value: dayjs.Dayjs) => {
                        setDateStart(value);
                    }}
                />
            </div>

            <div>
                <TextDate
                    placeholder="Hasta"
                    selectedDate={dateEnd}
                    onChange={(value: dayjs.Dayjs) => {
                        setDateEnd(value);
                    }}
                />
            </div>

            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
