import API_URL from "../../../../config/api";
import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router";
import type { ApiErrorResponse, User, Workshop } from "../../../../types";
import styles from "./styles.module.css";
import { LuCheck, LuTrash2, LuX, LuPencil, LuArrowLeft, LuCalendar, LuClock3 } from "react-icons/lu";
import { imageSkeletonFadeStyle, onImageSkeletonLoad } from "../../../../utils/imageSkeleton";
import { CgSpinner } from "react-icons/cg";
import Swal from "sweetalert2";
import { motion } from "framer-motion";
import { slideFromLeftVariants, slideFromLeftOnMountTransition, pageTitleTransition, pageTitleVariants, slideFromBottomVariants, slideFromBottomTransition, slideFromRightVariants, slideFromRightTransition, slideFromTopVariants, slideFromTopTransition, viewportOnce, cardInViewTransition, cardInViewVariants } from "../../../../utils/pageMotionVariants";

export default function User() {
    const { id } = useParams();
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const [formEdit, setFormEdit] = useState<boolean>(false);
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const navigate = useNavigate();
    const [videosWatched, setVideosWatched] = useState(0);
    const [videosCount, setVideosCount] = useState(0);
    const [workshopsInscribed, setWorkshopsInscribed] = useState(0);
    const [workshopsParticipated, setWorkshopsParticipated] = useState<Workshop[]>([]);

    useEffect(() => {
        getUser();
    }, [id]);

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

            const data = await response.json();

            if (response.ok) {
                setUser(data.data);
                setVideosWatched(data.videosWatched);
                setVideosCount(data.videosCount);
                setWorkshopsInscribed(data.workshopsInscribed);
                setWorkshopsParticipated(data.workshopsParticipated as Workshop[]);
            } else {
                setError(data as ApiErrorResponse);
                setUser(null);
            }
        } catch (error) {
            setError(error as ApiErrorResponse);
            setUser(null);
        } finally {
            setLoading(false);
        }
    }

    async function destroy(id: number) {
        const response = await fetch(`${API_URL}/api/edit-user/${id}`, {
            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 as string,
                icon: 'success',
                showConfirmButton: true,
                showCloseButton: true,
                allowOutsideClick: false,
                confirmButtonText: 'Voltar',
                confirmButtonColor: 'var(--primary-color)',
            }).then(() => {
                navigate('/admin/users');
            });
        } else {
            Swal.fire({
                title: data.message,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
        }
    }

    function handleDeleteUser() {
        Swal.fire({
            text: 'Tem a certeza que deseja apagar este utilizador?',
            showCancelButton: true,
            confirmButtonText: 'Sim, apagar',
            confirmButtonColor: 'var(--primary-color)',
            cancelButtonText: 'Cancelar',
        }).then((result) => {
            if (result.isConfirmed) {
                destroy(user?.id as number);
            }
        });
    }

    async function update(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);
        const user_id = formData.get("user_id");
        const name = formData.get("name");
        const email = formData.get("email");
        const role_id = formData.get("role_id");

        const payload = {
            user_id: user_id,
            name: name,
            email: email,
            role_id: role_id,
        };

        const response = await fetch(`${API_URL}/api/edit-user/${id}`, {
            method: "PATCH",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
            body: JSON.stringify(payload),
        });

        const data = await response.json();

        if (response.ok) {
            setUser(data.data);
            setFormEdit(false);
            Swal.fire({
                title: data.message as string,
                icon: 'success',
                showConfirmButton: false,
                showCloseButton: true,
            });
            getUser();
        } else {
            Swal.fire({
                title: data.message,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
        }
    }

    if (loading) {
        return (
            <div className="text-center">
                <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} />
            </div>
        )
    }

    return (
        <div className={`${styles.container} p-1 p-xl-0`}>
            <motion.div variants={slideFromLeftVariants} initial="initial" animate="animate" transition={slideFromLeftOnMountTransition} className={"text-start mt-5"}>
                <button className={`${styles.button} border-0 bg-transparent fs-5`}><Link className={`${styles.link} text-decoration-none`} to="/admin/users"><LuArrowLeft className={`${styles.LinkIcon} mb-1 fs-4 align-items-center`} /> <span className={styles.linkText}>Utilizadores</span> </Link></button>
            </motion.div>


            {user ? (
                <div className="my-3">
                    <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={styles.title}>Dados do Utilizador </motion.h1>

                    <div className="row mt-5 justify-content-between px-2">
                        <motion.div variants={slideFromLeftVariants} initial="initial" animate="animate" transition={slideFromLeftOnMountTransition} className="col-12 col-lg-8 p-2 rounded-3">
                            <div className={`${styles.userCard} d-flex flex-column flex-md-row g-5 p-4 bg-white h-100`}>
                                <div className="col-12 col-md-6 d-flex flex-column text-start flex-column mt-xl-0">
                                    <span className={`badge text-uppercase bg-primary fw-bold px-4 py-3 fs-6 mb-3 d-flex d-md-none align-self-center ${user.role_id === 1 ? 'bg-primary bg-gradient text-white' : 'bg-secondary bg-gradient text-white'} `} style={{ width: "fit-content" }}>{user.role_id === 1 ? "Administrador" : "Utilizador"}</span>
                                    <span className="fw-bold fs-4">{user.name}</span>
                                    <span className="fs-5 flex-grow-1">{user.email}</span>

                                    <div className="d-flex flex-column">
                                        <span className="d-flex justify-content-start text-black text-muted flex-wrap flex-sm-nowrap fs-6 fw-medium mt-4 py-0" style={{ maxWidth: "275px" }}>Membro desde: <b className="fw-bold fs-6">{new Date(user.created_at).toLocaleDateString('pt-PT')}</b></span>
                                        <span className="d-flex justify-content-start text-black text-muted flex-wrap flex-sm-nowrap fs-6 fw-medium py-0" style={{ maxWidth: "275px" }}>Última actualização: <b className="fw-bold fs-6">{new Date(user.updated_at).toLocaleDateString('pt-PT')}</b></span>
                                    </div>
                                </div>
                                <div className="col-12 col-md-6 d-flex flex-column gap-2 text-end align-items-start align-items-md-end mt-0 justify-content-between mx-auto mx-md-0">
                                    <span className={`badge text-uppercase d-none d-md-flex fw-bold px-4 py-3 fs-6 mt-0 ${user.role_id === 1 ? 'bg-primary bg-gradient text-white' : 'bg-secondary bg-gradient text-white'}`} style={{ width: "fit-content" }}>{user.role_id === 1 ? "Administrador" : "Utilizador"}</span>

                                    <div className="buttonsContainer mt-4 mt-md-5 d-flex gap-2 justify-content-center mx-auto mx-md-0 flex-wrap" >
                                        <a className={`${styles.updateButton} text-decoration-none text-primary`} onClick={() => { setFormEdit(true); }}> Editar <LuPencil className={`${styles.icon} mb-1 text-primary`} /></a>
                                        <a className={`${styles.deleteButton} text-decoration-none text-danger`} onClick={() => handleDeleteUser()}>Apagar <LuTrash2 className={`${styles.icon} mb-1 text-danger`} /></a>
                                    </div>
                                </div>
                            </div>
                        </motion.div>
                        <motion.div variants={slideFromRightVariants} initial="initial" animate="animate" transition={slideFromRightTransition} className="col-12 col-lg-4 p-2">
                            <div className={`${styles.userVideosWatched} text-start d-flex flex-column h-100 gap-3 p-4`}>
                                <div className="d-flex flex-column">
                                    <span className="fw-normal fs-6" style={{ color: "var(--bg-primary-color-opacity)" }}>Vídeos assistidos</span>
                                    <span className="fs-2 fw-bold text-white">{videosWatched}/{videosCount}</span>
                                </div>

                                <div className="d-flex flex-column">
                                    <span className="fw-normal fs-6" style={{ color: "var(--bg-grey)" }}>Workshops inscrito</span>
                                    <span className="fs-2 fw-bold text-white">{workshopsInscribed}</span>
                                </div>

                            </div>
                        </motion.div>

                        <motion.div className="mt-3">
                        {formEdit ? (
                            <motion.div variants={slideFromTopVariants} initial="initial" animate="animate" transition={slideFromTopTransition} className="my-3">
                                <span className={styles.title}>Editar Utilizador</span>

                                <form method="patch" onSubmit={update} id="formEditUser">
                                    <div className="row g-3 mt-2">
                                        <input type="hidden" name="user_id" value={user?.id} />
                                        <div className="col-12 col-md-6 text-start">
                                            <label className="form-label fw-bold" htmlFor="name">Nome</label>
                                            <input type="text" className="form-control py-2" id="name" name="name" defaultValue={user?.name} />
                                        </div>
                                        <div className="col-12 col-md-6 text-start">
                                            <label className="form-label fw-bold" htmlFor="email">Email</label>
                                            <input type="email" className="form-control py-2" id="email" name="email" defaultValue={user?.email} />
                                        </div>
                                        <div className="col-12 col-md-6 text-start">
                                            <label className="form-label fw-bold" htmlFor="role_id">Cargo</label>
                                            <select className="form-select py-2" id="role_id" name="role_id" defaultValue={user?.role_id}>
                                                <option value="1">Administrador</option>
                                                <option value="2">Utilizador</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div className="buttonsContainer mt-4 d-flex gap-2 justify-content-center" >
                                        <button type="button" className={`${styles.closeFormButton}`} onClick={() => setFormEdit(false)}> Cancelar <LuX className={`${styles.icon} mb-1`} /></button>
                                        <button type="submit" className={`${styles.submitFormButton}`} >Submeter dados <LuCheck className="mb-1" /></button>
                                    </div>
                                </form>
                            </motion.div>
                        ) : null}
                    </motion.div>

                        <motion.div variants={slideFromBottomVariants} initial="initial" animate="animate" transition={slideFromBottomTransition} className="col-12 p-2 mt-4 mb-3">
                            <span className={`${styles.subtitle} text-start`}>Workshops inscrito</span>
                        </motion.div>
                        {workshopsParticipated.length > 0 ? (
                            workshopsParticipated.map((workshop) => (
                                <div key={workshop.id} className="col-12 col-sm-6 col-lg-4 p-2">
                                    <motion.div variants={cardInViewVariants} initial="initial" whileInView="animate" viewport={viewportOnce} transition={cardInViewTransition} 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}
                                            />
                                            <span className={`${styles.workshopStatus} position-absolute top-0 end-0 m-2 badge ${workshop.status === "pending" ? "bg-warning text-dark" : workshop.status === "realized" ? "bg-success" : "bg-danger"}`}>
                                                {workshop.status === "pending" ? "Pendente" : workshop.status === "realized" ? "Realizado" : "Cancelado"}
                                            </span>
                                            <div className="position-absolute w-100 bottom-0 justify-content-evenly d-none d-md-flex mb-2 px-2">
                                                <p className={`${styles.dateWorkshop} mb-0`}><LuCalendar className={`${styles.icon} mb-1 me-2`} />{workshop.date.split("-").reverse().join("-")}</p>
                                                <p className={`${styles.timeWorkshop} mb-0`}><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="d-flex flex-column d-md-none mt-2">
                                                <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)} - {workshop.time_end.slice(0, 5)}</span>
                                            </div>
                                        </div>
                                        <div className="px-3 mt-3">
                                            <Link to={`/admin/edit-workshop/${workshop.id}`} className={`${styles.linkWorkshop} d-block text-center py-2 px-4 text-decoration-none`}>
                                                Ver detalhes
                                            </Link>
                                        </div>
                                    </motion.div>
                                </div>
                            ))
                        ) : (
                            <motion.div variants={slideFromBottomVariants} whileInView="animate" viewport={viewportOnce} transition={slideFromBottomTransition} className="col-12 text-center ps-1">
                                <span className="text-muted fs-5">Este utilizador ainda não participou em nenhum workshop</span>
                            </motion.div>
                        )}
                    </div>


                </div>
            ) : (
                <div className="text-center alert alert-danger mt-5 align-items-center">
                    <span>{error?.message}</span>
                </div>
            )}


        </div>

    )
}