import { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";


export default function CreateChannel() {
    const navigate = useNavigate();
    const [name, setName] = useState("");
    const [description, setDescription] = useState("");
    const [token, setToken] = useState<string>("");

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

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        axios
            .post("/api/channels/add", { name, description, token })
            .then(() => {
                navigate("/");
            })
            .catch((err) => {
                console.error(err.response.data.message);
            });
    }

    return (
        <div>
            <Link to="/">Home</Link>
            <h1>Create Channel</h1>
            <form onSubmit={handleSubmit}>
                <p>
                    {!/^[a-zA-Z0-9-_]+$/.test(name) && name.length != 0 && (
                        <span>Channel name can only contain letters, numbers, - and _</span>
                    )}
                </p>
                <input
                    type="text"
                    placeholder="Name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                />
                <input
                    type="text"
                    placeholder="Description"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                />
                <button type="submit" disabled={!/^[a-zA-Z0-9-_]+$/.test(name)}>
                    Create
                </button>
            </form>
        </div>
    );
}