import API_URL from "../../../config/api";
import { useEffect, useState } from "react";
import type { User, Workshop } from "../../../types";
import { Link } from "react-router";
import { CgSpinner } from "react-icons/cg";
import styles from "./styles.module.css";
import { LuPlus, LuCalendar, LuClock3, LuSettings2 } from "react-icons/lu";
import { useGetWorkshops } from "../../../hooks/useGetWorkshops";
import { useDebounce } from "../../../hooks/useDebounce";
import Swal from "sweetalert2";
import { Form, Pagination } from "react-bootstrap";
import { imageSkeletonFadeStyle, onImageSkeletonLoad } from "../../../utils/imageSkeleton";
import { AnimatePresence, motion } from "framer-motion";
import {
    cardInViewTransition,
    cardInViewVariants,
    dropdownTransition,
    dropdownVariants,
    fadeTransition,
    fadeVariants,
    listContentTransition,
    listContentVariants,
    pageTitleTransition,
    pageTitleVariants,
    slideFromLeftTransition,
    slideFromLeftVariants,
    slideFromRightOnMountTransition,
    slideFromRightTransition,
    slideFromRightVariants,
    viewportOnce,
} from "../../../utils/pageMotionVariants";

export default function Workshops() {
    const [loading, setLoading] = useState(true);
    const [selectedWorkshopStatus, setSelectedWorkshopStatus] = useState<string>("pending");
    const [showFilterDropdown, setShowFilterDropdown] = useState(false);
    const { getWorkshops } = useGetWorkshops();
    const [workshops, setWorkshops] = useState<Workshop[]>([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [search, setSearch] = useState<string>("");
    const debouncedSearch = useDebounce(search, 500);
    const [lastPage, setLastPage] = useState(1);
    const [loadingWorkshops, setLoadingWorkshops] = useState(false);
    const [role, setRole] = useState(0);
    const [userId, setUserId] = useState(0);
    const listContentKey = `${currentPage}-${debouncedSearch}-${selectedWorkshopStatus}`;
    /* const [searchLoading, setSearchLoading] = useState(false); */

    useEffect(() => {
        const fetchWorkshops = async () => {
            setLoadingWorkshops(true);

            try {
                const workshopsData = await getWorkshops({
                    page: currentPage,
                    search: debouncedSearch,
                    status: selectedWorkshopStatus,
                });

                if ("workshops" in workshopsData) {
                    setWorkshops(workshopsData.workshops);
                    setUserId(workshopsData.userId);
                    setRole(workshopsData.role);
                    setLastPage(workshopsData.meta.last_page);
                    setCurrentPage(workshopsData.meta.current_page);
                    setLoadingWorkshops(false);
                } else {
                    setWorkshops([]);
                }

            } catch {
                setWorkshops([]);

            } finally {
                setLoading(false);
                setLoadingWorkshops(false);
            }
        };

        fetchWorkshops();
    }, [selectedWorkshopStatus, debouncedSearch, currentPage]);

    /* Inscrever num workshop */
    async function inscrever(workshopId: number) {
        const response = await fetch(`${API_URL}/api/inscrever/${workshopId}`, {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
        });

        const data = await response.json();

        if (response.ok) {
            Swal.fire({
                title: data.message,
                icon: 'success',
                showConfirmButton: false,
                showCloseButton: true,
            });
            const workshopsData = await getWorkshops({
                page: currentPage,
                search: debouncedSearch,
                status: selectedWorkshopStatus,
            });
            if ("workshops" in workshopsData) {
                setWorkshops(workshopsData.workshops);
                setLastPage(workshopsData.meta.last_page);
                setCurrentPage(workshopsData.meta.current_page);
            } else {
                setWorkshops([]);
            }
        } else {
            Swal.fire({
                title: data.message,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
        }
    }

    /* Cancelar inscrição num workshop */
    async function cancelarInscricao(workshopId: number) {
        const response = await fetch(`${API_URL}/api/cancelar-inscricao/${workshopId}`, {
            method: "DELETE",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
        });

        const data = await response.json();

        if (response.ok) {
            Swal.fire({
                title: data.message,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            const workshopsData = await getWorkshops({
                page: currentPage,
                search: debouncedSearch,
                status: selectedWorkshopStatus,
            });
            if ("workshops" in workshopsData) {
                setWorkshops(workshopsData.workshops);
                setLastPage(workshopsData.meta.last_page);
                setCurrentPage(workshopsData.meta.current_page);
            } else {
                Swal.fire({
                    title: data.message,
                    icon: 'error',
                    showConfirmButton: false,
                    showCloseButton: true,
                });
            }
        }
    }

    if (loading) {
        return (
            <div className="text-center mt-5 d-flex flex-column gap-2 align-items-center">
                <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} />
            </div>
        )
    }

    return (
        <div className={`${styles.container} p-2 p-sm-4 p-lg-0`}>
            <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={`${styles.title} mt-1 mb-0 mb-sm-3`}>Workshops</motion.h1>

            <div className="row py-3 g-4 justify-content-between">
                <motion.div variants={slideFromLeftVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromLeftTransition} className="col-12 col-sm-7 col-md-8 col-lg-6 d-flex gap-2 text-start px-2">
                    <Form.Control type="text" placeholder="Pesquisar workshops..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                    />
                </motion.div>
                <motion.div variants={slideFromRightVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromRightTransition} className="col-12 col-sm-5 col-md-4 col-lg-3 d-flex mt-2 mt-sm-4">
                    {/* <label htmlFor="filter" className="form-label fw-bold text-start">Filtrar workshops</label> */}
                    <div
                        className="btn-group flex-grow-1 position-relative"
                        onMouseEnter={() => setShowFilterDropdown(true)}
                        onMouseLeave={() => setShowFilterDropdown(false)}
                    >
                        <button type="button" className="btn btn-outline-secondary w-100 dropdown-toggle text-center">
                            <LuSettings2 /> {selectedWorkshopStatus === 'pending' ? 'Agendados' : selectedWorkshopStatus === 'inscrito' ? 'Inscrito' : selectedWorkshopStatus === 'realized' ? 'Realizados' : 'Cancelados'}
                        </button>

                        <AnimatePresence>
                            {showFilterDropdown && (
                                <motion.ul
                                    variants={dropdownVariants}
                                    initial="initial"
                                    animate="animate"
                                    exit="exit"
                                    transition={dropdownTransition}
                                    className="dropdown-menu text-center w-100"
                                    style={{ display: "block", zIndex: 4000, top: "100%", marginTop: "0.25rem" }}
                                >
                                    <li>
                                        <button
                                            type="button"
                                            className={`dropdown-item ${selectedWorkshopStatus === "pending" ? "active" : ""}`}
                                            onClick={() => { setSelectedWorkshopStatus("pending"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                        >
                                            Agendados
                                        </button>
                                    </li>

                                    {role !== 1 && (
                                        <li>
                                            <button
                                                type="button"
                                                className={`dropdown-item ${selectedWorkshopStatus === "inscrito" ? "active" : ""}`}
                                                onClick={() => { setSelectedWorkshopStatus("inscrito"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                            >
                                                Inscrito
                                            </button>
                                        </li>
                                    )}

                                    <li>
                                        <button
                                            type="button"
                                            className={`dropdown-item ${selectedWorkshopStatus === "realized" ? "active" : ""}`}
                                            onClick={() => { setSelectedWorkshopStatus("realized"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                        >
                                            Realizados
                                        </button>
                                    </li>

                                    <li>
                                        <button
                                            type="button"
                                            className={`dropdown-item ${selectedWorkshopStatus === "canceled" ? "active" : ""}`}
                                            onClick={() => { setSelectedWorkshopStatus("canceled"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                        >
                                            Cancelados
                                        </button>
                                    </li>
                                </motion.ul>
                            )}
                        </AnimatePresence>
                    </div>
                </motion.div>
                {role === 1 ? (
                    <motion.div variants={slideFromRightVariants} initial="initial" animate="animate" transition={slideFromRightOnMountTransition} className="col-12 col-sm col-md-12 col-lg-3 text-end align-content-center mt-4 mt-lg-4" style={{ minHeight: '40px' }}>
                        <Link to="/admin/create-workshop" className={`${styles.btnAdicionarWorkshop} text-decoration-none`}><LuPlus className="mb-1" />Adicionar workshop</Link>
                    </motion.div>
                ) : null}
            </div>

            <div className="row py-3 g-4">
                <AnimatePresence mode="wait">
                    {loadingWorkshops ? (
                        <motion.div key="loading" variants={fadeVariants} initial="initial" animate="animate" exit="exit" transition={fadeTransition} className="col-12 text-center mt-5">
                            <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} />
                        </motion.div>
                    ) : (
                        <motion.div
                            key={listContentKey}
                            variants={listContentVariants}
                            initial="initial"
                            animate="animate"
                            exit="exit"
                            transition={listContentTransition}
                            className="row g-4 p-0 w-100 mx-0 mt-0"
                        >
                {workshops.length > 0 ? (
                    <>
                        {workshops.map((workshop) => (
                            <motion.div key={workshop.id} variants={cardInViewVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={cardInViewTransition} className="col-12 col-sm-6 col-lg-4 p-2 position-relative">
                                <div className={`${styles.boxWorkshop} d-flex flex-column text-start pb-3 h-100`}>
                                    <div className={`${styles.thumbnailWorkshop} position-relative`}>
                                        <img
                                            src={`${API_URL}/storage/${workshop.image}`}
                                            alt={workshop.title}
                                            className={styles.thumbnailWorkshop}
                                            style={imageSkeletonFadeStyle}
                                            onLoad={onImageSkeletonLoad}
                                        />
                                        {(workshop.status === "realized" || workshop.status === "canceled") && (
                                            <span className={`${styles.workshopStatus} position-absolute top-0 end-0 m-2 badge ${workshop.status === "realized" ? "bg-success" : "bg-danger"}`}>
                                                {workshop.status === "realized" ? "Realizado" : "Cancelado"}
                                            </span>
                                        )}
                                        <div className="position-absolute w-100 bottom-0 justify-content-evenly d-none d-md-flex d-xl-none d-xxl-flex mb-2">
                                            <p className={`${styles.dateWorkshop}`}><LuCalendar className={`${styles.icon} mb-1 me-2`} />{workshop.date.split('-').reverse().join('-')}</p>
                                            <p className={`${styles.timeWorkshop}`}> <LuClock3 className={`${styles.icon} mb-1 me-2`} />{workshop.time_start.slice(0, 5)} -  {workshop.time_end.slice(0, 5)}</p>
                                        </div>
                                    </div>
                                        <h2 className={`${styles.titleWorkshop} d-block text-start mt-3 px-3 flex-grow-1 mb-0`}>{workshop.title}</h2>
                                        <div className="position-relative d-flex flex-column d-md-none d-xl-flex d-xxl-none mt-3 px-3">
                                            <span className={`${styles.dateWorkshopMobile} text-start mb-1`}><LuCalendar className={`${styles.icon} mb-1 me-2`} />{workshop.date.split('-').reverse().join('-')}</span>
                                            <span className={`${styles.timeWorkshopMobile} text-start`}><LuClock3 className={`${styles.icon} mb-1 me-2`} />{workshop.time_start.slice(0, 5).split(':').join('h')} -  {workshop.time_end.slice(0, 5).split(':').join('h')}</span>
                                        </div>

                                    <div className="d-flex flex-wrap justify-content-evenly px-3 gap-2 mt-3">
                                        {workshop.status === "realized" || workshop.status === "canceled" ? (
                                            role === 1 && (
                                                <Link to={`/admin/edit-workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-5 text-decoration-none`}>Detalhes</Link>
                                            )
                                        ) : workshop.status === "pending" && role !== 1 && workshop.users.some((u: User) => u.id === userId) ? (
                                            <>
                                                <Link to={`/workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-5 text-decoration-none`}>Detalhes</Link>
                                                <button type="button" className={`${styles.btncancelarInscricao} btn text-center py-2 text-decoration-none`} onClick={() => {
                                                    cancelarInscricao(workshop.id); getWorkshops({
                                                        page: currentPage,
                                                        search: debouncedSearch,
                                                        status: selectedWorkshopStatus,
                                                    });
                                                }} key={workshop.id}>
                                                    Anular inscrição
                                                </button>
                                            </>
                                        ) : role === 1 && workshop.status === "pending" ? (
                                            <Link to={`/admin/edit-workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-5 text-decoration-none`}>Detalhes</Link>
                                        ) : workshop.status === "pending" && role !== 1 ? (
                                            <>
                                                <Link to={`/workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-5 text-decoration-none`}>Detalhes</Link>
                                                <button type="button" className={`${styles.btnInscrever} btn text-center py-2 px-4 text-decoration-none`} onClick={() => {
                                                    inscrever(workshop.id); getWorkshops({
                                                        page: currentPage,
                                                        search: debouncedSearch,
                                                        status: selectedWorkshopStatus,
                                                    });
                                                }} key={workshop.id}>
                                                    Inscrever-me
                                                </button>
                                            </>
                                        ) : null}
                                    </div>
                                </div>
                            </motion.div>
                        ))}
                        <div className="d-flex justify-content-center align-items-center gap-3 py-3">
                            <Pagination>
                                <Pagination.Prev
                                    disabled={currentPage <= 1}
                                    onClick={() => { setCurrentPage((p) => p - 1); setLoadingWorkshops(true); }}
                                />

                                {currentPage > 3 && <Pagination.Item onClick={() => { setCurrentPage(1); setLoadingWorkshops(true); }}>1</Pagination.Item>}
                                {currentPage > 4 && <Pagination.Ellipsis disabled />}

                                {Array.from({ length: 5 }, (_, i) => currentPage - 2 + i)
                                    .filter((p) => p >= 1 && p <= lastPage)
                                    .map((p) => (
                                        <Pagination.Item key={p} active={p === currentPage} onClick={() => { setCurrentPage(p); setLoadingWorkshops(true); }}>
                                            {p}
                                        </Pagination.Item>
                                    ))}

                                {currentPage < lastPage - 3 && <Pagination.Ellipsis disabled />}
                                {currentPage < lastPage - 2 && (
                                    <Pagination.Item onClick={() => { setCurrentPage(lastPage); setLoadingWorkshops(true); }}>{lastPage}</Pagination.Item>
                                )}

                                <Pagination.Next
                                    disabled={currentPage >= lastPage}
                                    onClick={() => { setCurrentPage((p) => p + 1); setLoadingWorkshops(true); }}
                                />
                            </Pagination>
                        </div>
                    </>

                ) : selectedWorkshopStatus === "pending" && workshops.length === 0 ? (
                <div className="col-12 text-center mt-5">
                    <span className="text-muted fs-5">Sem workshops agendados</span>
                </div>
                ) : workshops.length === 0 ? (
                <div className="col-12 text-center mt-5">
                    <span className="text-muted fs-5">Nenhum workshop encontrado com o filtro selecionado</span>
                </div>
                ) : null}
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        </div>
    )
}

