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

export default function Videos() {
    const [loading, setLoading] = useState(true);
    const [error, _setError] = useState<ApiErrorResponse | null>(null);
    const [categories, setCategories] = useState<Category[]>([]);
    const [selectedCategoryId, setSelectedCategoryId] = useState<string>("all");
    const [showFilterDropdown, setShowFilterDropdown] = useState(false);
    const { getVideos } = useGetVideos();
    const [videos, setVideos] = useState<Video[]>([]);
    const [search, setSearch] = useState<string>("");
    const debouncedSearch = useDebounce(search, 500);
    const [currentPage, setCurrentPage] = useState(1);
    const [lastPage, setLastPage] = useState(1);
    const [loadingVideos, setLoadingVideos] = useState(false);
    const videosToShow = videos; 
    const [role, setRole] = useState(0);
    const listContentKey = `${currentPage}-${debouncedSearch}-${selectedCategoryId}`;
    
    useEffect(() => {
        const fetchVideos = async () => {
            setLoadingVideos(true);
    
            try {
                const videosData = await getVideos({
                    page: currentPage,
                    search: debouncedSearch,
                    category:
                        selectedCategoryId !== "all" &&
                        selectedCategoryId !== "active" &&
                        selectedCategoryId !== "inactive" &&
                        selectedCategoryId !== "watched" &&
                        selectedCategoryId !== "unwatched"
                            ? selectedCategoryId
                            : undefined,
                    status:
                        selectedCategoryId === "active"
                            ? "active"
                            : selectedCategoryId === "inactive"
                            ? "inactive"
                            : undefined,
                    watched:
                        selectedCategoryId === "watched"
                            ? 1
                            : selectedCategoryId === "unwatched"
                            ? 0
                            : undefined,
                });
    
                if ("videos" in videosData) {
                    setVideos(videosData.videos);
                    setLastPage(videosData.meta.last_page);
                    setCurrentPage(videosData.meta.current_page);
                    setRole(videosData.role);
                    setCategories(videosData.categories);
                    localStorage.setItem("videosActive", videosData.videosActive.toString());
                    localStorage.setItem("videosWatched", videosData.videosWatched.toString());
                } else {
                    setVideos([]);
                }
    
            } catch {
                setVideos([]);
            } finally {
                setLoading(false);
                setLoadingVideos(false);
            }
        };
    
        fetchVideos();
    }, [debouncedSearch, currentPage, selectedCategoryId]);

    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`} />
                <span>A carregar vídeos...</span>
            </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`}>Vídeos</motion.h1>

            {error && (
                <div className="text-center mt-5 d-flex flex-column gap-2 align-items-center">
                    <span className="text-muted fs-5">{error.message}</span>
                </div>
            )}

            <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 vídeos..."
                        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">
                    <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">
                            <LuSettings2 /> {selectedCategoryId === 'all' ? 'Todos' :
                                selectedCategoryId === 'active' ? 'Ativos' :
                                    selectedCategoryId === 'inactive' ? 'Inativos' :
                                        selectedCategoryId === 'watched' ? 'Vistos' :
                                            selectedCategoryId === 'unwatched' ? 'Não vistos' :
                                                categories.find(c => String(c.id) === selectedCategoryId)?.name ?? 'Todos'}
                        </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 ${selectedCategoryId === "all" ? "active" : ""}`}
                                            onClick={() => { setSelectedCategoryId("all"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                        >
                                            Todos
                                        </button>
                                    </li>

                                    {role !== 1 && (
                                        <>
                                            <li>
                                                <button
                                                    type="button"
                                                    className={`dropdown-item ${selectedCategoryId === "watched" ? "active" : ""}`}
                                                    onClick={() => { setSelectedCategoryId("watched"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                                >
                                                    Vistos
                                                </button>
                                            </li>
                                            <li>
                                                <button
                                                    type="button"
                                                    className={`dropdown-item ${selectedCategoryId === "unwatched" ? "active" : ""}`}
                                                    onClick={() => { setSelectedCategoryId("unwatched"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                                >
                                                    Não vistos
                                                </button>
                                            </li>
                                        </>
                                    )}

                                    {role === 1 && (
                                        <>
                                            <li>
                                                <button
                                                    type="button"
                                                    className={`dropdown-item ${selectedCategoryId === "active" ? "active" : ""}`}
                                                    onClick={() => { setSelectedCategoryId("active"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                                >
                                                    Ativos
                                                </button>
                                            </li>
                                            <li>
                                                <button
                                                    type="button"
                                                    className={`dropdown-item ${selectedCategoryId === "inactive" ? "active" : ""}`}
                                                    onClick={() => { setSelectedCategoryId("inactive"); setCurrentPage(1); setShowFilterDropdown(false); }}
                                                >
                                                    Inativos
                                                </button>
                                            </li>
                                        </>
                                    )}

                                    {categories.map((category) => (
                                        <li key={category.id}>
                                            <button
                                                type="button"
                                                className={`dropdown-item ${selectedCategoryId === String(category.id) ? "active" : ""}`}
                                                onClick={() => { setSelectedCategoryId(String(category.id)); setCurrentPage(1); setShowFilterDropdown(false); }}
                                            >
                                                {category.name}
                                            </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">
                        <Link to="/admin/create-video" className={`${styles.btnAdicionarVideo} text-decoration-none`}><LuPlus className="mb-1" /> Adicionar vídeo</Link>
                    </motion.div>
                )}
            </div>

            <div className={`${styles.containerVideos} mt-3`}>
                <AnimatePresence mode="wait">
                    {loadingVideos ? (
                        <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-3 p-0"
                        >
                    {videosToShow.length > 0 ? (
                        <div>
                            <div className="row g-3 p-0">
                                {videos.map((video) => (
                                    <motion.div key={video.id} variants={cardInViewVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={cardInViewTransition} className="col-12 col-sm-6 col-lg-4 p-2">
                                        <Link to={`/video/${video.id}`} className={`${styles.linkVideo} text-decoration-none text-black`}>
                                            <div className={`${styles.boxVideo} position-relative`} data-category={video.categories?.map((category) => category.id).join(', ')} >
                                                {role === 1 && (
                                                    <Link to={`/admin/edit-video/${video.id}`}> <LuPencil className={`${styles.iconEdit} text-decoration-none`} /> </Link>
                                                )}
                                                <img
                                                    className={`${styles.videoThumbnail} position-absolute top-0 start-0 bottom-0 h-100`}
                                                    src={`${API_URL}/storage/${video.thumbnail}`}
                                                    alt={video.title}
                                                    style={imageSkeletonFadeStyle}
                                                    onLoad={onImageSkeletonLoad}
                                                />
                                                <div className={`${styles.boxVideoInfo} px-3 py-2 text-start text-truncate position-absolute bottom-0`}>
                                                    <h2 className={`${styles.titleVideo} d-flex text-wrap mb-1`}>{video.title}</h2>
                                                    {/*  <span className={`${styles.descriptionVideo} mt-0 pe-3`}>{video.description}</span> */}
                                                </div>
                                                {video.watched && <span className="d-block badge text-success text-start fs-6 position-absolute top-0 start-0 bg-success-subtle text-success px-3 py-2" style={{ borderRadius: "0 0 var(--border-radius) 0" }}><PiCheckCircleFill className="mb-1 me-1" /> Visto</span>}
                                            </div>
                                        </Link>
                                    </motion.div>
                                ))}
                            </div>
                            <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); setLoadingVideos(true); }}
                                        />

                                        {currentPage > 3 && <Pagination.Item onClick={() => { setCurrentPage(1); setLoadingVideos(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); setLoadingVideos(true); }}>
                                                    {p}
                                                </Pagination.Item>
                                            ))}

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

                                        <Pagination.Next
                                            disabled={currentPage >= lastPage}
                                            onClick={() => { setCurrentPage((p) => p + 1); setLoadingVideos(true); }}
                                        />
                                    </Pagination>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <>
                            {videosToShow.length === 0 && (
                                <div className="col-12 text-center mt-5">
                                    <span className="text-muted fs-5">Nenhum vídeo encontrado com o filtro selecionado</span>
                                </div>
                            )}
                        </>
                    )}
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        </div>
    )
}
