import { useState, useEffect } from 'react';
import { Card, Form, Input, Button, App, Typography, AutoComplete, Layout } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useUser } from '../contexts';
import { userAPI } from '../services/api';
import { validateUserForm } from '../utils/validation';
import 主要LOGO from '../assets/主要LOGO.svg';

const { Header, Content, Footer } = Layout;
const { Title } = Typography;

interface LoginHistory {
  name: string;
  phone: string;
}

const HomePage = () => {
  const navigate = useNavigate();
  const { message } = App.useApp();
  const { setUser } = useUser();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [historyOptions, setHistoryOptions] = useState<{ value: string; label: string; phone: string }[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  useEffect(() => {
    // 加载历史记录
    const history = JSON.parse(localStorage.getItem('loginHistory') || '[]');
    setHistoryOptions(history.map((item: LoginHistory) => ({
      value: item.name,
      label: item.name,
      phone: item.phone
    })));
  }, []);

  const saveToHistory = (name: string, phone: string) => {
    const history: LoginHistory[] = JSON.parse(localStorage.getItem('loginHistory') || '[]');
    // 移除已存在的同名记录（为了更新位置到最前，或者保持最新）
    const filtered = history.filter(item => item.name !== name);
    // 添加到头部
    filtered.unshift({ name, phone });
    // 保留前5条
    const newHistory = filtered.slice(0, 5);
    localStorage.setItem('loginHistory', JSON.stringify(newHistory));
    
    // 更新本地历史选项
    setHistoryOptions(newHistory.map(item => ({
      value: item.name,
      label: item.name,
      phone: item.phone
    })));
  };

  const handleNameSelect = (value: string, option: any) => {
    if (option.phone) {
      form.setFieldsValue({ phone: option.phone });
    }
  };

  const handleNameChange = async (value: string) => {
    if (!value) return;
    
    // 先检查本地历史记录
    const localOption = historyOptions.find(option => option.value === value);
    if (localOption && localOption.phone) {
      form.setFieldsValue({ phone: localOption.phone });
      return;
    }
    
    // 本地没有则从服务器查询
    try {
      setIsSearching(true);
      const response = await userAPI.getUsersByName(value) as any;
      
      if (response.success && response.data && response.data.length > 0) {
        // 假设返回的是数组，取第一个匹配的用户
        const user = response.data[0];
        if (user && user.phone) {
          form.setFieldsValue({ phone: user.phone });
          // 将查询结果保存到本地历史记录
          saveToHistory(value, user.phone);
        }
      }
    } catch (error: any) {
      console.error('查询用户失败:', error);
      // 查询失败不提示用户，保持原有逻辑
    } finally {
      setIsSearching(false);
    }
  };

  const handleSubmit = async (values: { name: string; phone: string; password?: string }) => {
    try {
      setLoading(true);
      
      // 验证表单
      const validation = validateUserForm(values.name, values.phone);
      if (!validation.valid) {
        message.error(validation.nameError || validation.phoneError);
        return;
      }

      // 创建用户或登录
      const response = await userAPI.validateUserInfo(values) as any;
      
      if (response.success) {
        setUser(response.data);
        saveToHistory(values.name, values.phone);
        message.success('登录成功，请选择考试科目');
        setTimeout(() => {
          navigate('/subjects');
        }, 1000);
      }
    } catch (error: any) {
      message.error(error.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  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">
              <Title level={2} className="text-mars-600 !mb-0.5 !text-lg">
                宝来威考试平台
              </Title>
              <p className="text-gray-500 text-xs">
                请填写您的基本信息开始答题
              </p>
            </div>

            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              autoComplete="off"
            >
              <Form.Item
                label="姓名"
                name="name"
                rules={[
                  { required: true, message: '请输入姓名' },
                  { min: 2, max: 20, message: '姓名长度必须在2-20个字符之间' },
                  { pattern: /^[\u4e00-\u9fa5a-zA-Z\s]+$/, message: '姓名只能包含中文、英文和空格' }
                ]}
                className="mb-2"
              >
                <AutoComplete
                  options={historyOptions}
                  onSelect={handleNameSelect}
                  onChange={handleNameChange}
                  placeholder="请输入您的姓名"
                  filterOption={(inputValue, option) =>
                    option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                  }
                />
              </Form.Item>

              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的中国手机号' }
                ]}
                className="mb-2"
              >
                <Input 
                  placeholder="请输入11位手机号" 
                  maxLength={11}
                />
              </Form.Item>

              <Form.Item
                label="登录密码"
                name="password"
                rules={[
                  { required: true, message: '请输入登录密码' }
                ]}
                className="mb-2"
              >
                <Input.Password
                  placeholder="请输入登录密码"
                  autoComplete="new-password"
                  visibilityToggle
                />
              </Form.Item>

              <Form.Item className="mb-2 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="/admin/login" 
                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 HomePage;
