import React from 'react';
import { Dropdown, Menu, Avatar, Button, Switch, message } from 'antd';
import { UserOutlined, SettingOutlined, LogoutOutlined, ReloadOutlined, MoonOutlined, RetweetOutlined } from '@ant-design/icons';

export default function UserMenu({ user, onLogout, darkMode, onToggleDarkMode, sortMode, setSortMode, saving }) {
  const [messageApi, contextHolder] = message.useMessage();
  // Funktion zum Leeren aller ads-overview-Caches
  function clearAdsCache() {
    let removed = 0;
    Object.keys(localStorage).forEach(key => {
      if (key.startsWith('ads-overview-')) {
        localStorage.removeItem(key);
        removed++;
      }
    });
    if (removed > 0) {
      messageApi.success({ content: 'Cache erfolgreich geleert!', duration: 2 });
    } else {
      messageApi.info({ content: 'Kein Cache gefunden.', duration: 2 });
    }
  }
  const menu = {
    items: [
      {
        key: 'darkmode',
        icon: <MoonOutlined />, 
        label: (
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span>Darkmode</span>
            <Switch checked={darkMode} onChange={onToggleDarkMode} size="small" />
          </span>
        ),
      },
      { type: 'divider' },
      // Sortierfunktion als Menüpunkt
      {
        key: 'sortmode',
        icon: <RetweetOutlined />, 
        label: (
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span>Sortieren</span>
            <Switch
              checked={!!sortMode}
              onChange={setSortMode}
              loading={!!saving}
              size="small"
              disabled={typeof sortMode === 'undefined' || typeof setSortMode !== 'function'}
            />
          </span>
        ),
        disabled: typeof sortMode === 'undefined' || typeof setSortMode !== 'function'
      },
      { type: 'divider' },
      {
        key: 'clearcache',
        icon: <ReloadOutlined />, 
        label: 'Cache leeren',
        onClick: clearAdsCache,
      },
      { type: 'divider' },
      {
        key: 'settings',
        icon: <SettingOutlined />, 
        label: 'Einstellungen (bald)',
        disabled: true,
      },
      { type: 'divider' },
      {
        key: 'logout',
        icon: <LogoutOutlined />, 
        label: 'Ausloggen',
        onClick: onLogout,
      },
    ].filter(Boolean),
  };

  return (
    <>
      {contextHolder}
      <Dropdown menu={menu} placement="bottomRight">
        {/* <Button type="text" style={{ padding: 0, height: 40 }}> */}
          {/* {user.username || user.client} */}
          <Avatar style={{ backgroundColor: '#c792ff', color: '#001f1e', marginRight: 8 }} icon={<UserOutlined />} />
        {/* </Button> */}
      </Dropdown>
    </>
  );
}
