import React, { useState } from 'react';
import { Modal, Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined, MobileOutlined } from '@ant-design/icons';
import { sendSms, phoneLogin } from '../api';

const LoginModal = ({ visible, onClose, onLoginSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);

  const handleSendCode = async () => {
    try {
      const phone = form.getFieldValue('phone_number');
      if (!phone) {
        message.error('请输入手机号');
        return;
      }
      
      // 简单的手机号校验
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        message.error('请输入有效的手机号');
        return;
      }
//
      await sendSms({ phone_number: phone });
      message.success('验证码已发送');
      
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
      
    } catch (error) {
      console.error(error);
      message.error('发送失败: ' + (error.response?.data?.error || '网络错误'));
    }
  };

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      const res = await phoneLogin(values);
      
      message.success('登录成功');
      onLoginSuccess(res.data);
      onClose();
    } catch (error) {
      console.error(error);
      message.error('登录失败: ' + (error.response?.data?.error || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="用户登录 / 注册"
      open={visible}
      onCancel={onClose}
      footer={null}
      destroyOnHidden
      centered
    >
      <Form
        form={form}
        name="login_form"
        onFinish={handleSubmit}
        layout="vertical"
        style={{ marginTop: 20 }}
      >
        <Form.Item
          name="phone_number"
          rules={[{ required: true, message: '请输入手机号' }]}
        >
          <Input 
            prefix={<MobileOutlined />} 
            placeholder="手机号码" 
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="code"
          rules={[{ required: true, message: '请输入验证码' }]}
        >
          <div style={{ display: 'flex', gap: 10 }}>
            <Input 
              prefix={<LockOutlined />} 
              placeholder="验证码" 
              size="large"
            />
            <Button 
              size="large" 
              onClick={handleSendCode}
              disabled={countdown > 0}
            >
              {countdown > 0 ? `${countdown}s` : '获取验证码'}
            </Button>
          </div>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block size="large" loading={loading}>
            登录
          </Button>
        </Form.Item>
        
        <div style={{ textAlign: 'center', color: '#999', fontSize: 12 }}>
          未注册的手机号验证后将自动创建账号<br/>
          已在小程序绑定的手机号将自动同步身份
        </div>
      </Form>
    </Modal>
  );
};

export default LoginModal;
