/**
 * @file Navbar.tsx - Top navigation bar displayed on all authenticated pages.
 * Includes the brand logo and company name, a home button (hidden on mobile and the home page), and a user settings dropdown containing the language switcher, auto-save mode selector, open mode selector, and a logout button.
 * User preferences for save mode and open mode are persisted in localStorage.
 */

import {
  Button,
  ButtonGroup,
  Container,
  Dropdown,
  DropdownButton,
  FloatingLabel,
  Form,
  Navbar as BSNavbar,
  OverlayTrigger,
  Tooltip,
} from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import {
  // @ts-expect-error vite-imagetools OutputMetadata
  src as iconSrc,
  // @ts-expect-error vite-imagetools OutputMetadata
  width as iconWidth,
  // @ts-expect-error vite-imagetools OutputMetadata
  height as iconHeight,
} from '../assets/brand/icon.png';
import { Icon } from './Icon.tsx';
import { useAuth } from '../contexts/AuthContext.tsx';
import { useMediaQuery } from 'react-responsive';
import { breakpoints } from '../utils/bootstrapBreakpoints.ts';
import { type ChangeEvent, useState } from 'react';
import {
  getStoredOpenMode,
  getStoredSaveMode,
  type OpenMode,
  type SaveMode,
  setStoredOpenMode,
  setStoredSaveMode,
} from '../utils/localStorage.ts';
import { useHasVerticalScrollbar } from '../hooks/useHasVerticalScrollbar.ts';
import { useTranslation } from 'react-i18next';
import { LanguageSwitcher } from './LanguageSwitcher.tsx';

/**
 * Fixed-top navigation bar with brand identity and user settings.
 * Renders the application title and company name alongside a home button and user settings dropdown.
 */
export const Navbar = () => {
  const { username, logout } = useAuth();
  const navigate = useNavigate();

  // Calculate ratio for scaling brand icon
  const desiredIconSize: number = import.meta.env.VITE_APP_NAVBAR_ICON_SIZE;
  const iconRatio = Math.min(
    desiredIconSize / iconWidth,
    desiredIconSize / iconHeight
  );

  // Used for "Auto-save mode" select menu
  const [saveMode, setSaveMode] = useState<SaveMode>(
    getStoredSaveMode() || 'manual'
  );
  const updateSaveMode = (event: ChangeEvent<HTMLSelectElement>) => {
    const value = event.target.value as SaveMode;
    setSaveMode(value);
    setStoredSaveMode(value);
  };

  // Used for "Auto-open mode" select menu
  const [openMode, setOpenMode] = useState<OpenMode>(
    getStoredOpenMode() || 'manual'
  );
  const updateOpenMode = (event: ChangeEvent<HTMLSelectElement>) => {
    const value = event.target.value as OpenMode;
    setOpenMode(value);
    setStoredOpenMode(value);
  };

  // Hide the home button on small screens and when already on the home page
  const isMobileSm = useMediaQuery({ maxWidth: breakpoints.sm - 1 });
  const isHomePage = window.location.pathname === '/home';
  const tooltipFixed = !useHasVerticalScrollbar();

  const { t } = useTranslation(undefined, {
    keyPrefix: 'components.navbar',
  });

  return (
    <>
      <BSNavbar
        bg={'dark'}
        variant={'dark'}
        fixed={'top'}
        expand={''}
        className={'flex-column navbar-z-index'}
      >
        <Container
          fluid
          className={'d-flex justify-content-between align-items-center px-3'}
        >
          <div
            className={'d-flex align-items-center'}
            style={{ minWidth: 0, flex: 1 }}
          >
            <BSNavbar.Brand
              onClick={() => navigate('/')}
              role={'button'}
              style={{ minWidth: 0 }}
            >
              <div
                className='d-flex align-items-center'
                style={{ marginTop: '-0.5rem', minWidth: 0 }}
              >
                <img
                  src={iconSrc}
                  width={Math.min(
                    desiredIconSize,
                    Math.round(iconWidth * iconRatio)
                  )}
                  height={Math.min(
                    desiredIconSize,
                    Math.round(iconHeight * iconRatio)
                  )}
                  className={'mt-1'}
                  loading={'lazy'}
                  style={{ flexShrink: 0 }}
                />{' '}
                <div
                  className={'ms-2 d-flex flex-column'}
                  style={{ minWidth: 0 }}
                >
                  <span
                    className={'fs-3 fw-semibold overflow-hidden'}
                    style={{ textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                  >
                    {import.meta.env.VITE_APP_TITLE}
                  </span>
                  <span
                    className={'fs-5 overflow-hidden'}
                    style={{
                      marginTop: '-0.5rem',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {window.__APP_CONFIG__?.COMPANY_NAME}
                  </span>
                </div>
              </div>
            </BSNavbar.Brand>
          </div>
          <div className={'d-flex align-items-center'}>
            {!isMobileSm && !isHomePage && (
              <BSNavbar.Brand onClick={() => navigate('/')} role={'button'}>
                <OverlayTrigger
                  placement={'bottom'}
                  overlay={
                    <Tooltip
                      className={tooltipFixed ? 'position-fixed' : undefined}
                    >
                      {t('buttons.home.tooltip')}
                    </Tooltip>
                  }
                >
                  <Icon iconName={'HouseFill'} size={32} />
                </OverlayTrigger>
              </BSNavbar.Brand>
            )}
            <Dropdown as={ButtonGroup}>
              <DropdownButton
                variant={'outline-light'}
                title={
                  <OverlayTrigger
                    placement={'bottom'}
                    overlay={
                      <Tooltip
                        className={tooltipFixed ? 'position-fixed' : undefined}
                      >
                        {t('buttons.user_profile.tooltip')}
                      </Tooltip>
                    }
                  >
                    <Icon iconName={'PersonFillGear'} size={32} />
                  </OverlayTrigger>
                }
                align={'end'}
              >
                <Dropdown.ItemText className={'text-center'}>
                  {t('buttons.user_profile.dropdown.logged_in_as')}:{' '}
                  <code className={'text-success'}>{username}</code>
                </Dropdown.ItemText>
                <Dropdown.Divider />
                {/* Language switcher */}
                <Dropdown.ItemText>
                  <LanguageSwitcher />
                </Dropdown.ItemText>
                <Dropdown.Divider />
                {/* Auto-save mode setting */}
                <Dropdown.ItemText>
                  <FloatingLabel
                    controlId={'save-mode-select'}
                    label={`${t('buttons.user_profile.dropdown.selects.save_mode.label')}`}
                  >
                    <Form.Select value={saveMode} onChange={updateSaveMode}>
                      <option key={'manual'} value={'manual'}>
                        {t(
                          'buttons.user_profile.dropdown.selects.save_mode.options.manual'
                        )}
                      </option>
                      <option key={'auto'} value={'auto'}>
                        {t(
                          'buttons.user_profile.dropdown.selects.save_mode.options.auto'
                        )}
                      </option>
                    </Form.Select>
                  </FloatingLabel>
                </Dropdown.ItemText>
                <Dropdown.Divider />
                {/* Auto-open mode setting */}
                <Dropdown.ItemText>
                  <FloatingLabel
                    controlId={'open-mode-select'}
                    label={`${t(
                      'buttons.user_profile.dropdown.selects.open_mode.label'
                    )}`}
                  >
                    <Form.Select value={openMode} onChange={updateOpenMode}>
                      <option key={'manual'} value={'manual'}>
                        {t(
                          'buttons.user_profile.dropdown.selects.open_mode.options.manual'
                        )}
                      </option>
                      <option key={'inbox'} value={'inbox'}>
                        {t(
                          'buttons.user_profile.dropdown.selects.open_mode.options.inbox'
                        )}
                      </option>
                      <option key={'queue'} value={'queue'}>
                        {t(
                          'buttons.user_profile.dropdown.selects.open_mode.options.queue'
                        )}
                      </option>
                    </Form.Select>
                  </FloatingLabel>
                </Dropdown.ItemText>
                <Dropdown.Divider />
                <Dropdown.ItemText>
                  <Button
                    variant={'danger'}
                    onClick={logout}
                    className={'w-100'}
                  >
                    {t('buttons.user_profile.dropdown.buttons.log_out.default')}
                  </Button>
                </Dropdown.ItemText>
              </DropdownButton>
            </Dropdown>
          </div>
        </Container>
      </BSNavbar>
    </>
  );
};
