import { useCallback, useEffect, useMemo, useState } from "react"
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Row,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import {
  createAdminTicketDepartment,
  deleteAdminTicketDepartment,
  listAdminTicketDepartments,
  updateAdminTicketDepartment,
  type TicketDepartmentPayload,
} from "../api/tickets"
import type { TicketDepartment } from "../../api/tickets"

const { Title, Paragraph, Text } = Typography
const { TextArea } = Input

interface DepartmentFormValues {
  code?: string
  name: string
  description?: string
  is_enabled: boolean
  sort_order: number
  min_member_level?: number | null
  auto_reply_enabled: boolean
  auto_reply_content?: string
}

function errorDetail(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

export default function AdminTicketDepartments() {
  const [form] = Form.useForm<DepartmentFormValues>()
  const [departments, setDepartments] = useState<TicketDepartment[]>([])
  const [loading, setLoading] = useState(true)
  const [modalOpen, setModalOpen] = useState(false)
  const [editingDepartment, setEditingDepartment] = useState<TicketDepartment | null>(null)
  const [saving, setSaving] = useState(false)

  const loadDepartments = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAdminTicketDepartments()
      setDepartments(res.data ?? [])
    } catch (error) {
      toast.error(errorDetail(error, "工单部门加载失败"))
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadDepartments()
  }, [loadDepartments])

  const openCreate = () => {
    setEditingDepartment(null)
    form.setFieldsValue({
      code: "",
      name: "",
      description: "",
      is_enabled: true,
      sort_order: 0,
      min_member_level: null,
      auto_reply_enabled: false,
      auto_reply_content: "",
    })
    setModalOpen(true)
  }

  const openEdit = useCallback((department: TicketDepartment) => {
    setEditingDepartment(department)
    form.setFieldsValue({
      code: department.code || "",
      name: department.name,
      description: department.description || "",
      is_enabled: department.is_enabled,
      sort_order: department.sort_order,
      min_member_level: department.min_member_level,
      auto_reply_enabled: department.auto_reply_enabled,
      auto_reply_content: department.auto_reply_content || "",
    })
    setModalOpen(true)
  }, [form])

  const handleSave = async () => {
    const values = await form.validateFields()
    const payload: TicketDepartmentPayload = {
      code: values.code?.trim() || null,
      name: values.name.trim(),
      description: values.description?.trim() || null,
      is_enabled: values.is_enabled,
      sort_order: values.sort_order ?? 0,
      min_member_level: values.min_member_level ?? null,
      auto_reply_enabled: values.auto_reply_enabled,
      auto_reply_content: values.auto_reply_content?.trim() || null,
    }
    setSaving(true)
    try {
      if (editingDepartment) {
        await updateAdminTicketDepartment(editingDepartment.id, payload)
        toast.success("工单部门已更新")
      } else {
        await createAdminTicketDepartment(payload)
        toast.success("工单部门已创建")
      }
      setModalOpen(false)
      await loadDepartments()
    } catch (error) {
      toast.error(errorDetail(error, editingDepartment ? "部门更新失败" : "部门创建失败"))
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = useCallback(async (department: TicketDepartment) => {
    try {
      await deleteAdminTicketDepartment(department.id)
      toast.success("工单部门已删除")
      await loadDepartments()
    } catch (error) {
      toast.error(errorDetail(error, "部门删除失败"))
    }
  }, [loadDepartments])

  const columns = useMemo<TableColumnsType<TicketDepartment>>(() => [
    {
      title: "部门",
      dataIndex: "name",
      render: (_: string, record) => (
        <Space orientation="vertical" size={2}>
          <Space>
            <Text strong>{record.name}</Text>
            <Tag color={record.is_enabled ? "green" : "default"}>{record.is_enabled ? "启用" : "停用"}</Tag>
            {record.min_member_level != null && <Tag color="gold">LV{record.min_member_level}+ 可见</Tag>}
            {record.auto_reply_enabled && <Tag color="blue">自动回复</Tag>}
          </Space>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.description || "暂无说明"}</Text>
          {record.code && <Text code style={{ fontSize: 12 }}>{record.code}</Text>}
        </Space>
      ),
    },
    { title: "排序", dataIndex: "sort_order", width: 100 },
    {
      title: "自动回复内容",
      dataIndex: "auto_reply_content",
      ellipsis: true,
      render: (value: string | null) => value || "-",
    },
    {
      title: "操作",
      key: "action",
      width: 180,
      align: "right",
      render: (_: unknown, record) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>编辑</Button>
          <Popconfirm
            title="删除工单部门"
            description="删除后历史工单会保留部门名称快照，确认删除吗？"
            okText="删除"
            cancelText="取消"
            okButtonProps={{ danger: true }}
            onConfirm={() => handleDelete(record)}
          >
            <Button size="small" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [handleDelete, openEdit])

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ margin: 0 }}>工单部门配置</Title>
        <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
          管理前台可选工单部门、启停状态、排序和自动回复模板。
        </Paragraph>
      </div>

      <Card
        variant="outlined"
        title="部门列表"
        extra={<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>新增部门</Button>}
      >
        <Table
          rowKey="id"
          loading={loading}
          dataSource={departments}
          columns={columns}
          pagination={false}
        />
      </Card>

      <Modal
        title={editingDepartment ? "编辑工单部门" : "新增工单部门"}
        open={modalOpen}
        okText={editingDepartment ? "保存" : "创建"}
        cancelText="取消"
        confirmLoading={saving}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        destroyOnHidden
      >
        <Form<DepartmentFormValues> form={form} layout="vertical" style={{ marginTop: 20 }}>
          <Form.Item name="code" label="部门标识">
            <Input placeholder="普通部门可留空，例如 agent_yunqi" />
          </Form.Item>
          <Form.Item name="name" label="部门名称" rules={[{ required: true, message: "请输入部门名称" }]}>
            <Input placeholder="例如：技术支持" />
          </Form.Item>
          <Form.Item name="description" label="部门说明">
            <Input placeholder="用于提示用户应该提交什么问题" />
          </Form.Item>
          <Row gutter={12}>
            <Col span={8}>
              <Form.Item name="sort_order" label="排序">
                <InputNumber min={0} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="is_enabled" label="启用" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="auto_reply_enabled" label="自动回复" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="min_member_level" label="最低可见会员等级">
            <InputNumber min={0} max={99} precision={0} style={{ width: "100%" }} placeholder="留空表示所有用户可见" />
          </Form.Item>
          <Form.Item name="auto_reply_content" label="自动回复内容">
            <TextArea rows={4} maxLength={4000} showCount placeholder="用户创建该部门工单后自动发送的系统回复。" />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
