import { useCallback, useEffect, useMemo, useState } from 'react'
import {
  Alert,
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { apiTokenApi, userApi } from '@/lib/api'
import { formatDate } from '@/lib/date'
import type { ApiTokenRecord, UserInfo } from '@/types/system'

export function ApiTokenPage() {
  const [searchForm] = Form.useForm()
  const [issueForm] = Form.useForm()
  const [rows, setRows] = useState<ApiTokenRecord[]>([])
  const [users, setUsers] = useState<UserInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [modalOpen, setModalOpen] = useState(false)
  const [issuedToken, setIssuedToken] = useState<string>('')

  const selectedUser = useMemo(
    () => users.find((item) => item.ID === issueForm.getFieldValue('userId')),
    [issueForm, users],
  )

  const reloadRows = useCallback(async () => {
    setLoading(true)
    try {
      const response = await apiTokenApi.getTokenList({
        page,
        pageSize,
        ...searchForm.getFieldsValue(),
      })
      setRows(response.data.list)
      setTotal(response.data.total)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, searchForm])

  const loadUsers = useCallback(async () => {
    const response = await userApi.getUserList({ page: 1, pageSize: 999 })
    setUsers(response.data.list)
  }, [])

  useEffect(() => {
    reloadRows()
    loadUsers()
  }, [loadUsers, reloadRows])

  const issueToken = async () => {
    const values = await issueForm.validateFields()
    const response = await apiTokenApi.createToken(values)
    setIssuedToken(response.data.token)
    setModalOpen(false)
    issueForm.resetFields()
    message.success('Token 已签发')
    reloadRows()
  }

  const columns: ColumnsType<ApiTokenRecord> = [
    { title: 'ID', dataIndex: 'ID', width: 80 },
    {
      title: '用户',
      width: 220,
      render: (_, record) => `${record.user?.nickName || '-'} (${record.user?.userName || '-'})`,
    },
    { title: '角色 ID', dataIndex: 'authorityId', width: 100 },
    {
      title: '状态',
      width: 100,
      render: (_, record) => <Tag color={record.status ? 'green' : 'red'}>{record.status ? '有效' : '已作废'}</Tag>,
    },
    {
      title: '过期时间',
      width: 180,
      render: (_, record) => formatDate(record.expiresAt),
    },
    { title: '备注', dataIndex: 'remark' },
    {
      title: '操作',
      width: 120,
      render: (_, record) => (
        <Button
          danger
          type="link"
          disabled={!record.status}
          onClick={async () => {
            await apiTokenApi.deleteToken(record.ID)
            message.success('Token 已作废')
            reloadRows()
          }}
        >
          作废
        </Button>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              API Token
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              为指定用户和角色签发临时访问 JWT。
            </Typography.Paragraph>
          </div>
          <Button type="primary" onClick={() => setModalOpen(true)}>
            签发 Token
          </Button>
        </div>
        <Form form={searchForm} layout="vertical" onFinish={() => { setPage(1); reloadRows() }}>
          <Row gutter={16}>
            <Col xs={24} md={8}>
              <Form.Item name="userId" label="用户 ID">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="status" label="状态">
                <Select allowClear options={[{ label: '有效', value: true }, { label: '无效', value: false }]} />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              onClick={() => {
                searchForm.resetFields()
                setPage(1)
                reloadRows()
              }}
            >
              重置
            </Button>
          </Space>
        </Form>
      </Card>
      <Card className="glass-panel page-panel">
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={rows}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          }}
        />
      </Card>

      <Modal open={modalOpen} title="签发 API Token" onCancel={() => setModalOpen(false)} onOk={issueToken}>
        <Form form={issueForm} layout="vertical" initialValues={{ days: 30 }}>
          <Form.Item name="userId" label="用户" rules={[{ required: true, message: '请选择用户' }]}>
            <Select
              options={users.map((user) => ({
                label: `${user.nickName} (${user.userName})`,
                value: user.ID,
              }))}
            />
          </Form.Item>
          <Form.Item name="authorityId" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select
              options={(selectedUser?.authorities || []).map((authority) => ({
                label: `${authority.authorityName} (${authority.authorityId})`,
                value: authority.authorityId,
              }))}
            />
          </Form.Item>
          <Form.Item name="days" label="有效期">
            <Select
              options={[
                { label: '1 天', value: 1 },
                { label: '7 天', value: 7 },
                { label: '30 天', value: 30 },
                { label: '90 天', value: 90 },
                { label: '永久', value: -1 },
              ]}
            />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal open={Boolean(issuedToken)} title="签发结果" footer={null} onCancel={() => setIssuedToken('')}>
        <Alert
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
          message="请立即复制保存。关闭后列表中不会再显示完整 Token。"
        />
        <Input.TextArea value={issuedToken} rows={6} readOnly />
        <Space style={{ marginTop: 12 }}>
          <Button
            onClick={async () => {
              await navigator.clipboard.writeText(issuedToken)
              message.success('Token 已复制')
            }}
          >
            复制
          </Button>
          <Button type="primary" onClick={() => setIssuedToken('')}>
            关闭
          </Button>
        </Space>
      </Modal>
    </div>
  )
}
