import { Button, Dropdown, Select, Space } from 'antd'
import { GlobalOutlined, LogoutOutlined, MenuOutlined, UserOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'

import apiClient from '../../api/client'
import { useAuthStore } from '../../stores/auth'

interface HeaderProps {
  pageTitle: string
  onMenuToggle: () => void
}

export default function Header({ pageTitle, onMenuToggle }: HeaderProps) {
  const { t, i18n } = useTranslation()
  const navigate = useNavigate()
  const user = useAuthStore((s) => s.user)
  const clear = useAuthStore((s) => s.clear)

  const onLogout = async () => {
    try { await apiClient.post('/auth/logout') } catch { /* ignore */ }
    clear()
    navigate('/login', { replace: true })
  }

  const onLangChange = (value: string) => {
    void i18n.changeLanguage(value)
  }

  return (
    <header className="header">
      <div className="header-left">
        <Button
          type="text"
          icon={<MenuOutlined />}
          onClick={onMenuToggle}
          className="header-menu-toggle"
          aria-label="Toggle navigation"
        />
        <h1 className="header-title">{pageTitle}</h1>
      </div>
      <div className="header-actions">
        <Select
          size="small"
          value={i18n.resolvedLanguage ?? 'de'}
          onChange={onLangChange}
          suffixIcon={<GlobalOutlined />}
          variant="borderless"
          options={[
            { value: 'de', label: 'DE' },
            { value: 'en', label: 'EN' },
          ]}
          popupMatchSelectWidth={false}
        />
        {user && (
          <Dropdown
            menu={{
              items: [
                {
                  key: 'logout',
                  icon: <LogoutOutlined />,
                  label: t('auth.logout'),
                  onClick: onLogout,
                },
              ],
            }}
            placement="bottomRight"
          >
            <Button type="text" className="header-user">
              <Space><UserOutlined />{user.actor}</Space>
            </Button>
          </Dropdown>
        )}
      </div>
    </header>
  )
}
