import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { User } from "../types";
import axios from "axios";
import TopBar from "../components/TopBar";

export default function CreateEmoji() {
    const navigate = useNavigate();
    const [name, setName] = useState("");
    const [token, setToken] = useState<string>("");
    const [user , setUser] = useState<User>();

    useEffect(() => {
        const localToken = localStorage.getItem("token");
        if (localToken) {
            setToken(localToken)

            axios
                .post("/api/auth/me", { token: localToken })
                .then((res) => {
                    setUser(res.data);
                });
        }
    }, []);

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();

        const formData = new FormData();
        const fileInput = document.getElementById("emoji") as HTMLInputElement;
        if (fileInput.files) {
            formData.append("emoji", fileInput.files[0]);
        }
        formData.append("token", token);
        formData.append("name", name);
        axios
            .post("/api/emojis/add", formData, { 
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            })
            .then(() => {
                navigate("/emojis");
            })
            .catch((err) => {
                console.error(err.response.data);
            });
    }

    return (
        <div className="forum-page">
            <TopBar user={user}/>
            <div className="forum-section">
                <h1>Create Emoji</h1>
                <form onSubmit={handleSubmit}>
                    <p>
                        {!/^[a-zA-Z0-9-_]+$/.test(name) && name.length != 0 && (
                            <span>Emoji name can only contain letters, numbers, - and _</span>
                        )}
                    </p>
                    <input
                        type="text"
                        placeholder="Name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                    />
                    <input type="file" name="emoji" id="emoji" accept="image/*"/>
                    <button type="submit" disabled={!/^[a-zA-Z0-9-_]+$/.test(name)}>
                        Create
                    </button>
                </form>
            </div>
        </div>
    );
}