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

export default function ChannelsPage({socket}: {socket: WebSocket}) {
    const [channels, setChannels] = useState<Channels>();
    const [search, setSearch] = useState<string>("");
    const [token, setToken] = useState<string>("");
    const [user, setUser] = useState<User>();

    function deleteChannel(name: string) {
        if (!window.confirm(`Are you sure you want to delete ${name}?`)) {
            return;
        }
        axios
            .post(`/api/channels/${name}/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) => {
                    setUser(res.data)
                })
        }
        axios
            .get("/api/channels")
            .then((res) => {
                setChannels(res.data)
            })
            .catch((err) => {
                console.error(err.response)
            })
    }, [])

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

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

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