"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 ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import WeekDaySelector from "@core/app/components/WeekDaySelector/WeekDaySelector";
import HeaderConfProvider from "@core/app/components/HeaderConfProvider/HeaderConfProvider";
import TextObjectFilter from "@components/TextObjectFilter/TextObjectFilter";
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import TextTime from "@components/TextTime/TextTime";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import { FindEmployeesParams, FindEmployeesServicesParams } from "@core/Models/Collaborators.model";
import dayjs from "dayjs";
import "dayjs/locale/es";
import Button from "@core/app/components/Button/Button";
import { CreateRepeatsParams } from "@core/Models/Repeats.model";
import { repeatAdd } from "../../Client.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import { FindDiscountsParams } from "@core/Models/Discounts.model";

type UrlData = {
    oid: string;
    clientId: string;
};

export default function ClientCreate() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();

    const [weekDay, setWeekDay] = useState(1);
    const [horario, setHorario] = useState<dayjs.Dayjs>(dayjs(new Date()).hour(8).minute(0));

    const { goTo } = useNavigation();

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

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

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

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

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

    useEffect(() => {}, []);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            console.log("save");
        }
    }, [eventHandler.eventType]);

    const [collaboratorFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Colaborador:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre del colaborador para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });
    const [collaboratorFilterData, setCollaboratorFilterData] = useState<TextObjectFilterResult[]>(
        []
    );
    const [collaboratorId, setCollaboratorId] = useState<string>("");

    const [serviceFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div style={{ fontWeight: "700", fontSize: "14px", paddingTop: "7px" }}>
                    Seleccionar Servicio:
                </div>
                <p style={{ fontWeight: "500", fontSize: "13px", paddingTop: "2px" }}>
                    Ingrese el nombre del servicio para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });
    const [serviceFilterData, setServiceFilterData] = useState<TextObjectFilterResult[]>([]);
    const [serviceId, setServiceId] = useState<string>("");

    useEffect(() => {
        const filter: FindEmployeesParams = {
            companyId: id,
        };
        filterObjects<FindEmployeesParams>("employees/filter-all", filter).then((res) => {
            setCollaboratorFilterData(res);
        });
    }, []);

    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(() => {
        setServiceFilterData([]);
        setServiceId("");

        if (collaboratorId === "") {
            return;
        }

        const filter: FindEmployeesServicesParams = {
            companyId: id,
            employeeId: collaboratorId,
        };
        filterObjects<FindEmployeesServicesParams>("employees/services-filter-all", filter).then(
            (res) => {
                setServiceFilterData(res);
            }
        );
        checkNeedSave();
    }, [collaboratorId]);

    const weekDayChangeHandler = (day: number) => {
        if (eventHandler.eventType === EVENT_TYPES.NEED_SAVE) {
            confirm.show(
                "Si no guardas los cambios se perderán. Estas seguro que queres cambiar el dia?",
                () => {
                    setWeekDay(day);
                },
                () => {
                    setWeekDay(weekDay);
                }
            );
        } else {
            setWeekDay(day);
        }
    };

    const checkNeedSave = () => {
        if (collaboratorId !== "" && clientId !== "" && serviceId !== "") {
            eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
        }
    };

    const handleReservar = () => {
        const data: CreateRepeatsParams = {
            companyId: id,
            employeeId: collaboratorId,
            serviceId: serviceId,
            clientId: clientId,
            discountId: discountId,
            weekDay: weekDay,
            startHour: horario.hour() + horario.minute() / 60,
            sessionUser: SessionInfo.userId,
        };

        repeatAdd(data)
            .then(() => {
                goTo("/admin/org/" + id + "/client/" + clientId + "/repeats");
            })
            .catch((error) => {
                if (error instanceof Yup.ValidationError) {
                    alert.showError(error.message);
                } else if (error instanceof ApiError) {
                    alert.showError(error.format());
                }
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />
            <HeaderConfProvider />
            <div style={{ marginTop: "30px" }}>
                <WeekDaySelector value={weekDay} onChange={weekDayChangeHandler} />
                <TextObjectFilter
                    placeholder="Colaborador"
                    content={collaboratorFilterContent}
                    data={collaboratorFilterData}
                    onChange={(id) => {
                        setCollaboratorId(id);
                        checkNeedSave();
                    }}
                />

                <TextObjectFilter
                    placeholder="Servicio"
                    content={serviceFilterContent}
                    data={serviceFilterData}
                    onChange={(id) => {
                        setServiceId(id);
                        checkNeedSave();
                    }}
                    selectedId={serviceId}
                />

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

                <TextTime
                    placeholder="Horario"
                    width="100%"
                    value={horario}
                    onChange={setHorario}
                />

                <Button
                    text="Reservar"
                    width="100%"
                    color="primary"
                    style={{ height: "42px", marginTop: "20px" }}
                    onClick={handleReservar}
                />
            </div>
            <div style={{ marginTop: "15px" }}></div>
        </>
    );
}
