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

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 { message } = App.useApp();
  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 (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: '#22D3EE',
          colorBgContainer: 'rgba(255, 255, 255, 0.05)',
        },
      }}
    >
      <Layout className="min-h-screen bg-[#0A1628]">
        <Header className="bg-transparent border-b border-white/10 flex items-center px-4 h-16 sticky top-0 z-10 backdrop-blur-md">
          <img src={主要LOGO} alt="主要LOGO" style={{ width: '120px', height: '48px', filter: 'brightness(0) invert(1)' }} />
        </Header>

        <Content className="flex items-center justify-center p-4 bg-gradient-to-br from-[#0A1628] via-[#0f2942] to-[#0A1628] relative overflow-hidden">
          {/* Decorative ambient gradients */}
          <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-cyan-500/10 rounded-full blur-3xl pointer-events-none" />
          <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-purple-500/10 rounded-full blur-3xl pointer-events-none" />

          <div className="w-full max-w-md relative z-10">
            <GlassCard className="p-4">
              <div className="text-center mb-6">
                <h1 className="text-2xl font-bold text-white mb-2">管理员登录</h1>
                <p className="text-white/60 text-xs">请输入管理员账号密码</p>
              </div>

              <Form
                layout="vertical"
                onFinish={handleSubmit}
                autoComplete="off"
                form={form}
                size="large"
              >
                {/* 最近登录记录下拉选择 */}
                {loginRecords.length > 0 && (
                  <Form.Item label={<span className="text-white/80">最近登录</span>} className="mb-4">
                    <Select
                      placeholder="选择最近登录记录"
                      className="w-full"
                      style={{ height: 'auto' }}
                      dropdownStyle={{ backgroundColor: 'rgba(30, 41, 59, 0.95)', border: '1px solid rgba(255,255,255,0.1)' }}
                      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">
                            <span className="font-medium block text-sm text-white">{record.username}</span>
                            <span className="text-xs text-white/50 block">
                              {new Date(record.timestamp).toLocaleString()}
                            </span>
                          </div>
                        )
                      }))}
                    />
                  </Form.Item>
                )}

                <Form.Item
                  label={<span className="text-white/80">用户名</span>}
                  name="username"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 3, message: '用户名至少3个字符' }
                  ]}
                  className="mb-4"
                >
                  <Input 
                    placeholder="请输入用户名" 
                    autoComplete="username"
                    className="bg-white/5 border-white/10 text-white placeholder:text-white/30 hover:bg-white/10 focus:bg-white/10 focus:border-cyan-500/50"
                  />
                </Form.Item>

                <Form.Item
                  label={<span className="text-white/80">密码</span>}
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6个字符' }
                  ]}
                  className="mb-6"
                >
                  <Input.Password 
                    placeholder="请输入密码" 
                    autoComplete="new-password"
                    allowClear
                    className="bg-white/5 border-white/10 text-white placeholder:text-white/30 hover:bg-white/10 focus:bg-white/10 focus:border-cyan-500/50"
                  />
                </Form.Item>

                <Form.Item className="mb-0">
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    block
                    className="bg-cyan-600 hover:!bg-cyan-500 border-none shadow-lg shadow-cyan-900/20 h-10 font-medium"
                  >
                    登录
                  </Button>
                </Form.Item>
              </Form>

              <div className="mt-4 text-center">
                <a 
                  href="/" 
                  className="text-cyan-400 hover:text-cyan-300 text-xs transition-colors"
                >
                  返回用户端
                </a>
              </div>
            </GlassCard>
          </div>
        </Content>

        <Footer className="bg-[#0A1628] border-t border-white/5 py-4 flex flex-col md:flex-row justify-center items-center text-white/30 text-xs">
          <div className="mb-2 md:mb-0 whitespace-nowrap">
            &copy; {new Date().getFullYear()} Boonlive OA System. All Rights Reserved.
          </div>
        </Footer>
      </Layout>
    </ConfigProvider>
  );
};

export default AdminLoginPage;
