import API_URL from "../../../../config/api";
import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router";
import type { ApiErrorResponse, Category, Video } from "../../../../types";
import styles from "./styles.module.css";
import { CgSpinner } from "react-icons/cg";
import { LuUpload, LuPlus, LuCheck, LuTrash2, LuArrowLeft } from "react-icons/lu";
import Swal from "sweetalert2";
import { slideFromLeftVariants, slideFromLeftOnMountTransition, pageTitleTransition, pageTitleVariants, slideFromBottomVariants, slideFromBottomTransition } from "../../../../utils/pageMotionVariants";
import { motion } from "framer-motion";

export default function editVideo() {
    const { id } = useParams();
    const [video, setVideo] = useState<Video | null>(null);
    const [loading, setLoading] = useState(true);
    const [categories, setCategories] = useState<Category[]>([]);
    const [category_ids, setCategoryIds] = useState<string[]>([]);
    const [thumbnailFile, setThumbnailFile] = useState<File | null>(null);
    const [isActive, setIsActive] = useState<boolean>();
    const [order, setOrder] = useState<number>();
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const navigate = useNavigate();

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

    useEffect(() => {
        if (!video) return;
        console.log(video);
        setCategoryIds(video.categories?.map((category) => category.id.toString()) ?? []);
        setIsActive(Boolean(video.is_active));
        setOrder(video.order);
    }, [video]);

    async function getVideo() {
        setLoading(true);

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

            const data = await response.json();

            if (response.ok) {
                setVideo(data.data);
            } else {
                setError(data as ApiErrorResponse);
                setVideo(null);
            }
        } catch {
            setError(error as ApiErrorResponse);
            setVideo(null);
        } finally {
            setLoading(false);
        }
    }

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

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

    async function update(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);

        // Garante categorias atualizadas via state (checkboxes controladas)
        formData.delete("category_ids[]");
        category_ids.forEach((categoryId) => {
            formData.append("category_ids[]", categoryId);
        });
        // Mesmo que fique vazio, força o backend a sincronizar (sync([]) remove pivots antigas)
        formData.append("sync_categories", "1");

        // Mantém compatibilidade de upload de ficheiro com Laravel
        // quando a rota aceita PATCH (method spoofing)
        formData.append("_method", "PATCH");

        const response = await fetch(`${API_URL}/api/edit-video/${id}`, {
            method: "POST",
            headers: {
                Accept: "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
            body: formData,
        });

        const data = await response.json();

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

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

        const data = await response.json();

        if (response.ok) {
            setCategories(data.data);
        } else {
            setCategories([]);
        }
    }

    const handleCheckbox = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { value, checked } = e.target;
        setCategoryIds(prev =>
            checked ? [...prev, value] : prev.filter(id => id !== value)
        );
    };

    function handleCreateCategory(e: React.MouseEvent<HTMLButtonElement>) {
        e.preventDefault();
        Swal.fire({
            title: 'Criar nova categoria',
            input: 'text',
            inputPlaceholder: 'Categoria...',
            showCancelButton: true,
            confirmButtonText: 'Adicionar',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: 'var(--primary-color)',
            inputValidator: (value) => {
                if (!value) {
                    return 'Indique o nome da categoria!';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const categoryName = result.value;
                createCategory(categoryName);
            }
        });
    }

    async function createCategory(categoryName: string) {
        const response = await fetch(`${API_URL}/api/categories`, {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`
            },
            body: JSON.stringify({
                name: categoryName
            })
        });

        const data = await response.json();

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

    return (
        <>
            {loading ? (
                <div className="text-center mt-5 d-flex flex-column gap-2 align-items-center">
                    <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} />
                </div>
            ) : (
                <div className={`${styles.container} p-3 p-xl-0`}>
                    <motion.div variants={slideFromLeftVariants} initial="initial" animate="animate" transition={slideFromLeftOnMountTransition} className={"text-start"}>
                        <button className={`${styles.button} border-0 bg-transparent fs-5`}><Link className={`${styles.link} text-decoration-none`} to="/videos"><LuArrowLeft className={`${styles.LinkIcon} mb-1 fs-4 align-items-center`} /> <span className={styles.linkText}>Vídeos</span> </Link></button>
                    </motion.div>

                    {video ? (
                        <div className="my-3">
                            <div className="mt-5">
                                <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={styles.title}>Alterar dados do vídeo</motion.h1>
                                <motion.div variants={slideFromBottomVariants} initial="initial" animate="animate" transition={slideFromBottomTransition} className="row mx-auto g-4">
                                    <form method="patch" onSubmit={update}>
                                        <input type="hidden" name="video_id" value={video?.id} />
                                        <div className="col-12 px-1 text-start mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="title">Título</label>
                                            <input type="text" className="form-control py-2 text-truncate" id="title" name="title" defaultValue={video?.title} />
                                        </div>
                                        <div className="col-12 px-1 text-start mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="description">Descrição</label>
                                            <textarea rows={5} className="form-control py-2" id="description" name="description" defaultValue={video?.description} />
                                        </div>
                                        <div className="col-12 px-1 text-start mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="tags">Tags <small className="text-muted">(separar por vírgulas)</small></label>
                                            <input type="text" className="form-control py-2 text-truncate" id="tags" name="tags" defaultValue={video?.tags} />
                                        </div>
                                        <div className="col-12 px-1 text-start mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="thumbnail">Atualizar thumbnail</label>
                                            <div className="position-relative">
                                                <span className={`${styles.inputFiles} form-control py-2 position-absolute top-0 start-0 text-white px-3 w-100 text-decoration-none text-start fw-light fs-6 text-truncate`}><LuUpload className="mb-1 me-2" /> {thumbnailFile ? thumbnailFile.name : "Carregar nova imagem"} </span>
                                                <input type="file" className={`${styles.inputFiles} form-control py-2 text-truncate`} id="thumbnail" name="thumbnail" accept="image/*" style={{ width: '100%', height: '100%', cursor: 'pointer', zIndex: 1000, opacity: 0 }} onChange={(e) => setThumbnailFile(e.target.files?.[0] ?? null)} />
                                            </div>
                                        </div>
                                        <div className="col-12 col-sm-2 px-1 text-start mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="order">Ordem</label>
                                            <input type="number" className="form-control py-2 text-truncate" id="order" name="order" value={order ?? ''} onChange={(e) => setOrder(parseInt(e.target.value, 10))} />
                                        </div>
                                        <div className="col-12 px-1 text-start mb-3">
                                            <div className="d-flex">
                                                <label className={`${styles.label} form-label fw-bold align-content-center mb-0 me-2`} htmlFor="category_id">Categorias</label>
                                                <button className={`${styles.btnAdicionarCategoria}`} onClick={handleCreateCategory} title="Adicionar categoria"><LuPlus className="mb-1" /></button>
                                            </div>
                                            <div>
                                                {categories && categories.length > 0 ? (
                                                    categories.map((category) => (
                                                        <div key={category.id}>
                                                            <input type="checkbox" name="category_ids[]" id={`category_${category.id}`} value={category.id} className="me-2" checked={category_ids.includes(category.id.toString())} onChange={handleCheckbox} />
                                                            <label htmlFor={`category_${category.id}`} key={category.id}>{category.name}</label>
                                                        </div>))
                                                ) : (
                                                    <div>
                                                        <span>Nenhuma categoria encontrada</span>
                                                    </div>
                                                )}

                                                {/* <button className={`${styles.btnAdicionarVideo} btn  mt-5`}><LuPlus className="mb-1" /> Nova categoria</button> */}
                                            </div>
                                        </div>
                                        <div className="col-12 px-1 text-start d-flex flex-column mb-3">
                                            <label className={`${styles.label} form-label fw-bold`} htmlFor="tags">Estado</label>
                                            <div className="d-flex gap-4">
                                                <span>
                                                    <input
                                                        type="radio"
                                                        name="is_active"
                                                        id="is_active_true"
                                                        value="1"
                                                        checked={isActive === true}
                                                        onChange={() => setIsActive(true)}
                                                    />
                                                    <label className="ms-1" htmlFor="is_active_true">Ativo</label>
                                                </span>
                                                <span>
                                                    <input
                                                        type="radio"
                                                        name="is_active"
                                                        id="is_active_false"
                                                        value="0"
                                                        checked={isActive === false}
                                                        onChange={() => setIsActive(false)}
                                                    />
                                                    <label className="ms-1" htmlFor="is_active_false">Inativo</label>
                                                </span>
                                            </div>
                                        </div>

                                        <div className="buttonsContainer mt-5 d-flex gap-2 justify-content-center flex-wrap" >
                                            <button type="submit" className={`${styles.submitButton} bg-primary`}>Submeter Dados <LuCheck className="mb-1 text-white" /></button>
                                            <button type="button" className={`${styles.deleteButton}`} onClick={() => handleDeleteVideo()}>Apagar <LuTrash2 className="mb-1 text-white" /></button>
                                        </div>
                                    </form>
                                </motion.div>

                            </div>

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