import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Space, Select } from 'antd';
import { UserOutlined, LockOutlined, IdcardOutlined, ApartmentOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import axios from 'axios';
import API_BASE_URL from '../config';

const Register = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [departments, setDepartments] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    fetchDepartments();
  }, []);

  const fetchDepartments = async () => {
    try {
      // 部门管理已合并进字典管理，使用字典接口获取
      const response = await axios.get(`${API_BASE_URL}/api/dictionaries/departments`);
      setDepartments(response.data);
    } catch (error) {
      message.error('获取部门列表失败');
    }
  };

  const sendCode = async () => {
    const phoneNumber = form.getFieldValue('username');
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      return message.error('请先输入正确的手机号');
    }

    setSending(true);
    try {
      await axios.post(`${API_BASE_URL}/api/auth/send-code`, { 
        phoneNumber,
        type: 'register'
      });
      message.success('验证码已发送');
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown(prev => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      message.error(error.response?.data?.message || '发送失败');
    } finally {
      setSending(false);
    }
  };

  const onFinish = async (values) => {
    setLoading(true);
    try {
      await axios.post(`${API_BASE_URL}/api/auth/register`, {
        ...values,
        role: 'user'
      });
      message.success('注册成功，请登录');
      navigate('/login');
    } catch (error) {
      message.error(error.response?.data?.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center', 
      height: '100vh',
      background: '#f0f2f5' 
    }}>
      <Card title="科技成果转化系统 - 用户注册" style={{ width: 400 }}>
        <Form form={form} name="register" onFinish={onFinish} layout="vertical">
          <Form.Item label="手机号" required style={{ marginBottom: 0 }}>
            <Space.Compact style={{ width: '100%' }}>
              <Form.Item
                name="username"
                noStyle
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '格式错误' }
                ]}
              >
                <Input prefix={<UserOutlined />} placeholder="手机号" style={{ width: '70%' }} />
              </Form.Item>
              <Button 
                onClick={sendCode} 
                disabled={sending || countdown > 0} 
                style={{ width: '30%' }}
              >
                {countdown > 0 ? `${countdown}s` : '验证码'}
              </Button>
            </Space.Compact>
          </Form.Item>

          <Form.Item
            name="code"
            label="验证码"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Input prefix={<LockOutlined />} placeholder="6位数字验证码" />
          </Form.Item>

          <Form.Item
            name="real_name"
            label="真实姓名"
            rules={[{ required: true, message: '请输入真实姓名' }]}
          >
            <Input prefix={<IdcardOutlined />} placeholder="真实姓名" />
          </Form.Item>

          <Form.Item
            name="department"
            label="所属部门"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select 
              placeholder="请选择所属部门" 
              prefix={<ApartmentOutlined />}
              showSearch
              optionFilterProp="children"
            >
              {departments.map(dept => (
                <Select.Option key={dept.id} value={dept.name}>{dept.name}</Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="设置登录密码" />
          </Form.Item>

          <Form.Item
            name="confirm"
            label="确认密码"
            dependencies={['password']}
            rules={[
              { required: true, message: '请再次输入密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="再次输入密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large" loading={loading}>
              立即注册
            </Button>
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              已有账号？ <Link to="/login">立即登录</Link>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Register;
