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

export default function UsersPage({socket}: {socket: WebSocket}) {
    const [users, setUsers] = useState<Users>();
    const [search, setSearch] = useState<string>("");
    const [token, setToken] = useState<string>("");
    const [thisUser, setThisUser] = useState<User>();

    function deleteUser(username: string) {
        if (!window.confirm(`Are you sure you want to delete ${username}?`)) {
            return;
        }
        axios
            .post(`/api/users/${username}/delete`, { token })
            .catch((err) => {
                console.error(err.response);
            });
    }

    useEffect(() => {
        const token = localStorage.getItem("token")

        if (token) {
            setToken(token)
            axios
                .post("/api/auth/me", {
                    token: token
                })
                .then((res) => {
                    setThisUser(res.data)
                })
        }
        axios
            .get("/api/users")
            .then((res) => {
                setUsers(res.data)
            })
            .catch((err) => {
                console.error(err.response)
            })
    }, [])

    useEffect(() => {
        socket.addEventListener('message', function (event) {
            const data = JSON.parse(event.data);
            if (data.type === "new_user" || data.type === "delete_user") {
                axios
                    .get("/api/users")
                    .then((res) => {
                        setUsers(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })
            }
        });
    }, [])

    if (!users) {
        return (
            <div className="forum-page">
                <TopBar user={thisUser} />
                <div className="forum-section">
                    <h2>Users</h2>
                    <p>Loading...</p>
                </div>
            </div>
        )
    }

    return (
        <div className="forum-page">
            <TopBar user={thisUser} />
            <div className="forum-section">
                <h2>Users</h2>
                <input
                    type="text"
                    placeholder="Search users"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                />
                <ul>
                    {users?.sort().filter((channel) => channel.username.toLowerCase().includes(search.toLowerCase())).map((user) => (
                        <li key={user.id}>
                            <Link to={`/u/${user.username}`}>{user.username}</Link>
                            {thisUser?.admin == 1 && (
                                <button onClick={() => deleteUser(user.username)}> 
                                    Delete
                                </button>
                            )}
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    )
}