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

export default function Home() {
    const [user, setUser] = useState<User>();
    const [channels, setChannels] = useState<Channels>();
    const [messages , setMessages] = useState<Messages>();

    useEffect(() => {
        const token = localStorage.getItem("token")
        if (token) {
            axios
                .post("/api/auth/me", {
                    token: token
                })
                .then((res) => {
                    setUser(res.data)
                })
                .catch((err) => {
                    console.error(err)
                })
            } 

        axios
            .get("/api/channels").then((res) => {
                setChannels(res.data)
            })
            .catch((err) => {
                console.error(err)
            })
        
        axios
            .get("/api/lastmessages").then((res) => {
                setMessages(res.data)
            }
        )
    }, [])

    return (
        <div>
            <h1>Home</h1>
            {user ? (
                <div>
                    <p>Welcome {user.username}</p>
                    <button onClick={() => {
                        localStorage.removeItem("token")
                        window.location.reload()
                    }}>Logout</button>
                    <Link to="/create-channel">Create Channel</Link>
                </div>
            ) : (
                <div>
                    <Link to="/login">Login</Link>
                    <Link to="/register">Register</Link>
                </div>
            )}
            <h2>Channels</h2>
            <ul>
                {channels?.map((channel) => (
                    <li key={channel.id}>
                        <Link to={`/c/${channel.name}`}>{channel.name}</Link>
                    </li>
                ))}
            </ul>
            <h2>Last messages</h2>
            <ul>
                {messages?.map((message) => (
                    <li key={message.id}>
                        <p><Link to={`/u/${message.username}`}>{message.username}</Link>: {message.content}</p>
                        <p>In <Link to={`/c/${message.channel_name}`}>{message.channel_name}</Link></p>
                        <p>{new Date(message.date * 1000).toLocaleString()}</p>
                    </li>
                ))}
            </ul>
            <img src="cat.jpg" alt="cat" className="cat"/>
        </div>
    )
}