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

import "../styles/UserPage.css";

export default function UserPage({socket}: {socket: WebSocket}) {
    const { username } = useParams();
    const [pageUser, setPageUser] = useState<User>();
    const [messages, setMessages] = useState<Messages>();
    const [user, setUser] = useState<User>();

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

        if (localToken) {
            axios
                .post("/api/auth/me", { token: localToken }).then((res) => {
                    setUser(res.data);
                });
        }
    }, []);

    useEffect(() => {
        axios
            .get(`/api/users/${username}`)
            .then((res) => {
                setPageUser(res.data);
            })
            .catch((err) => {
                console.error(err.response);
            });

        axios
            .get(`/api/users/${username}/lastmessages`)
            .then((res) => {
                setMessages(res.data);
            })
            .catch((err) => {
                console.error(err.response);
            });
    }, [username]);

    useEffect(() => {
        socket.addEventListener('message', function (event) {
            const data = JSON.parse(event.data);
            if (((data.type === "new_message" || data.type === "delete_message") && data.user_id === pageUser?.id) || data.type === "purge_channel" || data.type === "delete_channel") {
                axios
                    .get(`/api/users/${username}/lastmessages`)
                    .then((res) => {
                        setMessages(res.data);
                    })
                    .catch((err) => {
                        console.error(err.response);
                    });
            }
        });
    }, [pageUser]);

    if (!pageUser) {
        return (
            <div className="user-page">
                <TopBar user={user} />
                <div className="user">
                    <h2>Loading...</h2>
                </div>
            </div>
        )
    }

    return (
        <div className="user-page">
            <TopBar user={user} />
            <div className="user">
            <h2>{pageUser.username}</h2>
                {pageUser.admin ? <p>Admin</p> : <p>User</p>}
            </div>
            <div className="user-messages">
                <h2>Last messages</h2>
                <div className="messages-list">
                    {messages?.map((message) => (
                        <MessageComponent
                            key={message.id}
                            message={message}
                            user={pageUser}
                            channel={undefined}
                            deleteMessage={undefined}
                        />
                    ))}
                </div>
            </div>
        </div>
    );
}