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"

import "../styles/ChannelsPage.css"

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

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

        if (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(() => {
        const id = setInterval(() => {
            axios
                .get("/api/channels").then((res) => {
                    setChannels(res.data)
                }
            )
        }, 2000)

        return () => { clearInterval(id) }
    }, [])

    return (
        <div className="channels-page">
            <TopBar user={user} />
            <div className="channels-page-channels">
                <h2>Channels</h2>
                <input
                    type="text"
                    placeholder="Search channels"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                />
                <ul>
                    {channels?.filter((channel) => channel.name.toLowerCase().includes(search.toLowerCase())).map((channel) => (
                        <li key={channel.id}>
                            <Link to={`/c/${channel.name}`}>{channel.name}</Link>
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    )
}