import { useEffect, useState } from "react";
import { Link, useParams } from "react-router";
import { CgSpinner } from "react-icons/cg";
import type { ApiErrorResponse, User, Workshop } from "../../../types";
import { LuArrowLeft, LuCalendar, LuClock3, LuUsers } from "react-icons/lu";
import "react-datepicker/dist/react-datepicker.css";
import Swal from "sweetalert2";
import styles from "./styles.module.css";
import { imageSkeletonFadeStyle, onImageSkeletonLoad } from "../../../utils/imageSkeleton";

export default function Workshop() {
    const { id } = useParams();
    const [loading, setLoading] = useState(true);
    const [workshop, setWorkshop] = useState<Workshop | null>(null);
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const [role, setRole] = useState(0);
    const [userId, setUserId] = useState(0);

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

            const [workshopData] = await Promise.all([
                getWorkshop(),
            ]);

            setWorkshop(workshopData?.workshop as Workshop);
            setRole(workshopData?.role as number);
            setUserId(workshopData?.userId as number);

            setLoading(false);
        };

        fetchAll();
    }, []);

    async function getWorkshop() {
        try {
            const response = await fetch(`http://127.0.0.1:8000/api/workshop/${id}`, {
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${localStorage.getItem("token")}`
                },
            });

            const data = await response.json();

            if (response.ok) {
                return {
                    workshop: data.data as Workshop,
                    role: data.role as number,
                    userId: data.userId as number,
                };
            } else {
                setError(data as ApiErrorResponse);
                return null;
            }
        } catch (err) {
            setError({ message: "Erro de ligação" } as ApiErrorResponse);
            return null;
        }
    }

    /* Inscrever num workshop */
    async function inscrever(workshopId: number) {
        const response = await fetch(`http://127.0.0.1:8000/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 workshop = await getWorkshop();
            setWorkshop(workshop?.workshop as Workshop);
        } 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(`http://127.0.0.1:8000/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 workshop = await getWorkshop();
            setWorkshop(workshop?.workshop as Workshop);
        } 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`} />
                <span>A carregar dados do workshop...</span>
            </div>
        )
    }

    return (
        <div className={`${styles.container} p-3 p-xl-0`}>
            <div className={"text-start mb-3"}>
                <button className={`${styles.button} border-0 bg-transparent fs-5`}>
                    <Link className={`${styles.link} text-decoration-none`} to="/workshops">
                        <LuArrowLeft className={`${styles.LinkIcon} mb-1 fs-4 align-items-center`} /> <span className={styles.linkText}>Workshops</span>
                    </Link>
                </button>
            </div>

            {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>
            )}

            {workshop && (
                <>
                    <div className={`${styles.container} d-flex flex-column gap-2`}>
                        <div className="row mt-4 g-3 gx-md-4 gx-lg-5 ms-0">
                            <div className={`${styles.thumbnailWrapper} col-12 col-lg-3 align-self-center align-self-sm-center px-0 mt-0`}>
                                <img
                                    src={`http://127.0.0.1:8000/storage/${workshop.image}`}
                                    alt={workshop.title}
                                    className={`${styles.thumbnail} w-100`}
                                    style={imageSkeletonFadeStyle}
                                    onLoad={onImageSkeletonLoad}
                                />
                            </div>
                            <div className="col-12 col-lg-9 d-flex flex-column justify-content-between gap-2 mt-3 mt-lg-0">
                                <div className="d-flex flex-column flex-wrap  gap-1 justify-content-center justify-content-md-start">
                                    <h2 className={`${styles.title} text-start d-inline-block`}>{workshop.title}</h2>

                                    <p className={`${styles.description} text-start mb-3`}>{workshop.description}</p>

                                </div>
                                <div className="d-flex flex-wrap gap-1">
                                    <div className={`${styles.dateWorkshop} text-start d-inline-block px-3 py-2`}>
                                        <small className="d-block text-muted mb-1 me-2"><LuCalendar className={`${styles.iconCalendar} mb-1 me-2`} /> Dia</small>
                                        {workshop.date.split("-").reverse().join("-")}
                                    </div>

                                    <div className={`${styles.timeWorkshop} text-start d-inline-block px-3 py-2`}>
                                        <small className="d-block text-muted mb-1 me-2"><LuClock3 className={`${styles.iconClock} mb-1 me-2`} /> Hora</small>
                                        {workshop.time_start.slice(0, 5).split(":").join("h")} - {workshop.time_end.slice(0, 5).split(":").join("h")}
                                    </div>

                                    <div className={`${styles.timeWorkshop} text-start align-content-center d-inline-block px-3 py-2`}>
                                        <small className="d-block text-muted mb-1 me-2"><LuUsers className={`${styles.iconClock} mb-1 me-2`} /> Inscritos</small>
                                        <span className={`${styles.contagemUtilizadoresInscritos} fs-6 px-0`}>{workshop.users.length === 1 ? "1 utilizador" : `${workshop.users.length} utilizadores`} </span>
                                    </div>
                                </div>
                            </div>
                            {role !== 1 ? (
                                <div className="col-12 mx-auto ms-sm-0 mt-5 pt-3">
                                    {workshop.users.some((user: User) => user.id === userId) ? (
                                        <button type="button" className={`${styles.btncancelarInscricao} btn text-center mx-auto py-2  text-decoration-none`} onClick={() => cancelarInscricao(workshop.id)} key={workshop.id} style={{ width: '180px' }}>
                                            Anular inscrição
                                        </button>
                                    ) : (
                                        <button type="button" className={`${styles.btnInscrever} btn text-center mx-auto py-2 px-4 text-decoration-none`} onClick={() => inscrever(workshop.id)} key={workshop.id} style={{ width: '180px' }}>
                                            Inscrever-me
                                        </button>
                                    )}
                                </div>
                            ) : null}


                        </div>
                    </div>
                </>
            )}
        </div>
    );
}