import { useContext } from 'react';
import { Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import { lastPathPart } from '../../utils/StringUtils.js';

import './Header.css';
import { UserContext } from '../../context/UserContext.jsx';
import { clearSession } from '../../utils/session.js';

export default function Header() {
    const navigate = useNavigate();
    const { user, setUser } = useContext(UserContext);

    function handleLogout() {
        clearSession();
        setUser(null);
        navigate('/login');
    }

    const path = window.location.pathname;
    const showBackButton = !!user
        && '/' !== path
        && '/login' !== path
        && 'home' !== lastPathPart(window.location.href);

    const goHome = () => {
        if (user?.tenantCode) {
            navigate(`/${user.tenantCode}/home`);
        } else {
            navigate('/');
        }
    };

    return (
        <>
            <header className="main-header">
                <h2 className="header-logo" onClick={goHome}>
                    MyKOPKB QMS-Admin
                </h2>

                <div className="header-logout">
                    {!!user && (
                        <button
                            className="header-logout-btn"
                            onClick={handleLogout}
                        >
                            Logout
                        </button>
                    )}
                </div>
            </header>

            {showBackButton && (
                <Button
                    variant="secondary"
                    className="mt-2 px-4"
                    onClick={goHome}
                >
                    Back
                </Button>
            )}
        </>
    );
}