import { useQuery } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useState } from 'react'

import {
  deleteAdminWorkCategory,
  fetchAdminWorkCategories,
  saveAdminWorkCategory,
} from '@/services/admin'
import type { WorkCategory } from '@/types/worker-platform'

export default function CategoriesPanel() {
  const { message } = App.useApp()
  const [form] = Form.useForm()
  const [editingCategory, setEditingCategory] = useState<WorkCategory | null>(null)
  const [deletingCategory, setDeletingCategory] = useState<WorkCategory | null>(null)
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: () => fetchAdminWorkCategories(),
  })

  async function refreshCategories() {
    await categoriesQuery.refetch()
  }

  function startEdit(category: WorkCategory) {
    setEditingCategory(category)
    form.setFieldsValue({
      categoryKey: category.categoryKey,
      name: category.name,
      sortOrder: category.sortOrder,
      status: category.status,
    })
  }

  function cancelEdit() {
    setEditingCategory(null)
    form.resetFields()
  }

  async function saveCategory(values: {
    categoryKey: string
    name: string
    sortOrder?: number
    status?: string
  }) {
    try {
      await saveAdminWorkCategory(values)
      message.success(editingCategory ? '分类已更新' : '分类已保存')
      cancelEdit()
      await refreshCategories()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    }
  }

  async function toggleCategory(category: WorkCategory) {
    try {
      await saveAdminWorkCategory({
        categoryKey: category.categoryKey,
        name: category.name,
        sortOrder: category.sortOrder,
        status: category.status === 'active' ? 'disabled' : 'active',
      })
      message.success(category.status === 'active' ? '分类已停用' : '分类已启用')
      await refreshCategories()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '操作失败')
    }
  }

  async function submitDelete() {
    if (!deletingCategory) return
    try {
      await deleteAdminWorkCategory(deletingCategory.categoryId)
      message.success('分类已删除')
      setDeletingCategory(null)
      await refreshCategories()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '删除失败')
      setDeletingCategory(null)
    }
  }

  const columns: TableColumnsType<WorkCategory> = [
    { title: '分类', dataIndex: 'name' },
    { title: '标识', dataIndex: 'categoryKey' },
    { title: '排序', dataIndex: 'sortOrder', width: 100 },
    {
      title: '状态',
      width: 120,
      render: (_, row) => (
        <Tag color={row.status === 'active' ? 'green' : 'default'}>
          {row.status === 'active' ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      width: 240,
      render: (_, row) => (
        <Space wrap>
          <Button size="small" onClick={() => startEdit(row)}>
            编辑
          </Button>
          <Button size="small" onClick={() => toggleCategory(row)}>
            {row.status === 'active' ? '停用' : '启用'}
          </Button>
          <Button size="small" danger onClick={() => setDeletingCategory(row)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <section className="platform-panel-stack">
      <Card
        title={editingCategory ? `编辑分类：${editingCategory.name}` : '保存分类'}
        bordered={false}
      >
        <Form
          form={form}
          layout="inline"
          initialValues={{ status: 'active', sortOrder: 100 }}
          onFinish={saveCategory}
        >
          <Form.Item
            label="标识"
            name="categoryKey"
            rules={[{ required: true, message: '请输入标识' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="排序" name="sortOrder">
            <InputNumber min={0} max={9999} />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select
              style={{ width: 110 }}
              options={[
                { value: 'active', label: '启用' },
                { value: 'disabled', label: '停用' },
              ]}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              {editingCategory ? <Button onClick={cancelEdit}>取消</Button> : null}
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card title="分类列表" bordered={false}>
        <Table<WorkCategory>
          rowKey="categoryId"
          loading={categoriesQuery.isLoading}
          dataSource={categoriesQuery.data?.data.items || []}
          columns={columns}
          pagination={false}
        />
      </Card>
      <Modal
        title="删除分类"
        open={Boolean(deletingCategory)}
        onOk={submitDelete}
        onCancel={() => setDeletingCategory(null)}
        okButtonProps={{ danger: true }}
        okText="删除"
        cancelText="取消"
      >
        <Typography.Text>
          确定删除分类「{deletingCategory?.name}
          」？已引用该分类的工单和物品规则将无法删除，需先处理。
        </Typography.Text>
      </Modal>
    </section>
  )
}
