"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 { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { createDiscount } from "../Discounts.Service";
import { DiscountType } from "@models/Discounts.model";
import TextSelect from "@components/TextSelect/TextSelect";

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 [name, setName] = useState("");
    const [code, setCode] = useState("");
    const [type, setType] = useState<DiscountType>(DiscountType.PERCENTAGE);
    const [value, setValue] = useState(0);
    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" }} />,
        });
    }, []);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            createDiscount({
                companyId: id,
                name: name,
                code: code,
                type: type,
                value: value,
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess(`El descuento ha sido creado`);
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                    setTimeout(() => {
                        goTo("/admin/org/profile/" + id + "/discounts");
                    }, 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: DiscountType.FIXED, text: "Fijo" },
                    { id: DiscountType.PERCENTAGE, text: "Porcentaje" },
                ]}
                setSelectedValue={(value) => {
                    setType(value as DiscountType);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
                style={{ width: "100%", marginTop: "15px" }}
            />
            <Textbox
                placeholder="Valor"
                type="number"
                value={value.toString()}
                width="100%"
                onChange={(e) => {
                    setValue(Number(e.target.value));
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />
            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
