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

import "../styles/Home.css"

export default function Home({socket}: {socket: WebSocket}) {
    const [user, setUser] = useState<User>();
    const [channels, setChannels] = useState<RecentChannels>();
    const [messages , setMessages] = useState<Messages>();
    const [searchedChannels, setSearchedChannels] = useState<Channels>([]);
    const [newChannels, setNewChannels] = useState<Channels>([]);
    const [search, setSearch] = useState<string>("");

    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.response)
                })
        } 

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

        axios
            .get("/api/newchannels")
            .then((res) => {
                setNewChannels(res.data)
            })
            .catch((err) => {
                console.error(err.response)
            })
    }, [])

    useEffect(() => {
        socket.addEventListener('message', function (event) 
        {
            const data = JSON.parse(event.data);
            if (data.type === "new_message" || data.type === "delete_message" || data.type === "purge_channel") {
                axios
                    .get("/api/lastmessages")
                    .then((res) => {
                        setMessages(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })

                axios
                    .get("/api/activechannels")
                    .then((res) => {
                        setChannels(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })
            } else if (data.type === "new_channel") {
                axios
                    .get("/api/activechannels")
                    .then((res) => {
                        setChannels(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })

                axios
                    .get("/api/newchannels")
                    .then((res) => {
                        setNewChannels(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })
            } else if (data.type === "delete_channel") {
                axios
                    .get("/api/activechannels")
                    .then((res) => {
                        setChannels(res.data)
                    })
                    .catch((err) => {
                        console.error(err.response)
                    })

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

    useEffect(() => {
        if (!search) {
            setSearchedChannels([])
            return
        }
        axios
            .get(`/api/searchchannels?search=${search}`).then((res) => {
                setSearchedChannels(res.data)
            }
            ).catch((err) => {
                console.error(err.response)
            })
    }, [search])

    return (
        <div className="home">
            <TopBar user={user} />
            <div className="forum-section home-header">
                <div className="home-header-text">
                    <h2>Welcome to Tanuki's forum !</h2>
                    <p>
                        I don't know what to say, but I hope you will enjoy your stay here.
                    </p>
                </div>
                <img src="osaka_arch.png" alt="osaka" className="osaka"/>
            </div>
            <div className="main-content">
                <div className="forum-section messages">
                    <h2>Last messages</h2>
                    <div className="messages-list">
                        {messages?.map((message) => (
                            <MessageComponent
                                key={message.id}
                                message={message}
                                user={user}
                                channel={undefined}
                            />
                        ))}
                    </div>
                </div>
                <div className="forum-section channels">
                    <h2>Channels</h2>
                    <div className="channels-content">
                        <Link to={'/channels'}>All channels</Link>
                        {user && (
                            <Link to={'/create-channel'}>Create channel</Link>
                        )}
                        <div className="channels-recent">
                            <h3>Recent active channels</h3>
                            <ul>
                                {channels?.map((channel) => (
                                    <li key={channel.id}>
                                        <Link to={`/c/${channel.name}`}>{channel.name}</Link>
                                    </li>
                                ))}
                            </ul>
                        </div>
                        <div className="channels-new">
                            <h3>Last created channels</h3>
                            <ul>
                                {newChannels?.map((channel) => (
                                    <li key={channel.id}>
                                        <Link to={`/c/${channel.name}`}>{channel.name}</Link>
                                    </li>
                                ))}
                            </ul>
                        </div>
                        <div className="channels-search">   
                            <h3>Search channels</h3>
                            <input
                                type="text"
                                placeholder="Search channels"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                            <ul>
                                {searchedChannels?.map((channel) => (
                                    <li key={channel.id}>
                                        <Link to={`/c/${channel.name}`}>{channel.name}</Link>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}