import API_URL from "../../../config/api";
import { useEffect, useState } from "react";
import type { ApiErrorResponse, User, Video, Workshop } from "../../../types";
import { Link, useSearchParams } from "react-router";
import styles from "./styles.module.css";
import { CgSpinner } from "react-icons/cg";
import { LuCalendar, LuClock3, LuPencil } from "react-icons/lu";
import { useGetVideosSearch } from "../../../hooks/useGetVideosSearch";
import { useGetWorkshopsSearch } from "../../../hooks/useGetWorkshopsSearch";
import { PiCheckCircleFill } from "react-icons/pi";
import { imageSkeletonFadeStyle, onImageSkeletonLoad } from "../../../utils/imageSkeleton";
import { motion } from "framer-motion";
import { pageTitleTransition, pageTitleVariants, slideFromBottomTransition, slideFromBottomVariants, slideFromTopTransition, slideFromTopVariants, viewportOnce } from "../../../utils/pageMotionVariants";


export default function Search() {
    const [videos, setVideos] = useState<Video[]>([]);
    const [workshops, setWorkshops] = useState<Workshop[]>([]);
    const [error, _setError] = useState<ApiErrorResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const { getVideosSearch } = useGetVideosSearch();
    const { getWorkshopsSearch } = useGetWorkshopsSearch();

    const [searchParams] = useSearchParams();
    const query = (searchParams.get("q") ?? "").trim();

    const user = JSON.parse(localStorage.getItem("user") || "{}") as User;
    const isAdmin = user.role_id === 1;

    useEffect(() => {
        const fetchAll = async () => {
            setLoading(true);


            const [videoResponse, workshopResponse] = await Promise.all([ 
                getVideosSearch(query),
                getWorkshopsSearch(query),
            ]);
    
            let videoData: Video[] = [];
            let workshopData: Workshop[] = [];
            
            if("videos" in videoResponse) {
                videoData = videoResponse.videos;
                setVideos(videoData);
            } else {
                setVideos([]);
            }
            
            if("workshops" in workshopResponse) {
                workshopData = workshopResponse.workshops;
                setWorkshops(workshopData);
            } else {
                setWorkshops([]);
            }
            
            setLoading(false);
        };

        fetchAll();
    }, [query]);

    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 os resultados da sua pesquisa...</span>
            </div>
        );
    }

    if(error) {
        return(
            <div className="text-center mt-5 d-flex flex-column gap-2 align-items-center">
                <span className="text-muted">Ocorreu um erro ao carregar os resultados da sua pesquisa.</span>
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={`${styles.subtitle} mb-4`}>Resultados da pesquisa: "{query}"</motion.h1>

            {videos.length > 0 ? (
                <div className="row g-3 p-0">
                    <motion.h2 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={`${styles.title} text-start`}>Vídeos</motion.h2>
                    <motion.span variants={slideFromTopVariants} initial="initial" animate="animate" transition={slideFromTopTransition} className="text-muted text-start mt-0">{videos.length === 1 ? `Foi encontrado ${videos.length} vídeo na sua pesquisa.` : `Foram encontrados ${videos.length} vídeos na sua pesquisa.`}</motion.span>
                    {videos.map((video) => (
                        <motion.div variants={slideFromBottomVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromBottomTransition} className="col-12 col-sm-6 col-lg-4 p-2">
                        <Link to={`/video/${video.id}`} className={`${styles.linkVideo} text-decoration-none text-black`} key={video.id}>
                            <div className={`${styles.boxVideo} position-relative`} data-category={video.categories?.map((category) => category.id).join(', ')} >
                                {isAdmin && (
                                    <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>
                                </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>
            ) : null}

            {workshops.length > 0 ? (
                <div className="row g-3 p-0 mt-3">
                    <motion.h2 variants={pageTitleVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={pageTitleTransition} className={`${styles.title} text-start`}>Workshops</motion.h2>
                    <motion.span variants={slideFromTopVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromTopTransition} className="text-muted text-start mt-0">{workshops.length === 1 ? `Foi encontrado ${workshops.length} workshop na sua pesquisa.` : `Foram encontrados ${workshops.length} workshops na sua pesquisa.`}</motion.span>
                    {workshops.map((workshop) => (
                        <motion.div variants={slideFromBottomVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromBottomTransition} className="col-12 col-sm-6 col-lg-4  p-2 position-relative" key={workshop.id}>
                            <div className={`${styles.boxWorkshop} text-start pb-3`}>
                                <div className={`${styles.thumbnailWorkshop} position-relative`}>
                                    <img
                                        src={`${API_URL}/storage/${workshop.image}`}
                                        alt={workshop.title}
                                        className={styles.thumbnailWorkshop}
                                        style={imageSkeletonFadeStyle}
                                        onLoad={onImageSkeletonLoad}
                                    />
                                    <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>
                                <div className="px-3">
                                    <h2 className={`${styles.titleWorkshop} d-block text-start mt-3`}>{workshop.title}</h2>
                                    <div className="position-relative d-flex flex-column d-md-none d-xl-flex d-xxl-none mt-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>
                                <Link to={`/workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center mt-3 py-2 px-5 mx-auto text-decoration-none`}> Detalhes </Link>
                            </div>
                        </motion.div>
                    ))}
                </div>
            ) : null}

            {videos.length === 0 && workshops.length === 0 ? (
                <div className="mt-5" role="alert">
                    <span className="text-muted">Não foram encontrados resultados na sua pesquisa.</span>
                </div>
            ) : null}
        </div>
    );
}