import React, { useState } from 'react';
import { Button, Card, Space, Row, Col, Table, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router';

export const SmsModulePage = () => {
  const navigate = useNavigate();
  const [deviceStatus, setDeviceStatus] = useState({
    io_alive: false,
    md_alive: false,
    signal_rate: 0,
    mno: '未知'
  });
  interface TaskStatus {
    id: string;
    status: string;
    result?: string;
    timestamp?: string;
  }

  const [taskStatus, setTaskStatus] = useState<TaskStatus | null>(null);
  const [taskId, setTaskId] = useState<string>('');
  const [phoneNumber, setPhoneNumber] = useState<string>('');
  const [smsContent, setSmsContent] = useState<string>('');

  const fetchDeviceStatus = async () => {
    try {
      const response = await fetch('http://vsmsd:Vsmsd123@52.55.129.63:12080/api/v1/info');
      const data = await response.json();
      setDeviceStatus({
        io_alive: data.io_alive,
        md_alive: data.md_alive,
        signal_rate: data.signal_rate,
        mno: data.mno
      });
      message.success('状态获取成功');
    } catch (error) {
      message.error('状态获取失败');
      console.error('Error fetching device status:', error);
    }
  };

  const sendSms = async () => {
    // 验证手机号码
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      message.error('请输入正确的11位手机号码');
      return;
    }
    
    // 验证短信内容
    if (!smsContent.trim()) {
      message.error('请输入短信内容');
      return;
    }

    try {
      const response = await fetch('http://vsmsd:Vsmsd123@52.55.129.63:12080/api/v1/sms', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          method: 'send_sms',
          number: phoneNumber,
          content: smsContent
        })
      });
      
      const data = await response.json();
      setTaskId(data.task_id);
      message.success('短信发送成功');
    } catch (error) {
      message.error('短信发送失败');
      console.error('Error sending SMS:', error);
    }
  };

  const fetchTaskStatus = async (taskId: string) => {
    try {
      const response = await fetch(`http://vsmsd:Vsmsd123@52.55.129.63:12080/api/v1/task/${taskId}`);
      const data = await response.json();
      setTaskStatus(data);
      message.success('任务状态获取成功');
    } catch (error) {
      message.error('任务状态获取失败');
      console.error('Error fetching task status:', error);
    }
  };

  return (
    <div className="p-4">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold">短信模块管理</h1>
      </div>

      <Row gutter={16}>
        <Col span={24}>
          <Card title="功能测试面板" className="mb-4">
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Row gutter={16}>
                <Col span={12}>
                  <Card title="设备状态">
                    <p>信号强度: {deviceStatus.signal_rate}%</p>
                    <p>运营商: {deviceStatus.mno}</p>
                    <p>4G模块: {deviceStatus.md_alive ? '在线' : '离线'}</p>
                    <Button 
                      type="primary" 
                      onClick={fetchDeviceStatus}
                      style={{ marginTop: 16 }}
                    >
                      获取状态
                    </Button>
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="模式选择">
                    <Space>
                      <Button type="primary">短信</Button>
                      <Button>电话</Button>
                      <Button>语音</Button>
                      <Button>余额查询</Button>
                      <Button>测试</Button>
                    </Space>
                  </Card>
                </Col>
              </Row>
              
              <Card title="短信测试">
                <Form layout="vertical">
                  <Form.Item label="号码" required>
                    <Input
                      placeholder="请输入11位手机号码"
                      value={phoneNumber}
                      onChange={(e) => setPhoneNumber(e.target.value)}
                    />
                  </Form.Item>
                  <Form.Item label="内容" required>
                    <Input.TextArea
                      rows={4}
                      placeholder="请输入短信内容"
                      value={smsContent}
                      onChange={(e) => setSmsContent(e.target.value)}
                    />
                  </Form.Item>
                  <Form.Item label="任务ID">
                    <Space.Compact style={{ width: '100%' }}>
                      <Input
                        placeholder="可手动输入或自动生成"
                        value={taskId}
                        onChange={(e) => setTaskId(e.target.value)}
                      />
                      <Button
                        onClick={() => setTaskId(`TASK_${Date.now()}`)}
                      >
                        自动生成
                      </Button>
                      <Button
                        onClick={() => setTaskId('')}
                      >
                        重置
                      </Button>
                    </Space.Compact>
                  </Form.Item>
                  <Space>
                    <Button
                      type="primary"
                      onClick={sendSms}
                    >
                      发送短信
                    </Button>
                    <Button
                      type="default"
                      onClick={() => fetchTaskStatus(taskId)}
                      disabled={!taskId}
                    >
                      获取任务状态
                    </Button>
                  </Space>
                </Form>
              </Card>
              
              <Card title="执行信息">
                <Table
                  columns={[
                    { title: '序列号', dataIndex: 'id', key: 'id' },
                    { title: '运营商', dataIndex: 'carrier', key: 'carrier' },
                    { title: '时间', dataIndex: 'time', key: 'time' },
                    { title: '结果', dataIndex: 'result', key: 'result' }
                  ]}
                  dataSource={[]}
                  size="small"
                />
              </Card>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};