import {
  ApiOutlined,
  DesktopOutlined,
  IdcardOutlined,
  LockOutlined,
} from '@ant-design/icons';
import { GridContent } from '@ant-design/pro-components';
import { useIntl, useModel } from '@umijs/max';
import { Avatar, Layout, Menu, Spin, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import ApiKeysView from './components/apikeys';
import BaseView from './components/base';
import SecurityView from './components/security';
import SessionsView from './components/sessions';
import useStyles from './style.style';

const { Sider, Content } = Layout;
const { Title, Text } = Typography;

type SettingsStateKeys = 'base' | 'security' | 'apikeys' | 'sessions';

const Settings: React.FC = () => {
  const { styles } = useStyles();
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const dom = useRef<HTMLDivElement>(null);

  const [selectKey, setSelectKey] = useState<SettingsStateKeys>('base');
  const [collapsed, setCollapsed] = useState(false);

  // Responsive handling
  useEffect(() => {
    const resizeHandler = () => {
      if (!dom.current) return;
      const width = dom.current.offsetWidth;
      if (width < 640) {
        setCollapsed(true);
      } else {
        setCollapsed(false);
      }
    };
    window.addEventListener('resize', resizeHandler);
    resizeHandler();
    return () => window.removeEventListener('resize', resizeHandler);
  }, []);

  const menuMap: Record<string, React.ReactNode> = {
    base: intl.formatMessage({
      id: 'pages.account.settings.menu.base',
      defaultMessage: '基本设置',
    }),
    security: intl.formatMessage({
      id: 'pages.account.settings.menu.security',
      defaultMessage: '安全设置',
    }),
    apikeys: intl.formatMessage({
      id: 'pages.account.settings.menu.apikeys',
      defaultMessage: 'API Key',
    }),
    sessions: intl.formatMessage({
      id: 'pages.account.settings.menu.sessions',
      defaultMessage: '会话管理',
    }),
  };

  const menuItems = [
    {
      key: 'base',
      icon: <IdcardOutlined />,
      label: menuMap.base,
    },
    {
      key: 'security',
      icon: <LockOutlined />,
      label: menuMap.security,
    },
    {
      key: 'apikeys',
      icon: <ApiOutlined />,
      label: menuMap.apikeys,
    },
    {
      key: 'sessions',
      icon: <DesktopOutlined />,
      label: menuMap.sessions,
    },
  ];

  const renderContent = () => {
    switch (selectKey) {
      case 'base':
        return <BaseView />;
      case 'security':
        return <SecurityView />;
      case 'apikeys':
        return <ApiKeysView />;
      case 'sessions':
        return <SessionsView />;
      default:
        return null;
    }
  };

  const getAvatarURL = () => {
    if (currentUser?.avatar) return currentUser.avatar;
    return 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
  };

  if (!currentUser) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <GridContent>
      <div className={styles.container} ref={dom}>
        <Layout className={styles.layout}>
          <Sider
            width={280}
            theme="light"
            className={styles.sider}
            trigger={null}
            collapsible
            collapsed={collapsed}
            collapsedWidth={80}
            breakpoint="lg"
          >
            <div className={styles.siderContent}>
              <div className={styles.profileSection}>
                <Avatar
                  src={getAvatarURL()}
                  size={collapsed ? 48 : 64}
                  className={styles.avatar}
                />
                {!collapsed && (
                  <div className={styles.profileInfo}>
                    <Text strong className={styles.profileName}>
                      {currentUser.name || currentUser.username}
                    </Text>
                    <Text type="secondary" className={styles.profileEmail}>
                      {currentUser.email}
                    </Text>
                  </div>
                )}
              </div>

              <Menu
                mode="inline"
                selectedKeys={[selectKey]}
                onClick={({ key }) => setSelectKey(key as SettingsStateKeys)}
                items={menuItems}
                className={styles.menu}
              />
            </div>
          </Sider>

          <Content className={styles.content}>
            <div className={styles.contentHeader}>
              <Title level={4} style={{ marginBottom: 0 }}>
                {menuMap[selectKey]}
              </Title>
              {/* Optional: Add a toggle button for mobile if needed, though sider handles responsive */}
            </div>
            <div className={styles.contentBody}>{renderContent()}</div>
          </Content>
        </Layout>
      </div>
    </GridContent>
  );
};

export default Settings;
