import API_URL from "../../../config/api";
import { useEffect, useState } from "react";
import type { ApiErrorResponse, Video, Workshop, DashboardResponse } from "../../../types";
import styles from "./styles.module.css";
import { LuArrowUpRight, LuCalendar, LuClock3, LuPencil } from "react-icons/lu";
import { Link } from "react-router";
import { CgSpinner } from "react-icons/cg";
import AnimatedProgressBar from "../../../components/animatedProgressBar";
import AnimatedCounter from "../../../components/animatedNumberCount";
import { motion } from "framer-motion";
import {
    slideFromLeftOnMountTransition,
    slideFromLeftInViewTransition03,
    slideFromLeftVariants,
    slideFromRightOnMountTransition02,
    slideFromRightInViewTransition04,
    slideFromRightVariants,
    viewportOnce,
} from "../../../utils/pageMotionVariants";
/* import { useGetCurrentUser } from "../../../hooks/useGetCurrentUser"

import { useGetVideosLength } from "../../../hooks/useGetVideosLength";
import { useNextVideos } from "../../../hooks/useNextVideos";
import { useNextWorkshops } from "../../../hooks/useNextWorkshops";
import { useGetWorkshopsLength } from "../../../hooks/useGetWorkshopsLength"; */
import Swal from "sweetalert2";
import { PiCheckCircleFill } from "react-icons/pi";
import { imageSkeletonFadeStyle, onImageSkeletonLoad } from "../../../utils/imageSkeleton";


export default function Home() {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const [messageSuccess, setMessageSuccess] = useState<string | null>(null);
    const [sending, setSending] = useState(false);
    const [videos, setVideos] = useState<Video[]>([]);
    const [videosWatched, setVideosWatched] = useState(0);
    const [videosCount, setVideosCount] = useState(0);
    const [workshops, setWorkshops] = useState<Workshop[]>([]);
    const [workshopsInscribed, setWorkshopsInscribed] = useState(0);
    const [workshopsCount, setWorkshopsCount] = useState(0);
    const [role, setRole] = useState(0);
    const [userId, setUserId] = useState<number | null>(null);

    useEffect(() => {
        getDashboard();
    }, []);

    async function getDashboard() {
        setLoading(true);
        const response = await fetch(`${API_URL}/api/dashboard`, {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
        });

        const data = await response.json();

        if (response.ok) {
            setVideos(data.videos);
            setVideosWatched(data.videosWatched);
            setVideosCount(data.videosCount);
            setWorkshops(data.workshops);
            setWorkshopsInscribed(data.workshopsInscribed);
            setWorkshopsCount(data.workshopsCount);
            setRole(data.role);
            setUserId(data.userId);

            localStorage.setItem("videosWatched", data.videosWatched.toString());
            localStorage.setItem("videosCount", data.videosCount.toString());
            setLoading(false);
        } else {
            setError(data as ApiErrorResponse);
            setLoading(false);
        }
    }
    /* Vídeos */
    let progressoVideos = Math.round(videosWatched / videosCount * 100);

    /* 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,
            });
            getDashboard();
            setWorkshops(data.workshops as DashboardResponse['workshops']);
        } 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,
            });
            getDashboard();
            setWorkshops(data.workshops as DashboardResponse['workshops']);
        } else {
            Swal.fire({
                title: data.message,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
        }
    }

    /* Formulário de contacto */
    async function sendMail(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formElement = event.currentTarget;

        const formData = new FormData(formElement);
        const name = formData.get("name");
        const email = formData.get("email");
        const subject = formData.get("subject");
        const message = formData.get("message");

        const payload = {
            name: name,
            email: email,
            subject: subject,
            message: message,
        };

        setSending(true);
        const response = await fetch(`${API_URL}/api/contact`, {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: JSON.stringify(payload),
        });

        const data = await response.json();

        if (response.ok) {
            setError(null);
            setSending(false);
            setMessageSuccess(data.message);
            setTimeout(() => {
                setMessageSuccess("");
            }, 3000)
            formElement.reset();
        } else {
            setError(data as ApiErrorResponse);
            setSending(false);
            setMessageSuccess("");
        }
    }

    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} mx-2 mx-sm-0 p-2 p-sm-4 p-lg-0`}>

            <motion.div variants={slideFromLeftVariants} initial="initial" animate="animate" transition={slideFromLeftOnMountTransition} className={`${styles.containerVideos} px-2 p-sm-4 mx-sm-1 mx-lg-0`}>
                <div className="d-flex flex-column flex-sm-row justify-content-between align-items-center px-0" >
                    <h2 className={`${styles.subtitle} text-center text-sm-start mt-4 mt-sm-3 mb-4 px-0 `}>{role === 1 ? "Vídeos ativos" : "Continuar Formação"}</h2>
                    <Link to="/videos" className={`${styles.link} text-decoration-none fw-semibold fs-5 mt-sm-3 mb-4`}>Ver vídeos <LuArrowUpRight className="mb-1 me-2" size={25} /></Link>
                </div>

                {role !== 1 && (
                    <>
                        <AnimatedProgressBar value={progressoVideos ?? 0} className={`${styles.progressBar}`} />

                        {progressoVideos === 100 && (
                            <div className="text-center mt-3">
                                <span className="text-black fw-bold fs-6">Parabéns! A sua formação está completa!</span>
                            </div>
                        )}
                    </>
                )}

                <div className="row mt-4 px-2">
                    {videos.length > 0 ? videos.map((video: Video) => (
                        <div 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(', ')} >
                                    {role === 1 && (
                                        <Link to={`/admin/edit-video/${video.id}`}> <LuPencil className={`${styles.iconEdit} text-decoration-none`} /> </Link>
                                    )}
                                    <img
                                        src={`${API_URL}/storage/${video.thumbnail}`}
                                        className={`${styles.videoThumbnail} position-absolute top-0 start-0 bottom-0 h-100`}
                                        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 text-truncate`}>{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>
                        </div>
                    )) : videos.length === 0 ? (
                        <div className="col-12 text-start ps-1">
                            <span className="text-muted fs-5">Nenhum vídeo encontrado</span>
                        </div>
                    ) : null}
                </div>
            </motion.div>

            <motion.div variants={slideFromRightVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromRightOnMountTransition02} className="ms-0 px-lg-4 mt-4">
                <div className="d-flex flex-column flex-sm-row justify-content-between align-items-center px-0" >
                    <h2 className={`${styles.subtitle} text-center text-sm-start mt-4 mt-sm-3 mb-4`}>Próximos workshops</h2>
                    <Link to="/workshops" className={`${styles.link} text-decoration-none fw-semibold fs-5 mt-sm-3 mb-sm-4`}>Ver workshops <LuArrowUpRight className="mb-1 me-2" size={25} /></Link>
                </div>
                <div className="row mt-4 mt-sm-1 px-1 px-sm-2">
                    {workshops.length > 0 ? workshops.map((workshop: Workshop) => (
                        <div 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}
                                    />
                                    <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">
                                    <Link to={`${role === 1 ? `/admin/edit-workshop/${workshop.id}` : `/workshop/${workshop.id}`}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-5 text-decoration-none`}> Detalhes </Link>

                                    {role !== 1 ? (
                                        (workshop.users as unknown as number[]).includes(userId as number) ? (
                                            <button type="button" className={`${styles.btncancelarInscricao} btn text-center py-2  text-decoration-none`} onClick={() => cancelarInscricao(workshop.id)} key={workshop.id}>
                                                Anular inscrição
                                            </button>
                                        ) : (
                                            <button type="button" className={`${styles.btnInscrever} btn text-center py-2 px-4 text-decoration-none`} onClick={() => inscrever(workshop.id)} key={workshop.id}>
                                                Inscrever-me
                                            </button>
                                        )
                                    ) : null}
                                </div>
                            </div>
                        </div>
                    )
                    ) : workshops.length === 0 ? (
                        <div className="col-12 text-center text-sm-start px-0">
                            <span className="text-black text-muted fs-5 ms-sm-2 ps-sm-1">Sem workshops agendados</span>
                        </div>
                    ) : null}
                </div>
            </motion.div>


            <div className="row">
                <motion.div variants={slideFromLeftVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromLeftInViewTransition03} className="col-12 col-lg-8 mt-5 px-3">
                    <form onSubmit={sendMail} className="pt-2 px-1">
                        <div className="row g-3 bg-white p-4 mt-3" style={{ borderRadius: "var(--border-radius)" }}>
                            <div className="text-center text-sm-start mb-4">
                                <h2 className={styles.subtitle}>Formulário de contacto</h2>
                                <span>Preencha o formulário abaixo para entrar em contacto connosco</span>
                            </div>
                            <div className="col-12 col-md-6 text-start mt-0">
                                <label className={styles.label} htmlFor="name">Nome</label>
                                <input type="text" className="form-control py-2 border" placeholder="Nome completo" id="name" name="name" />
                            </div>
                            <div className="col-12 col-md-6 text-start mt-0">
                                <label className={styles.label} htmlFor="email">E-mail</label>
                                <input type="email" placeholder="E-mail" className="form-control py-2 border" id="email" name="email" />
                            </div>
                            <div className="col-12 text-start">
                                <label className={styles.label} htmlFor="subject">Assunto</label>
                                <select className="form-select py-2 border" id="subject" name="subject" defaultValue="">
                                    <option value="" disabled>Assunto</option>
                                    <option value="Suporte Técnico" >Suporte Técnico</option>
                                    <option value="Sugestão">Sugestão</option>
                                    <option value="Dúvida">Dúvida</option>
                                    <option value="Outro">Outro</option>
                                </select>
                            </div>

                            <div className="col-12 text-start">
                                <label className={styles.label} htmlFor="message">Mensagem</label>
                                <textarea rows={5} className="form-control border  py-2" id="message" name="message" placeholder="Escreva aqui a sua mensagem..." />
                            </div>

                            {error && (
                                <div className="col-12 text-center">
                                    <span className="text-danger">{error.message}</span>
                                </div>
                            )}

                            {messageSuccess && (
                                <div className="col-12 text-center ">
                                    <span className="text-success">{messageSuccess}</span>
                                </div>
                            )}

                            <div className="col-12 text-center text-sm-end">
                                <button type="submit" className={`${styles.submitButton}`} disabled={sending}>{sending ? (<><span>A enviar...</span> <CgSpinner className={`${styles.animateSpin} mb-1`} size={20} /></>) : "Submeter"}</button>
                            </div>
                        </div>
                    </form>
                </motion.div>

                <motion.div variants={slideFromRightVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={slideFromRightInViewTransition04} className="col-12 col-lg-4 mt-lg-5 px-sm-0 ps-lg-4 pe-lg-3 px-2">
                    <div className="h-100 pt-4 px-1 px-lg-0">
                        <div className={`${styles.userVideosWatched} text-start justify-content-evenly d-flex flex-column h-100 p-4 mx-sm-2 ms-lg-2 me-lg-0`}>
                            <div className="d-flex flex-column">
                                <span className="fw-normal fs-3 text-white" > {role === 1 ? "Vídeos ativos" : "Vídeos assistidos"}</span>
                                <span className=" fw-bold text-white" style={{ fontSize: "4rem" }}>
                                    {role === 1
                                        ? <AnimatedCounter value={videosCount} />
                                        : <> <AnimatedCounter value={videosWatched} />/<AnimatedCounter value={videosCount} /></>
                                    }
                                </span>
                            </div>

                            <div className="d-flex flex-column">
                                <span className="fw-normal fs-3" style={{ color: "var(--bg-grey)" }}>{role === 1 ? "Workshops agendados" : "Workshops inscrito"}</span>
                                <span className="fw-bold text-white" style={{ fontSize: "4rem" }}>
                                    {role === 1
                                        ? <AnimatedCounter value={workshopsCount} />
                                        : <> <AnimatedCounter value={workshopsInscribed} />/<AnimatedCounter value={workshopsCount} /></>
                                    }
                                </span>
                            </div>
                        </div>
                    </div>
                </motion.div>
            </div>

        </div>
    )
}
