"use client";
import AnimatedContainer from "@components/AnimatedConainer/AnimatedContainer";
import { useNavigation } from "@core/app/hooks/goto";
import { useEffect, useState } from "react";
import {
    findAppointmentByUserPaginated,
    findAppointmentByCollaboratorPaginated,
} from "./Appointments.Service";
import { EVENT_TYPES, useEventHandlerStore } from "@core/Store/EventHandler.Store";
import { useAlert } from "@core/Store/Alert.Store";
import { AppointmentEventByClient } from "@core/Models/Appointments.model";
import { useSessionStore } from "@core/Store/Sesion.Store";
import dayjs from "dayjs";
import "dayjs/locale/es";
import ExploreCategories from "@core/app/components/ExploreCategories/ExploreCategories";
import useContainerHeight from "@core/app/hooks/ContainerHeight";
import { ScrollToTop } from "@core/app/components/ScrollTop";
import PendingRepeatsCard from "@core/app/components/PendingRepeatsCard/PendingRepeatsCard";
import HeaderConfProvider from "@core/app/components/HeaderConfProvider/HeaderConfProvider";
import { Button, Tabs, Tab, Box } from "@mui/material";
import { ThemeProvider } from "@emotion/react";
import turnosXpressTheme from "@core/app/theme/turnosXpress";

dayjs.locale("es");

interface TabPanelProps {
    children?: React.ReactNode;
    index: number;
    value: number;
}

function CustomTabPanel(props: TabPanelProps) {
    const { children, value, index, ...other } = props;

    return (
        <div
            role="tabpanel"
            hidden={value !== index}
            id={`appointments-tabpanel-${index}`}
            aria-labelledby={`appointments-tab-${index}`}
            style={{ width: "100%" }}
            {...other}
        >
            {value === index && <Box sx={{ p: 3, width: "100%" }}>{children}</Box>}
        </div>
    );
}

function a11yProps(index: number) {
    return {
        id: `appointments-tab-${index}`,
        "aria-controls": `appointments-tabpanel-${index}`,
    };
}

const AppointmentList = ({ appointments, containerHeight, emptyMessage, goTo, isProfessionalView }: { appointments: any, containerHeight: any, emptyMessage: string, goTo: any, isProfessionalView: boolean }) => {
    if (appointments.length === 0) {
        return <ExploreCategories containerHeight={containerHeight} message={emptyMessage} />;
    }

    return (
        <div
            style={{
                display: "flex",
                flexDirection: "column",
                justifyContent: "flex-start",
                alignItems: "flex-start",
                marginTop: "20px",
                width: "100%",
                gap: "20px",
                marginBottom: "40px",
                minHeight: "50vh",
            }}
        >
            {appointments.map((item: AppointmentEventByClient, index: number) => (
                <div
                    key={index}
                    style={{
                        display: "flex",
                        flexDirection: "row",
                        justifyContent: "flex-start",
                        alignItems: "flex-start",
                        width: "100%",
                        gap: "20px",
                        borderBottom: "solid 1px var(--gray-light)",
                    }}
                >
                    <div
                        style={{
                            width: "120px",
                            minWidth: "120px",
                            display: "flex",
                            flexDirection: "column",
                            justifyContent: "center",
                            alignItems: "center",
                            borderRight: "solid 1px var(--gray-light)",
                            color: "var(--black)",
                            marginBottom: "20px",
                        }}
                    >
                        <div
                            style={{
                                fontWeight: "bold",
                                fontSize: "60px",
                                color: "var(--wine-red)",
                            }}
                        >
                            {dayjs(item.appointmentDate).format("D")}
                        </div>
                        <div
                            style={{
                                fontWeight: "bold",
                                fontSize: "20px",
                                textTransform: "uppercase",
                                color: "var(--wine-red)",
                            }}
                        >
                            {dayjs(item.appointmentDate).format("MMMM").substring(0, 3)}
                        </div>
                    </div>
                    <div
                        style={{
                            paddingTop: "15px",
                            color: "var(--black)",
                            cursor: "pointer",
                            width: "100%",
                        }}
                    >
                        <h1 style={{ fontSize: "24px" }}>{item.serviceName}</h1>
                        <p>{item.serviceDescription}</p>
                        <p
                            style={{
                                color: "var(--gray-dark)",
                                fontSize: "14px",
                                marginTop: "4px",
                                marginBottom: "4px",
                            }}
                        >
                            {isProfessionalView ? (
                                <>
                                    Cliente:{" "}
                                    <strong style={{ color: "var(--black)" }}>{item.clientName}</strong>
                                </>
                            ) : (
                                <>
                                    Profesional:{" "}
                                    <strong style={{ color: "var(--black)" }}>{item.collaboratorName}</strong>
                                </>
                            )}
                        </p>
                        <p style={{ color: "var(--gray-dark)", fontWeight: "bold" }}>
                            {dayjs(item.appointmentDate).format("HH:mm")} hs.
                        </p>
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "flex-end",
                                marginBottom: "20px",
                            }}
                        >
                            <ThemeProvider theme={turnosXpressTheme}>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    onClick={() => {
                                        if (isProfessionalView) {
                                            goTo(
                                                `/admin/org/${item.companyId}/client/${item.clientId}/appointments/${item.id}`,
                                            );
                                        } else {
                                            goTo(`/landing/my-appointments/${item.id}`);
                                        }
                                    }}
                                >
                                    Ver turno
                                </Button>
                            </ThemeProvider>
                        </div>
                    </div>
                </div>
            ))}
        </div>
    );
};

export default function MyAppointmentsPage() {
    const [clientAppointments, setClientAppointments] = useState<AppointmentEventByClient[]>([]);
    const [collaboratorAppointments, setCollaboratorAppointments] = useState<AppointmentEventByClient[]>([]);
    const [clientPage, setClientPage] = useState(1);
    const [clientHasMore, setClientHasMore] = useState(false);
    const [collaboratorPage, setCollaboratorPage] = useState(1);
    const [collaboratorHasMore, setCollaboratorHasMore] = useState(false);
    const [tabValue, setTabValue] = useState(0);
    const containerHeight = useContainerHeight();
    const eventHandler = useEventHandlerStore();
    const SessionInfo = useSessionStore();
    const alert = useAlert();
    const { goTo } = useNavigation();

    const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
        setTabValue(newValue);
    };

    useEffect(() => {
        if (!SessionInfo.userId) {
            eventHandler.setEventType(EVENT_TYPES.SLEEP);
            return;
        }
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        Promise.all([
            findAppointmentByUserPaginated({ sessionUser: SessionInfo.userId, page: 1, limit: 10 }),
            findAppointmentByCollaboratorPaginated({ sessionUser: SessionInfo.userId, page: 1, limit: 10 }),
        ])
            .then(([resUser, resCollaborator]) => {
                setClientAppointments(resUser.data);
                setClientHasMore(resUser.page < resUser.pages);

                setCollaboratorAppointments(resCollaborator.data);
                setCollaboratorHasMore(resCollaborator.page < resCollaborator.pages);

                if (resUser.data.length === 0 && resCollaborator.data.length > 0) {
                    setTabValue(1);
                }
            })
            .catch((error: Error | any) => {
                if (error.format) {
                    alert.showError(error.format());
                } else {
                    alert.showError(error.message);
                }
                console.error(error);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    }, [SessionInfo.userId]);

    const handleLoadMoreClient = () => {
        const nextPage = clientPage + 1;
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findAppointmentByUserPaginated({ sessionUser: SessionInfo.userId, page: nextPage, limit: 10 })
            .then((res) => {
                setClientAppointments((prev) => [...prev, ...res.data]);
                setClientPage(nextPage);
                setClientHasMore(res.page < res.pages);
            })
            .catch((error) => alert.showError(error.message))
            .finally(() => eventHandler.setEventType(EVENT_TYPES.SLEEP));
    };

    const handleLoadMoreCollaborator = () => {
        const nextPage = collaboratorPage + 1;
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findAppointmentByCollaboratorPaginated({ sessionUser: SessionInfo.userId, page: nextPage, limit: 10 })
            .then((res) => {
                setCollaboratorAppointments((prev) => [...prev, ...res.data]);
                setCollaboratorPage(nextPage);
                setCollaboratorHasMore(res.page < res.pages);
            })
            .catch((error) => alert.showError(error.message))
            .finally(() => eventHandler.setEventType(EVENT_TYPES.SLEEP));
    };

    return (
        <AnimatedContainer
            color="#aeaeae"
            minSize={150}
            maxSize={500}
            items={10}
            style={{
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
            }}
        >
            <ScrollToTop />
            <HeaderConfProvider />
            <div className="homeCentered" style={{ width: "100%", maxWidth: "1200px" }}>
                <h1 className="homeTitleHeader" style={{ textAlign: "center", width: "100%" }}>
                    Mis Turnos
                </h1>

                <Box sx={{ width: "100%", mt: 4 }}>
                    {collaboratorAppointments.length > 0 ? (
                        <>
                            <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
                                <ThemeProvider theme={turnosXpressTheme}>
                                    <Tabs
                                        value={tabValue}
                                        onChange={handleTabChange}
                                        aria-label="appointments tabs"
                                        centered
                                    >
                                        <Tab label="Como Cliente" {...a11yProps(0)} />
                                        <Tab label="Como Profesional" {...a11yProps(1)} />
                                    </Tabs>
                                </ThemeProvider>
                            </Box>
                            <CustomTabPanel value={tabValue} index={0}>
                                <AppointmentList
                                    appointments={clientAppointments}
                                    containerHeight={containerHeight}
                                    emptyMessage="Aun no tienes ninguna reserva hecha como cliente."
                                    goTo={goTo}
                                    isProfessionalView={false}
                                />
                                {clientHasMore && (
                                    <Box sx={{ display: "flex", justifyContent: "center", mt: 3, mb: 3 }}>
                                        <ThemeProvider theme={turnosXpressTheme}>
                                            <Button
                                                variant="outlined"
                                                color="primary"
                                                onClick={handleLoadMoreClient}
                                            >
                                                Cargar Más
                                            </Button>
                                        </ThemeProvider>
                                    </Box>
                                )}
                            </CustomTabPanel>
                            <CustomTabPanel value={tabValue} index={1}>
                                <Box sx={{ display: "flex", justifyContent: "flex-end", mb: 2 }}>
                                    <ThemeProvider theme={turnosXpressTheme}>
                                        <Button
                                            variant="contained"
                                            color="primary"
                                            onClick={() => goTo("/landing/dashboard")}
                                            sx={{
                                                borderRadius: "8px",
                                                textTransform: "none",
                                                fontWeight: 600,
                                                px: 3,
                                                py: 1,
                                                boxShadow: "0 4px 12px rgba(225, 29, 72, 0.2)",
                                                "&:hover": {
                                                    boxShadow: "0 6px 16px rgba(225, 29, 72, 0.3)",
                                                    transform: "translateY(-2px)",
                                                },
                                                transition: "all 0.2s ease-in-out",
                                            }}
                                        >
                                            Ir a mi Dashboard
                                        </Button>
                                    </ThemeProvider>
                                </Box>
                                <PendingRepeatsCard />
                                <AppointmentList
                                    appointments={collaboratorAppointments}
                                    containerHeight={containerHeight}
                                    emptyMessage="No tienes turnos asignados como profesional."
                                    goTo={goTo}
                                    isProfessionalView={true}
                                />
                                {collaboratorHasMore && (
                                    <Box sx={{ display: "flex", justifyContent: "center", mt: 3, mb: 3 }}>
                                        <ThemeProvider theme={turnosXpressTheme}>
                                            <Button
                                                variant="outlined"
                                                color="primary"
                                                onClick={handleLoadMoreCollaborator}
                                            >
                                                Cargar Más
                                            </Button>
                                        </ThemeProvider>
                                    </Box>
                                )}
                            </CustomTabPanel>
                        </>
                    ) : (
                        <Box sx={{ p: 3, width: "100%" }}>
                            <AppointmentList
                                appointments={clientAppointments}
                                containerHeight={containerHeight}
                                emptyMessage="Aun no tienes ninguna reserva hecha."
                                goTo={goTo}
                                isProfessionalView={false}
                            />
                            {clientHasMore && (
                                <Box sx={{ display: "flex", justifyContent: "center", mt: 3, mb: 3 }}>
                                    <ThemeProvider theme={turnosXpressTheme}>
                                        <Button
                                            variant="outlined"
                                            color="primary"
                                            onClick={handleLoadMoreClient}
                                        >
                                            Cargar Más
                                        </Button>
                                    </ThemeProvider>
                                </Box>
                            )}
                        </Box>
                    )}
                </Box>
            </div>
        </AnimatedContainer>
    );
}
