import {X} from "lucide-react";
import {useNavigate} from "react-router-dom";
import type {LoginResponse} from "../api/dtos/LoginResponse.ts";
import {getUserUrl} from "../routes.ts";
import Button from "./basics/Button.tsx";
import {ButtonType} from "./basics/BasicButtonDefinitions.ts";
import type {UserDto} from "../api/dtos/UserDto.ts";

/**
 * Overlay settings menu that displays current user info
 * and provides navigation to user management.
 */
type SettingsMenuProps = {
    onClose: () => void;
};

export function SettingsMenu({onClose}: SettingsMenuProps) {
    const navigate = useNavigate();
    const storedSession = localStorage.getItem("session");
    const loginData: LoginResponse | null = storedSession
        ? JSON.parse(storedSession)
        : null;
    const user = loginData?.userData;

    const formatUserName = (user: UserDto) => {
        const parts = [];
        if (user.firstName) parts.push(user.firstName);
        if (user.lastName) parts.push(user.lastName);
        return parts.length > 0 ? parts.join(" ") : user.userName;
    };

    return (
        <div className="fixed inset-0 bg-black/40 flex justify-end z-50">
            <div className="bg-white dark:bg-gray-800 w-80 p-6 shadow-xl flex flex-col">
                {/* Close button */}
                <button
                    onClick={onClose}
                    className="self-end text-gray-500 hover:text-gray-800"
                >
                    <X/>
                </button>

                <h2 className="text-xl font-semibold mb-4">Einstellungen</h2>

                {user ? (
                    <>
                        <p className="text-gray-800 dark:text-gray-100 font-medium">
                            {formatUserName(user)}
                        </p>
                        <p className="text-gray-600 dark:text-gray-400 text-sm mb-6">
                            {user.role === "admin" ? "Administrator" : "Benutzer"}
                        </p>

                        <Button
                            onClick={() => {
                                navigate(getUserUrl());
                                onClose();
                            }}
                            buttonType={ButtonType.PrimaryButton}
                            text={"Benutzerverwaltung"}
                        />
                    </>
                ) : (
                    <p className="text-gray-500">Nicht eingeloggt</p>
                )}
            </div>
        </div>
    );
}
