'use client';

import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, theme, Avatar, Dropdown, Spin, Modal, Form, Input, message } from 'antd';
import {
  DashboardOutlined,
  TeamOutlined,
  SafetyOutlined,
  FileTextOutlined,
  LogoutOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  BookOutlined,
  LockOutlined,
} from '@ant-design/icons';
import { useRouter, usePathname } from 'next/navigation';
import { buildRoute, matchRoute } from '@/utils/route';
import { changePassword } from '@/services/api';

const { Header, Sider, Content } = Layout;

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const [collapsed, setCollapsed] = useState(false);
  const [loading, setLoading] = useState(true);
  const [showChangePasswordModal, setShowChangePasswordModal] = useState(false);
  const [passwordForm] = Form.useForm();
  const [passwordLoading, setPasswordLoading] = useState(false);
  const router = useRouter();
  const pathname = usePathname();
  const { token: themeToken } = theme.useToken();

  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token && !matchRoute(pathname, '/login')) {
      router.push(buildRoute('/login'));
    } else {
      setLoading(false);
    }
  }, [router, pathname]);

  if (loading) {
    return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
  }

  const menuItems = [
    { key: buildRoute('/dashboard'), icon: <DashboardOutlined />, label: '仪表盘' },
    { key: buildRoute('/clients'), icon: <TeamOutlined />, label: '客户管理' },
    { key: buildRoute('/permissions'), icon: <SafetyOutlined />, label: '权限配置' },
    { key: buildRoute('/logs'), icon: <FileTextOutlined />, label: '调用日志' },
    { key: buildRoute('/client'), icon: <BookOutlined />, label: '客户端' },
  ];

  const handleMenuClick = ({ key }: { key: string }) => {
    if (key === buildRoute('/client')) {
      window.open('/client.html', '_blank');
    } else {
      router.push(key);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    router.push(buildRoute('/login'));
  };

  const handleChangePassword = async (values: { oldPassword: string; newPassword: string }) => {
    setPasswordLoading(true);
    try {
      await changePassword(values.oldPassword, values.newPassword);
      message.success('密码修改成功，请重新登录');
      localStorage.removeItem('token');
      router.push(buildRoute('/login'));
    } catch (err: any) {
      message.error(err.response?.data?.detail || '密码修改失败');
    } finally {
      setPasswordLoading(false);
    }
  };

  const userMenu = {
    items: [
      { key: 'changePassword', icon: <LockOutlined />, label: '修改密码', onClick: () => setShowChangePasswordModal(true) },
      { key: 'logout', icon: <LogoutOutlined />, label: '退出登录', onClick: handleLogout },
    ],
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        theme="dark"
        style={{ position: 'fixed', left: 0, top: 0, bottom: 0, zIndex: 10 }}
      >
        <div style={{
          height: 64, display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontSize: collapsed ? 14 : 16, fontWeight: 600,
          borderBottom: '1px solid rgba(255,255,255,0.1)',
        }}>
          {collapsed ? '开放平台' : '进销存数据开放平台'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[pathname]}
          items={menuItems}
          onClick={handleMenuClick}
        />
      </Sider>
      <Layout style={{ marginLeft: collapsed ? 80 : 200, transition: 'all 0.2s' }}>
        <Header style={{
          padding: '0 24px', background: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          boxShadow: '0 1px 4px rgba(0,0,0,0.08)',
        }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{ fontSize: 16 }}
          />
          <Dropdown menu={userMenu}>
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar icon={<UserOutlined />} size="small" />
              <span>{localStorage.getItem('username') || '管理员'}</span>
            </div>
          </Dropdown>
        </Header>
        <Content style={{ margin: 24, padding: 24, background: themeToken.colorBgContainer, borderRadius: 8, minHeight: 360 }}>
          {children}
        </Content>
      </Layout>
      <Modal
        title="修改密码"
        open={showChangePasswordModal}
        onCancel={() => { setShowChangePasswordModal(false); passwordForm.resetFields(); }}
        footer={null}
      >
        <Form form={passwordForm} onFinish={handleChangePassword} layout="vertical">
          <Form.Item
            name="oldPassword"
            label="旧密码"
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="请输入旧密码" />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[{ required: true, message: '请输入新密码' }, { min: 6, message: '新密码长度不能少于6位' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的新密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="请再次输入新密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={passwordLoading} block>
              确认修改
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
}
