import API_URL from "../../../../config/api";
import { useState } from "react";
import { Link } from "react-router";
import styles from "./styles.module.css";
import { LuArrowLeft, LuPlus, LuUpload } from "react-icons/lu";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { pt } from "date-fns/locale";
import { CgSpinner } from "react-icons/cg";
import Swal from "sweetalert2";
import { motion } from "framer-motion";
import {
    pageTitleTransition,
    pageTitleVariants,
    slideFromBottomTransition,
    slideFromBottomVariants,
    slideFromLeftOnMountTransition,
    slideFromLeftVariants,
} from "../../../../utils/pageMotionVariants";

export default function CreateWorkshop() {
    const [title, setTitle] = useState<string>("");
    const [description, setDescription] = useState<string>("");
    const [image, setImage] = useState<File | null>(null);
    const [date, setDate] = useState<Date | null>(null);
    const [time_start, setTimeStart] = useState<Date | null>(null);
    const [time_end, setTimeEnd] = useState<Date | null>(null);

    const [isLoading, setIsLoading] = useState(false);
    const [creating, setCreating] = useState(false);

    //função para formatar a data para o formato Local
    function formatDateLocalISO(d: Date) {
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, "0");
        const dd = String(d.getDate()).padStart(2, "0");
        return `${yyyy}-${mm}-${dd}`;
    }

    async function createWorkshop() {

        if (!title || !description || !image || !date || !time_start || !time_end) {
            Swal.fire({
                title: "Todos os campos são obrigatórios",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        }
        
        setCreating(true);

        const formData = new FormData();

        formData.append("title", title);
        formData.append("description", description);
        formData.append("image", image as File);
        formData.append("date", formatDateLocalISO(date));
        formData.append("time_start", time_start.toTimeString().slice(0, 5));
        formData.append("time_end", time_end.toTimeString().slice(0, 5));

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

        setIsLoading(true);

        const data = await response.json();

        if (response.ok) {
            setTitle("");
            setDescription("");
            setImage(null);
            setDate(null);
            setTimeStart(null);
            setTimeEnd(null);
            setIsLoading(false);
            Swal.fire({
                title: data.message as string,
                icon: 'success',
                showConfirmButton: false,
                showCloseButton: true,
            });
            setCreating(false);
        } else {
            Swal.fire({
                title: data.message as string,
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            setCreating(false);
        }
    }

    return (
        <div className={`${styles.container} p-3 p-xl-0 px-2 px-md-5`}>
            <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="/workshops"><LuArrowLeft className={`${styles.LinkIcon} mb-1 fs-4 align-items-center`} /> <span className={styles.linkText}>Workshops</span> </Link></button>
            </motion.div>
            <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={styles.title}>Adicionar Workshop</motion.h1>
            <div>
                <motion.div variants={slideFromBottomVariants} initial="initial" animate="animate" transition={slideFromBottomTransition}>
            <div className="row mx-auto g-4">
                <div className="col-12 px-1 text-start">
                    <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" placeholder="Insira o título do workshop" value={title} onChange={(e) => setTitle(e.target.value)} required />
                </div>
                <div className="col-12 px-1 text-start">
                    <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" placeholder="Insira uma descrição para o workshop" value={description} onChange={(e) => setDescription(e.target.value)} />
                </div>
                <div className="col-12 px-1 text-start">
                    <label className={`${styles.label} form-label fw-bold`} htmlFor="image">Adicionar imagem</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" /> {image ? image.name : "Carregar imagem do workshop"} </span>
                        <input type="file" className={`${styles.inputFiles} form-control py-2 text-truncate`} id="image" name="image" accept="image/*" style={{ width: '100%', height: '100%', cursor: 'pointer', zIndex: 1000, opacity: 0 }} onChange={(e) => setImage(e.target.files?.[0] ?? null)} />
                    </div>
                </div>
                <div className="col-12 col-sm-4 px-1 text-start d-flex flex-column">
                    <label className={`${styles.label} form-label fw-bold mb-2`} htmlFor="date">Data</label>
                    <DatePicker
                        selected={date}
                        onChange={(d: Date | null) => setDate(d)}
                        dateFormat="dd/MM/yyyy"
                        locale={pt}
                        className="form-control py-2"
                        placeholderText="Seleciona a data"
                        id="date"
                    />
                </div>
                <div className="col-12 col-sm-4 px-1 text-start d-flex flex-column">
                    <label className={`${styles.label} form-label fw-bold`} htmlFor="time_start">Hora de início</label>
                    <DatePicker
                        selected={time_start}
                        onChange={(t: Date | null) => setTimeStart(t)}
                        showTimeSelect
                        showTimeSelectOnly
                        timeIntervals={10}
                        timeFormat="HH:mm"
                        dateFormat="HH:mm"
                        locale={pt}
                        className="form-control py-2"
                        placeholderText="Hora de início"
                        id="time_start"
                        minTime={time_end
                            ? new Date(new Date(time_end).getTime() - 30 * 60 * 1000)
                            : new Date(new Date().setHours(9, 0, 0, 0))
                        }
                        maxTime={new Date(new Date().setHours(23, 59, 59, 999))}
                    />
                </div>
                <div className="col-12 col-sm-4 px-1 text-start d-flex flex-column">
                    <label className={`${styles.label} form-label fw-bold`} htmlFor="time_end">Hora de término</label>
                    <DatePicker
                        selected={time_end}
                        onChange={(t: Date | null) => setTimeEnd(t)}
                        showTimeSelect
                        showTimeSelectOnly
                        timeIntervals={10}
                        timeFormat="HH:mm"
                        dateFormat="HH:mm"
                        locale={pt}
                        className="form-control py-2"
                        placeholderText="Hora de término"
                        id="time_end"
                        minTime={time_start
                            ? new Date(new Date(time_start).getTime() + 30 * 60 * 1000)
                            : new Date(new Date().setHours(23, 59, 59, 999))
                        }
                        maxTime={new Date(new Date().setHours(23, 59, 59, 999))}
                    />
                </div>
            </div>

            <div className="buttonsContainer mt-4 d-flex gap-2 justify-content-center" >
                <button type="submit" onClick={createWorkshop} className={`${styles.btnAdicionarWorkshop}`} disabled={isLoading}><LuPlus className="mb-1 text-white" /> {creating ? <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} /> : "Adicionar Workshop"}</button>
            </div>
                </motion.div>
            </div>
        </div>
    )
}