import { useState } from 'react';
import { Layout, Menu, Button, Typography, Avatar, Dropdown, Grid, Drawer } from 'antd';
import {
  DashboardOutlined,
  CloudServerOutlined,
  SaveOutlined,
  AuditOutlined,
  SettingOutlined,
  LogoutOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MenuOutlined,
  ApiOutlined,
  KeyOutlined,
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth.store';

const { Header, Sider, Content } = Layout;

export default function AppLayout() {
  const [collapsed, setCollapsed] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { user, logout } = useAuthStore();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const menuItems = [
    {
      key: '/app',
      icon: <DashboardOutlined />,
      label: 'Dashboard',
    },
    {
      key: '/app/instances',
      icon: <CloudServerOutlined />,
      label: 'Instances',
    },
    {
      key: '/app/backups',
      icon: <SaveOutlined />,
      label: 'Backups',
    },
    {
      key: '/app/agents',
      icon: <ApiOutlined />,
      label: 'Remote Agents',
      children: [
        { key: '/app/agents/registrations', icon: <ApiOutlined />, label: 'Registrations' },
        { key: '/app/agents/invite-codes', icon: <KeyOutlined />, label: 'Invite Codes' },
      ],
    },
    {
      key: '/app/audit',
      icon: <AuditOutlined />,
      label: 'Audit Log',
    },
    {
      key: '/app/settings',
      icon: <SettingOutlined />,
      label: 'Settings',
    },
  ];

  // Use startsWith matching with longest-match preference so sub-routes
  // like /app/instances/123 highlight the "Instances" menu item, not Dashboard.
  // Flatten children for matching.
  const allKeys = menuItems.flatMap((item) =>
    'children' in item && item.children
      ? item.children.map((c) => ({ key: c.key as string }))
      : [{ key: item.key as string }]
  );
  const selectedKey = allKeys
    .filter((item) => location.pathname === item.key || location.pathname.startsWith(item.key + '/'))
    .sort((a, b) => b.key.length - a.key.length)[0]?.key || '/app';

  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
    if (isMobile) setDrawerOpen(false);
  };

  const userMenu = {
    items: [
      {
        key: 'logout',
        icon: <LogoutOutlined />,
        label: 'Logout',
        onClick: async () => {
          await logout();
          navigate('/login');
        },
      },
    ],
  };

  const siderContent = (
    <>
      <div
        style={{
          height: 64,
          display: 'flex',
          alignItems: 'center',
          justifyContent: isMobile ? 'flex-start' : collapsed ? 'center' : 'flex-start',
          padding: isMobile ? '0 16px' : collapsed ? 0 : '0 16px',
        }}
      >
        <Typography.Title
          level={4}
          style={{ color: '#fff', margin: 0, whiteSpace: 'nowrap' }}
        >
          {!isMobile && collapsed ? 'CCP' : 'Control Panel'}
        </Typography.Title>
      </div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={[selectedKey]}
        items={menuItems}
        onClick={handleMenuClick}
      />
    </>
  );

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {isMobile ? (
        <Drawer
          placement="left"
          open={drawerOpen}
          onClose={() => setDrawerOpen(false)}
          width={240}
          styles={{ body: { padding: 0, background: '#001529' } }}
          closable={false}
        >
          {siderContent}
        </Drawer>
      ) : (
        <Sider
          collapsible
          collapsed={collapsed}
          onCollapse={setCollapsed}
          trigger={null}
          width={240}
          style={{
            overflow: 'auto',
            height: '100vh',
            position: 'fixed',
            left: 0,
            top: 0,
            bottom: 0,
            zIndex: 10,
          }}
        >
          {siderContent}
        </Sider>
      )}
      <Layout style={{ marginLeft: isMobile ? 0 : collapsed ? 80 : 240, transition: 'margin-left 0.2s' }}>
        <Header
          style={{
            padding: '0 24px',
            background: 'transparent',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          {isMobile ? (
            <Button
              type="text"
              icon={<MenuOutlined />}
              onClick={() => setDrawerOpen(true)}
              style={{ fontSize: 16 }}
            />
          ) : (
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              style={{ fontSize: 16 }}
            />
          )}
          <Dropdown menu={userMenu} placement="bottomRight">
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar icon={<UserOutlined />} size="small" />
              <span>{user?.name || user?.email}</span>
            </div>
          </Dropdown>
        </Header>
        <Content style={{ margin: isMobile ? 12 : 24, minHeight: 280 }}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
}
