import React, { useEffect } from "react";
import { Layout, Space, Avatar, Dropdown, Select } from "antd";
import { UserOutlined, LogoutOutlined } from "@ant-design/icons";
import { useAuthStore } from "@/shared/stores/authStore";
import { useServerStore } from "@/shared/stores/serverStore";
import { api } from "@/shared/api";

const { Header } = Layout;

/**
 * Header для десктопной версии
 * Содержит логотип, заглушку выбора сервера и аватар пользователя
 */
export const DesktopHeader: React.FC = () => {
  const { user, logout } = useAuthStore();
  const { servers, activeServer, isLoading, fetchServers, setActiveServer } =
    useServerStore();

  // Загружаем список серверов при маунте компонента
  useEffect(() => {
    fetchServers();
  }, [fetchServers]);

  const handleLogout = async () => {
    await api.logout();
    logout();
    window.location.href = "/web";
  };

  const handleServerChange = (serverId: string) => {
    setActiveServer(serverId);
  };

  const userMenuItems = [
    {
      key: "logout",
      label: "Выйти",
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  return (
    <Header
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        backgroundColor: "#ffffff",
        boxShadow: "0 2px 8px rgba(0, 0, 0, 0.06)",
        padding: "0 24px",
        height: "64px",
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        zIndex: 1000,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: "24px" }}>
        {/* Логотип */}
        <div
          style={{
            fontSize: "20px",
            fontWeight: "bold",
            color: "#1890ff",
            display: "flex",
            alignItems: "center",
            gap: "8px",
          }}
        >
          <span>RMSer</span>
        </div>

        {/* Выбор сервера */}
        <Select
          placeholder="Выберите сервер"
          value={activeServer?.id || undefined}
          onChange={handleServerChange}
          loading={isLoading}
          disabled={isLoading}
          style={{ minWidth: "200px" }}
          options={servers.map((server) => ({
            label: server.name,
            value: server.id,
          }))}
        />
      </div>

      {/* Аватар пользователя */}
      <Space>
        <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
          <div
            style={{
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: "8px",
            }}
          >
            <Avatar size="default" icon={<UserOutlined />} />
            <span style={{ color: "#262626" }}>
              {user?.username || "Пользователь"}
            </span>
          </div>
        </Dropdown>
      </Space>
    </Header>
  );
};
