import { useState } from 'react';
import { Layout, Menu, Dropdown, Badge, Space, Avatar, Button, DatePicker } from 'antd';
import { useNavigate, Outlet, useLocation } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
  IconMenu2,
  IconBell,
  IconUser,
  IconLogout,
} from '@tabler/icons-react';
import dayjs from 'dayjs';
import { menuApi, MenuResp } from '@/api/menu';
import { authApi } from '@/api/auth';
import { useAuthStore } from '@/stores/auth';

const { Header, Sider, Content } = Layout;

function toMenuItems(menus: MenuResp[]): any[] {
  return menus.map((m) => ({
    key: m.menuPath ?? m.menuCode,
    label: m.menuName,
    children: m.children?.length ? toMenuItems(m.children) : undefined,
  }));
}

export default function MainLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const auth = useAuthStore();
  const [collapsed, setCollapsed] = useState(false);
  const [settleMonth, setSettleMonth] = useState(dayjs());

  const { data: menus = [] } = useQuery({
    queryKey: ['menu', 'my'],
    queryFn: menuApi.myMenus,
  });

  const handleLogout = async () => {
    try { await authApi.logout(); } catch { /* ignore */ }
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    auth.clear();
    navigate('/login');
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header
        style={{
          height: 48,
          lineHeight: '48px',
          background: '#ffffff',
          borderBottom: '1px solid #f0f0f0',
          padding: '0 16px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          boxShadow: 'var(--ga-shadow-card)',
        }}
      >
        <Space size={12}>
          <Button
            type="text"
            icon={<IconMenu2 size={18} />}
            onClick={() => setCollapsed((c) => !c)}
          />
          <span style={{ fontSize: 15, fontWeight: 600, color: '#185FA5' }}>
            GA 정산시스템
          </span>
        </Space>
        <Space size={12}>
          <DatePicker
            picker="month"
            value={settleMonth}
            onChange={(d) => d && setSettleMonth(d)}
            allowClear={false}
            format="YYYY-MM"
            size="small"
          />
          <Badge count={0} size="small">
            <Button type="text" icon={<IconBell size={18} />} />
          </Badge>
          <Dropdown
            menu={{
              items: [
                {
                  key: 'logout',
                  label: '로그아웃',
                  icon: <IconLogout size={14} />,
                  onClick: handleLogout,
                },
              ],
            }}
          >
            <Space style={{ cursor: 'pointer' }}>
              <Avatar size="small" icon={<IconUser size={14} />} />
              <span style={{ fontSize: 13 }}>{auth.userName ?? auth.loginId}</span>
            </Space>
          </Dropdown>
        </Space>
      </Header>
      <Layout>
        <Sider
          width={220}
          collapsedWidth={64}
          collapsed={collapsed}
          theme="light"
          style={{ borderRight: '1px solid #f0f0f0' }}
        >
          <Menu
            mode="inline"
            items={toMenuItems(menus)}
            selectedKeys={[location.pathname]}
            onClick={({ key }) => navigate(String(key))}
            style={{ borderRight: 0, height: '100%', paddingTop: 8 }}
          />
        </Sider>
        <Content style={{ padding: 'var(--ga-content-padding)', overflow: 'auto' }}>
          <div className="ga-page-container">
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}
