import { useState, useEffect } from 'react';
import { Card, Form, Input, Button, message, Select, Layout } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAdmin } from '../../contexts';
import { adminAPI } from '../../services/api';
import 主要LOGO from '../../assets/主要LOGO.svg';

const { Header, Content, Footer } = Layout;

// 定义登录记录类型 - 不再保存密码
interface LoginRecord {
  username: string;
  timestamp: number;
}

// 本地存储键名
const LOGIN_RECORDS_KEY = 'admin_login_records';
// 最大记录数量
const MAX_RECORDS = 5;

// 获取本地存储的登录记录
const getLoginRecords = (): LoginRecord[] => {
  try {
    const records = localStorage.getItem(LOGIN_RECORDS_KEY);
    return records ? JSON.parse(records) : [];
  } catch (error) {
    console.error('获取登录记录失败:', error);
    return [];
  }
};

// 保存登录记录到本地存储 - 不再保存密码
const saveLoginRecord = (record: LoginRecord) => {
  try {
    const records = getLoginRecords();
    // 移除相同用户名的旧记录
    const filteredRecords = records.filter(r => r.username !== record.username);
    // 添加新记录到开头
    const updatedRecords = [record, ...filteredRecords].slice(0, MAX_RECORDS);
    localStorage.setItem(LOGIN_RECORDS_KEY, JSON.stringify(updatedRecords));
  } catch (error) {
    console.error('保存登录记录失败:', error);
  }
};

const AdminLoginPage = () => {
  const navigate = useNavigate();
  const { setAdmin } = useAdmin();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [loginRecords, setLoginRecords] = useState<LoginRecord[]>([]);

  // 初始化获取登录记录
  useEffect(() => {
    setLoginRecords(getLoginRecords());
  }, []);

  const handleSubmit = async (values: { username: string; password: string }) => {
    try {
      setLoading(true);
      const response = await adminAPI.login(values) as any;
      
      if (response.success) {
        // 保存登录记录 - 不再保存密码
        saveLoginRecord({
          username: values.username,
          timestamp: Date.now()
        });
        
        // 更新状态
        setLoginRecords(getLoginRecords());
        
        setAdmin({
          username: values.username,
          token: response.data.token
        });
        message.success('登录成功');
        navigate('/admin/dashboard');
      }
    } catch (error: any) {
      message.error(error.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理从下拉列表选择历史记录 - 不再自动填充密码
  const handleSelectRecord = (record: LoginRecord) => {
    form.setFieldsValue({
      username: record.username,
      password: '' // 清空密码，必须每次手动输入
    });
  };

  return (
    <Layout className="min-h-screen bg-gray-50">
      <Header className="bg-white shadow-sm flex items-center px-4 h-12 sticky top-0 z-10">
        <img src={主要LOGO} alt="主要LOGO" style={{ width: '120px', height: '48px' }} />
      </Header>

      <Content className="flex items-center justify-center p-2 bg-gradient-to-br from-mars-50 to-white">
        <div className="w-full max-w-md">
          <Card className="shadow-xl border-t-4 border-t-mars-500 p-2">
            <div className="text-center mb-3">
              <h1 className="text-2xl font-bold text-mars-600 mb-2">管理员登录</h1>
              <p className="text-gray-600 text-xs">请输入管理员账号密码</p>
            </div>

            <Form
              layout="vertical"
              onFinish={handleSubmit}
              autoComplete="off"
              form={form}
            >
              {/* 最近登录记录下拉选择 */}
              {loginRecords.length > 0 && (
                <Form.Item label="最近登录" className="mb-2">
                  <Select
                    placeholder="选择最近登录记录"
                    className="w-full"
                    style={{ height: 'auto' }} // 让选择框高度自适应内容
                    onSelect={(value) => {
                      const record = loginRecords.find(r => `${r.username}-${r.timestamp}` === value);
                      if (record) {
                        handleSelectRecord(record);
                      }
                    }}
                    options={loginRecords.map(record => ({
                      value: `${record.username}-${record.timestamp}`,
                      label: (
                        <div className="flex flex-col p-1" style={{ minHeight: '40px', justifyContent: 'center' }}>
                          <span className="font-medium block text-xs">{record.username}</span>
                          <span className="text-xs text-gray-500 block">
                            {new Date(record.timestamp).toLocaleString()}
                          </span>
                        </div>
                      )
                    }))}
                  />
                </Form.Item>
              )}

              <Form.Item
                label="用户名"
                name="username"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, message: '用户名至少3个字符' }
                ]}
                className="mb-2"
              >
                <Input 
                  placeholder="请输入用户名" 
                  autoComplete="username" // 正确的自动完成属性
                />
              </Form.Item>

              <Form.Item
                label="密码"
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' }
                ]}
                className="mb-2"
              >
                <Input.Password 
                  placeholder="请输入密码" 
                  autoComplete="new-password" // 防止自动填充密码
                  allowClear // 允许清空密码
                />
              </Form.Item>

              <Form.Item className="mb-0 mt-3">
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  className="bg-mars-500 hover:!bg-mars-600 border-none shadow-md h-9 text-sm font-medium"
                >
                  登录
                </Button>
              </Form.Item>
            </Form>

            <div className="mt-3 text-center">
              <a 
                href="/" 
                className="text-mars-600 hover:text-mars-800 text-xs transition-colors"
              >
                返回用户端
              </a>
            </div>
          </Card>
        </div>
      </Content>

      <Footer className="bg-white border-t border-gray-100 py-1.5 px-2 flex flex-col md:flex-row justify-center items-center text-gray-400 text-xs">
        <div className="mb-2 md:mb-0 whitespace-nowrap">
          &copy; {new Date().getFullYear()} Boonlive OA System. All Rights Reserved.
        </div>
      </Footer>
    </Layout>
  );
};

export default AdminLoginPage;
