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

export default function CreateUser() {
    const [name, setName] = useState<string>("");
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [password_confirmation, setPasswordConfirmation] = useState<string>("");
    const [role_id, setRoleId] = useState("2");
    const [creating, setCreating] = useState(false);


    async function create() {
        //validação dos campos

        if (name.length < 3) {
            Swal.fire({
                title: "Nome deve ter pelo menos 3 caracteres",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        } else if (!email.includes('@')) {
            Swal.fire({
                title: "Email inválido",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        } else if (password !== password_confirmation) {
            Swal.fire({
                title: "As senhas não coincidem",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        } else if (password.length < 6) {
            Swal.fire({
                title: "Password deve ter pelo menos 6 caracteres",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        }

        if (role_id === "") {
            Swal.fire({
                title: "Cargo é obrigatório",
                icon: 'error',
                showConfirmButton: false,
                showCloseButton: true,
            });
            return;
        }

        setCreating(true);

        const payload = {
            name: name,
            email: email,
            password: password,
            password_confirmation: password_confirmation,
            role_id: role_id,
        };

        const response = await fetch(`${API_URL}/api/create-user`, {
            method: "POST",
            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) {
            setCreating(false);
            setName("");
            setEmail("");
            setPassword("");
            setPasswordConfirmation("");
            setRoleId("2");

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

    return (
        <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="/admin/users"><LuArrowLeft className={`${styles.LinkIcon} mb-1 fs-4 align-items-center`} /> <span className={styles.linkText}>Utilizadores</span> </Link></button>
            </motion.div>
            <motion.h1 variants={pageTitleVariants} initial="initial" animate="animate" transition={pageTitleTransition} className={styles.title}>Criar Utilizador</motion.h1>

            <div>
                <motion.div variants={slideFromBottomVariants} initial="initial" animate="animate" transition={slideFromBottomTransition} >
                    <div className="row g-3">
                        <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" value={name} onChange={(e) => setName(e.target.value)} />
                        </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" value={email} onChange={(e) => setEmail(e.target.value)} />
                        </div>
                        <div className="col-12 col-md-6 text-start">
                            <label className="form-label fw-bold" htmlFor="password">Password</label>
                            <input type="password" className="form-control py-2" value={password} onChange={(e) => setPassword(e.target.value)} />
                        </div>
                        <div className="col-12 col-md-6 text-start">
                            <label className="form-label fw-bold" htmlFor="password_confirmation">Confirme a Password</label>
                            <input type="password" className="form-control py-2" id="password_confirmation" name="password_confirmation" value={password_confirmation} onChange={(e) => setPasswordConfirmation(e.target.value)} />
                        </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" value={role_id} onChange={(e) => setRoleId(e.target.value)}>
                                <option value="2">Utilizador</option>
                                <option value="1">Administrador</option>
                            </select>
                        </div>
                    </div>

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