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

const ResetPassword = () => {
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [countdown]);

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

      setSendingCode(true);
      await axios.post(`${API_BASE_URL}/api/auth/send-code`, { 
        phoneNumber,
        type: 'reset' 
      });
      message.success('验证码已发送');
      setCountdown(60);
    } catch (error) {
      // 如果是 429 错误，尝试从错误消息中解析剩余秒数
      if (error.response?.status === 429) {
        const msg = error.response.data.message;
        const match = msg.match(/(\d+)/);
        if (match) {
          setCountdown(parseInt(match[1], 10));
        }
      }
      message.error(error.response?.data?.message || '发送失败');
    } finally {
      setSendingCode(false);
    }
  };

  const onFinish = async (values) => {
    setLoading(true);
    try {
      await axios.post(`${API_BASE_URL}/api/auth/reset-password`, {
        phoneNumber: values.phoneNumber,
        code: values.code,
        newPassword: values.newPassword
      });
      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: 'linear-gradient(135deg, #1677ff 0%, #003a8c 100%)' 
    }}>
      <Card style={{ width: 400, borderRadius: '12px', boxShadow: '0 8px 24px rgba(0,0,0,0.15)' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <h2 style={{ margin: 0, color: '#1f1f1f', fontSize: '24px', fontWeight: 600 }}>重置密码</h2>
          <p style={{ color: '#8c8c8c', marginTop: 8 }}>通过手机验证码重置您的密码</p>
        </div>
        <Form form={form} name="reset-password" onFinish={onFinish} layout="vertical">
          <Form.Item
            name="phoneNumber"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="手机号" size="large" />
          </Form.Item>

          <Form.Item label="验证码" required style={{ marginBottom: 0 }}>
            <Row gutter={8}>
              <Col span={14}>
                <Form.Item
                  name="code"
                  rules={[{ required: true, message: '请输入验证码' }]}
                >
                  <Input prefix={<SafetyOutlined />} placeholder="验证码" size="large" />
                </Form.Item>
              </Col>
              <Col span={10}>
                <Button 
                  block 
                  size="large" 
                  onClick={sendCode} 
                  disabled={countdown > 0 || sendingCode}
                  loading={sendingCode}
                >
                  {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6位' }
            ]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="新密码" size="large" />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            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="确认新密码" size="large" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large" loading={loading}>
              重置密码
            </Button>
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <Link to="/login"><ArrowLeftOutlined /> 返回登录</Link>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default ResetPassword;
