import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "./UserProfile.css";

const UserProfile = () => {
    const navigate = useNavigate();
    const [token, setToken] = useState(localStorage.getItem("token"));
    const [email, setEmail] = useState(localStorage.getItem("email"));
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);

    useEffect(() => {
        if (!token) {
            navigate("/login");
        }
    }, [token, navigate]);

    const logout = () => {
        setToken(null);
        setEmail(null);
        localStorage.removeItem("token");
        localStorage.removeItem("email");
        navigate("/login");
    };

    if (!token) {
        return <div>No estás logueado</div>;
    }

    return (
        <div className="user-profile-wrapper">
            {/* Contenedor principal del perfil */}
            <div
                className="user-profile-container"
                onClick={() => setIsDropdownOpen(!isDropdownOpen)}
            >
                <div className="user-profile-img"></div>
                <div className="user-profile-content">
                    <p className="user-name">Oscar Vargas</p>
                    <p className="user-email">{email}</p>
                </div>
            </div>

            {/* Dropdown */}
            {isDropdownOpen && (
                <div className="user-dropdown">
                    <button onClick={logout} className="user-button-logout">
                        Cerrar sesión
                    </button>
                </div>
            )}
        </div>
    );
};

export default UserProfile;
