import { Link, useParams, useNavigate } 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 navigate = useNavigate();
    const { username } = useParams();
    const [pageUser, setPageUser] = useState<User>();
    const [messages, setMessages] = useState<Messages>();
    const [user, setUser] = useState<User>();
    const [noUser, setNoUser] = useState<boolean>(false);
    const [token, setToken] = useState<string>("");

    function deleteUser() {
        if (!window.confirm(`Are you sure you want to delete ${pageUser?.username}?`)) {
            return;
        }
        axios
            .post(`/api/users/${pageUser?.username}/delete`, { token })
            .then(() => {
                navigate("/");
            })
            .catch((err) => {
                console.error(err.response.data);
            });
    }

    function deleteUserPfp() {
        if (!window.confirm(`Are you sure you want to delete ${pageUser?.username}'s profile picture?`)) {
            return;
        }
        axios
            .post(`/api/users/${pageUser?.username}/deletepfp`, { token })
            .then(() => {
                window.location.reload();
            })
            .catch((err) => {
                console.error(err.response.data);
            });
    }

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

        if (localToken) {
            setToken(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) => {
                if (err.response.data.error === "No user found") {
                    setNoUser(true);
                }
                console.error(err.response.data);
            });

        axios
            .get(`/api/users/${username}/lastmessages`)
            .then((res) => {
                setMessages(res.data);
            })
            .catch((err) => {
                console.error(err.response.data);
            });
    }, [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 (noUser) {
        return (
            <div className="forum-page">
                <TopBar user={user} />
                <div className="forum-section">
                    <h2>User Not Found</h2>
                    <p>Sorry, the user you are looking for does not exist.</p>
                    <Link to="/">Go back to the homepage</Link>
                </div>
            </div>
        )
    }

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

    return (
        <div className="forum-page">
            <TopBar user={user} />
            <div className="forum-section">
                <div className="user-top">
                    <img src={`/api/users/${pageUser.username}/pfp`} alt="pfp" className="user-page-pfp" />
                    <h2>{pageUser.username}</h2>
                </div>
                {pageUser.admin ? <p>Admin</p> : <p>User</p>}
                {pageUser.id === user?.id && (
                    <Link to="/edit-profile">Edit profile</Link>
                )}
                {user?.admin == 1 && (
                    <div>
                        <button onClick={deleteUser}>    
                            Delete user
                        </button>
                        <button onClick={deleteUserPfp}>
                            Delete profile picture
                        </button>
                    </div>
                )}
            </div>
            <div className="forum-section">
                <h2>Last messages</h2>
                <div className="messages-list">
                    {messages?.map((message) => (
                        <MessageComponent
                            key={message.id}
                            message={message}
                            user={user}
                            channel={undefined}
                        />
                    ))}
                </div>
            </div>
        </div>
    );
}