/** @jsxImportSource react */
import React, { useState } from 'react'
import { useRequest } from './hooks_sys.tsx'
import { Button, Card, Form, Input, Table, message } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { smsApi } from './api/sms.ts'

// 配置JSX运行时
import * as jsxRuntime from 'react/jsx-runtime'
Object.assign(globalThis, {
  React: React,
  ...jsxRuntime
})

interface SmsItem {
  id: string
  phone: string
  content: string
  status: string
  createdAt: string
}

export default function SmsPage() {
  const [form] = Form.useForm()
  const [activeTab, setActiveTab] = useState('send')
  const [password, setPassword] = useState('')

  // 登录状态检查
  const { data: isLoggedIn } = useRequest(() => smsApi.checkLogin(), {
    onError: () => message.error('请先登录短信服务')
  })

  // 发送短信
  const { run: sendSms } = useRequest(
    (values: { phone: string; content: string }) => smsApi.send(values),
    {
      manual: true,
      onSuccess: () => message.success('短信发送任务已创建'),
      onError: () => message.error('短信发送失败')
    }
  )

  // 获取设备状态
  const { data: deviceStatus } = useRequest(() => smsApi.getStatus(), {
    ready: isLoggedIn,
    pollingInterval: 5000
  })

  // 短信记录
  const { data: smsList } = useRequest(() => smsApi.getList(), {
    ready: isLoggedIn,
    pollingInterval: 10000
  })

  // 登录
  const handleLogin = async () => {
    try {
      await smsApi.login({ username: 'vsmsd', password })
      message.success('登录成功')
    } catch (error) {
      message.error('登录失败')
    }
  }

  const columns: ColumnsType<SmsItem> = [
    { title: '任务ID', dataIndex: 'id' },
    { title: '手机号', dataIndex: 'phone' },
    { title: '内容', dataIndex: 'content' },
    { title: '状态', dataIndex: 'status' },
    { title: '发送时间', dataIndex: 'createdAt' }
  ]

  if (!isLoggedIn) {
    return (
      <Card title="短信服务登录">
        <Form layout="vertical">
          <Form.Item label="密码" required>
            <Input.Password 
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入初始密码 Vsmsd123"
            />
          </Form.Item>
          <Button type="primary" onClick={handleLogin}>
            验证登录
          </Button>
        </Form>
      </Card>
    )
  }

  return (
    <Card
      tabList={[
        { key: 'send', tab: '发送短信' },
        { key: 'status', tab: '设备状态' },
        { key: 'history', tab: '发送记录' }
      ]}
      activeTabKey={activeTab}
      onTabChange={setActiveTab}
    >
      {activeTab === 'send' && (
        <Form form={form} onFinish={sendSms}>
          <Form.Item name="phone" label="手机号" rules={[{ required: true }]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="content" label="短信内容" rules={[{ required: true }]}>
            <Input.TextArea rows={4} placeholder="请输入短信内容" />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            发送短信
          </Button>
        </Form>
      )}

      {activeTab === 'status' && deviceStatus && (
        <div>
          <p>信号强度: {deviceStatus.signalStrength}%</p>
          <p>运营商: {deviceStatus.carrier}</p>
          <p>当前模式: {deviceStatus.mode}</p>
        </div>
      )}

      {activeTab === 'history' && (
        <Table<SmsItem>
          columns={columns}
          dataSource={smsList}
          rowKey="id"
          pagination={false}
        />
      )}
    </Card>
  )
}