import { useCallback, useEffect, useMemo, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Drawer,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { apiRegistryApi, authorityApi } from '@/lib/api'
import { flattenAuthorities } from '@/lib/tree'
import type { ApiRecord, Authority } from '@/types/system'

const methodOptions = ['GET', 'POST', 'PUT', 'DELETE']

export function ApiManagementPage() {
  const [searchForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [apis, setApis] = useState<ApiRecord[]>([])
  const [roles, setRoles] = useState<Authority[]>([])
  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 [saving, setSaving] = useState(false)
  const [editingApi, setEditingApi] = useState<ApiRecord | null>(null)
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [activeApi, setActiveApi] = useState<ApiRecord | null>(null)
  const [selectedRoles, setSelectedRoles] = useState<number[]>([])
  const [savingRoles, setSavingRoles] = useState(false)

  const roleOptions = useMemo(
    () =>
      flattenAuthorities(roles).map((item) => ({
        label: `${'　'.repeat(item.depth)}${item.authorityName} (${item.authorityId})`,
        value: item.authorityId,
      })),
    [roles],
  )

  const apiGroupOptions = useMemo(
    () =>
      Array.from(new Set(apis.map((item) => item.apiGroup)))
        .filter(Boolean)
        .map((group) => ({
          label: group,
          value: group,
        })),
    [apis],
  )

  const reloadApis = useCallback(async () => {
    setLoading(true)
    try {
      const [apiRes, roleRes] = await Promise.all([
        apiRegistryApi.getApiList({
          page,
          pageSize,
          ...searchForm.getFieldsValue(),
        }),
        authorityApi.getAuthorityList(),
      ])
      setApis(apiRes.data.list)
      setTotal(apiRes.data.total)
      setRoles(roleRes.data)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, searchForm])

  useEffect(() => {
    reloadApis()
  }, [reloadApis])

  const openCreate = () => {
    setEditingApi(null)
    editForm.resetFields()
    editForm.setFieldsValue({ method: 'POST' })
    setModalOpen(true)
  }

  const openEdit = async (record: ApiRecord) => {
    const response = await apiRegistryApi.getApiById(record.ID)
    setEditingApi(response.data.api)
    editForm.setFieldsValue(response.data.api)
    setModalOpen(true)
  }

  const saveApi = async () => {
    const values = await editForm.validateFields()
    setSaving(true)
    try {
      if (editingApi) {
        await apiRegistryApi.updateApi({
          ID: editingApi.ID,
          ...values,
        })
        message.success('接口已更新')
      } else {
        await apiRegistryApi.createApi(values)
        message.success('接口已创建')
      }
      setModalOpen(false)
      reloadApis()
    } finally {
      setSaving(false)
    }
  }

  const deleteApi = (record: ApiRecord) => {
    Modal.confirm({
      title: `删除接口 ${record.path}`,
      okButtonProps: { danger: true },
      onOk: async () => {
        await apiRegistryApi.deleteApi({ ID: record.ID })
        message.success('接口已删除')
        reloadApis()
      },
    })
  }

  const openRoleDrawer = async (record: ApiRecord) => {
    const response = await apiRegistryApi.getApiRoles(record.path, record.method)
    setActiveApi(record)
    setSelectedRoles(response.data)
    setDrawerOpen(true)
  }

  const saveRoles = async () => {
    if (!activeApi) {
      return
    }
    setSavingRoles(true)
    try {
      await apiRegistryApi.setApiRoles({
        path: activeApi.path,
        method: activeApi.method,
        authorityIds: selectedRoles,
      })
      message.success('接口角色关系已更新')
      setDrawerOpen(false)
    } finally {
      setSavingRoles(false)
    }
  }

  const columns: ColumnsType<ApiRecord> = [
    { title: 'ID', dataIndex: 'ID', width: 80 },
    { title: '路径', dataIndex: 'path', width: 260 },
    { title: '分组', dataIndex: 'apiGroup', width: 160 },
    { title: '描述', dataIndex: 'description', width: 240 },
    {
      title: '方法',
      dataIndex: 'method',
      width: 100,
      render: (value: string) => <Tag color={value === 'GET' ? 'blue' : value === 'POST' ? 'green' : value === 'PUT' ? 'orange' : 'red'}>{value}</Tag>,
    },
    {
      title: '操作',
      key: 'actions',
      width: 220,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Button type="link" onClick={() => openRoleDrawer(record)}>
            分配角色
          </Button>
          <Button danger type="link" onClick={() => deleteApi(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              API 管理
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页覆盖接口目录、接口元数据和接口角色关系。
            </Typography.Paragraph>
          </div>
          <Space>
            <Button
              onClick={async () => {
                await apiRegistryApi.freshCasbin()
                message.success('Casbin 缓存已刷新')
              }}
            >
              刷新 Casbin
            </Button>
            <Button type="primary" onClick={openCreate}>
              新建接口
            </Button>
          </Space>
        </div>
        <Form form={searchForm} layout="vertical" onFinish={() => { setPage(1); reloadApis() }}>
          <Row gutter={[16, 0]}>
            <Col xs={24} md={8}>
              <Form.Item name="path" label="路径">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="description" label="描述">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="apiGroup" label="分组">
                <Select allowClear options={apiGroupOptions} />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="method" label="方法">
                <Select allowClear options={methodOptions.map((item) => ({ label: item, value: item }))} />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              onClick={() => {
                searchForm.resetFields()
                setPage(1)
                reloadApis()
              }}
            >
              重置
            </Button>
          </Space>
        </Form>
      </Card>
      <Card className="glass-panel page-panel">
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={apis}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          }}
        />
      </Card>

      <Modal
        open={modalOpen}
        title={editingApi ? '编辑接口' : '新建接口'}
        onCancel={() => setModalOpen(false)}
        onOk={saveApi}
        confirmLoading={saving}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="path" label="路径" rules={[{ required: true, message: '请输入路径' }]}>
            <Input placeholder="/api/example" />
          </Form.Item>
          <Form.Item name="description" label="描述" rules={[{ required: true, message: '请输入描述' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="apiGroup" label="分组" rules={[{ required: true, message: '请输入分组' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="method" label="方法" rules={[{ required: true, message: '请选择方法' }]}>
            <Select options={methodOptions.map((item) => ({ label: item, value: item }))} />
          </Form.Item>
        </Form>
      </Modal>

      <Drawer
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        title={activeApi ? `接口角色分配 · ${activeApi.path}` : '接口角色分配'}
        width={520}
        extra={
          <Button type="primary" loading={savingRoles} onClick={saveRoles}>
            保存
          </Button>
        }
      >
        <Select
          mode="multiple"
          style={{ width: '100%' }}
          value={selectedRoles}
          options={roleOptions}
          onChange={setSelectedRoles}
        />
      </Drawer>
    </div>
  )
}
