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

import "../styles/EmojisPage.css"

export default function EmojisPage({socket}: {socket: WebSocket}) {
    const [emojis, setEmojis] = useState<Emojis>();
    const [search, setSearch] = useState<string>("");
    const [token, setToken] = useState<string>("");
    const [user, setUser] = useState<User>();

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

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

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

    return (
        <div className="forum-page">
            <TopBar user={user} />
            <div className="forum-section">
                <h2>Emojis</h2>
                <Link to="/create-emoji">Create emoji</Link>
                <input
                    type="text"
                    placeholder="Search emojis"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                />
                <ul>
                    {emojis?.sort().filter((emoji) => emoji.name.toLowerCase().includes(search.toLowerCase())).map((emoji) => (
                        <li key={emoji.id}>
                            <img src={`/api/emojis/${emoji.name}`} alt={emoji.name} className="emoji" />
                            <span>:{emoji.name}:</span>
                            {user?.admin == 1 && (
                                <button onClick={() => deleteEmoji(emoji.name)}> 
                                    Delete
                                </button>
                            )}
                        </li>
                    ))}
                </ul>
            </div>
        </div>
    )
}