"use client";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
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 TextObjectFilter from "@components/TextObjectFilter/TextObjectFilter";
import { TextObjectModalContent } from "@store/TextObjectModal.Store";
import { TOFClientsParams, TextObjectFilterResult } from "@models/TextObjectFilter.model";
import filterObjects from "@core/app/components/TextObjectFilter/Filter.Service";
import TextObjectFilterItem from "@components/TextObjectFilterItem/TextObjectFilterItem";
import { FindEmployeesParams, FindEmployeesServicesParams } from "@core/Models/Collaborators.model";
import TextTime from "@components/TextTime/TextTime";

import dayjs from "dayjs";
import "dayjs/locale/es";
import { CreateAppointmentParams } from "@core/Models/Appointments.model";
import { useSessionStore } from "@store/Sesion.Store";
import { createAppointment } from "../Appointment.Service";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import Switch from "@mui/material/Switch";
import { ThemeProvider } from "@emotion/react";
import turnosXpressTheme from "@core/app/theme/turnosXpress";

dayjs.locale("es");

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

export default function ClientCreate() {
    const data = useParams<UrlData>();
    const id = data.id;
    const appointmentDate = dayjs(decodeURIComponent(data.appdate));
    const SessionUser = useSessionStore();
    const alert = useAlert();
    const { goTo } = useNavigation();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();

    const [validation, setValidation] = useState<boolean>(true);
    const [notification, setNotification] = useState<boolean>(true);

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

    const [clientFilterData, setClientFilterData] = useState<TextObjectFilterResult[]>([]);
    const [clientId, setClientId] = useState<string>("");

    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(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        const filter: TOFClientsParams = {
            companyId: id,
        };
        filterObjects<TOFClientsParams>("clients/filter-all", filter).then((res) => {
            setClientFilterData(res);
        });
    }, []);

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

    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 [horario, setHorario] = useState<dayjs.Dayjs>(dayjs(new Date()).hour(8).minute(0));

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

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

        location.add({
            url:
                "/admin/org/profile/" +
                id +
                "/appointments/" +
                encodeURIComponent(dayjs(appointmentDate).clone().startOf("day").toISOString()),
            title: "Turnos",
            icon: <ClientsIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            const addData: CreateAppointmentParams = {
                companyId: id,
                serviceId: serviceId,
                clientId: clientId,
                employeeId: collaboratorId,
                start: appointmentDate.hour(horario.hour()).minute(horario.minute()).toISOString(),
                validation: validation,
                notification: notification,
                sessionUser: SessionUser.userId,
            };

            eventHandler.setEventType(EVENT_TYPES.LOADING);

            createAppointment(addData)
                .then(() => {
                    alert.showSuccess("Turno creado con exito");

                    goTo(
                        "/admin/org/profile/" +
                            id +
                            "/appointments/" +
                            encodeURIComponent(
                                dayjs(appointmentDate).clone().startOf("day").toISOString()
                            )
                    );
                })
                .catch((error) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    useEffect(() => {
        checkNeedSave();
    }, [collaboratorId, clientId, serviceId]);

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

    return (
        <>
            <Location />
            <div style={{ marginTop: "15px" }}>
                Nuevo turno para el dia{" "}
                <strong>{appointmentDate.format("dddd DD [de] MMMM, YYYY")}</strong>
            </div>

            <TextObjectFilter
                placeholder="Cliente"
                content={clientFilterContent}
                data={clientFilterData}
                onChange={(id) => {
                    setClientId(id);
                    checkNeedSave();
                }}
            />

            <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}
            />

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

            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",

                    marginTop: "10px",
                }}
            >
                <ThemeProvider theme={turnosXpressTheme}>
                    <Switch
                        checked={validation}
                        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                            setValidation(event.target.checked);
                        }}
                        size="medium"
                    />
                </ThemeProvider>
                <span
                    style={{
                        fontSize: "16px",
                        fontWeight: "600",
                        color: "var(--black)",
                    }}
                >
                    Validar disponibilidad?
                </span>
            </div>

            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",

                    marginTop: "10px",
                }}
            >
                <ThemeProvider theme={turnosXpressTheme}>
                    <Switch
                        checked={notification}
                        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                            setNotification(event.target.checked);
                        }}
                        size="medium"
                    />
                </ThemeProvider>
                <span
                    style={{
                        fontSize: "16px",
                        fontWeight: "600",
                        color: "var(--black)",
                    }}
                >
                    Enviar notificatión?
                </span>
            </div>

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