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 CreateChannel() {
    const navigate = useNavigate();
    const [name, setName] = useState("");
    const [description, setDescription] = 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();
        axios
            .post("/api/channels/add", { name, description, token })
            .then(() => {
                navigate(`/c/${name}`);
            })
            .catch((err) => {
                console.error(err.response.data.message);
            });
    }

    return (
        <div className="forum-page">
            <TopBar user={user}/>
            <div className="forum-section">
                <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>
        </div>
    );
}