import { useCallback, useEffect, useState } from "react"
import { DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined } from "@ant-design/icons"
import {
  Button,
  Card,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import {
  createAdminTicketReplyTemplate,
  deleteAdminTicketReplyTemplate,
  listAdminTicketDepartments,
  listAdminTicketReplyTemplates,
  updateAdminTicketReplyTemplate,
  type TicketReplyTemplate,
  type TicketReplyTemplatePayload,
} from "../api/tickets"
import type { TicketDepartment } from "../../api/tickets"
import RichTextContent from "../../components/RichTextContent"
import RichTextEditor from "../../components/RichTextEditor"
import { toast } from "../../utils/toast"
import { isRichTextEmpty, sanitizeRichText } from "../../utils/richText"

const { Title, Paragraph, Text } = Typography

interface FormValues {
  title: string
  content: string
  department_id?: number | null
  is_enabled: boolean
  sort_order: number
}

function formatDate(value?: string | null) {
  if (!value) return "-"
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString("zh-CN", { hour12: false })
}

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

export default function AdminTicketReplyTemplates() {
  const [items, setItems] = useState<TicketReplyTemplate[]>([])
  const [departments, setDepartments] = useState<TicketDepartment[]>([])
  const [loading, setLoading] = useState(true)
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<TicketReplyTemplate | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [form] = Form.useForm<FormValues>()

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [templatesRes, departmentsRes] = await Promise.all([
        listAdminTicketReplyTemplates(),
        listAdminTicketDepartments(),
      ])
      setItems(templatesRes.data ?? [])
      setDepartments(departmentsRes.data ?? [])
    } catch (error) {
      toast.error(errorDetail(error, "回复模板加载失败"))
    } finally {
      setLoading(false)
    }
  }, [])

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

  const openCreate = () => {
    setEditing(null)
    form.resetFields()
    form.setFieldsValue({
      title: "",
      content: "",
      department_id: null,
      is_enabled: true,
      sort_order: 0,
    })
    setModalOpen(true)
  }

  const openEdit = (record: TicketReplyTemplate) => {
    setEditing(record)
    form.setFieldsValue({
      title: record.title,
      content: record.content,
      department_id: record.department_id,
      is_enabled: record.is_enabled,
      sort_order: record.sort_order,
    })
    setModalOpen(true)
  }

  const submit = async () => {
    const values = await form.validateFields()
    const payload: TicketReplyTemplatePayload = {
      title: values.title.trim(),
      content: sanitizeRichText(values.content).trim(),
      department_id: values.department_id ?? null,
      is_enabled: values.is_enabled,
      sort_order: values.sort_order ?? 0,
    }
    setSubmitting(true)
    try {
      if (editing) {
        await updateAdminTicketReplyTemplate(editing.id, payload)
        toast.success("回复模板已更新")
      } else {
        await createAdminTicketReplyTemplate(payload)
        toast.success("回复模板已创建")
      }
      setModalOpen(false)
      await load()
    } catch (error) {
      toast.error(errorDetail(error, "回复模板保存失败"))
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async (record: TicketReplyTemplate) => {
    try {
      await deleteAdminTicketReplyTemplate(record.id)
      toast.success("回复模板已删除")
      await load()
    } catch (error) {
      toast.error(errorDetail(error, "回复模板删除失败"))
    }
  }

  const columns: TableColumnsType<TicketReplyTemplate> = [
    {
      title: "模板",
      dataIndex: "title",
      width: 240,
      render: (_: string, record) => (
        <Space orientation="vertical" size={4}>
          <Text strong>{record.title}</Text>
          <Text type="secondary">使用 {record.usage_count} 次</Text>
        </Space>
      ),
    },
    {
      title: "内容",
      dataIndex: "content",
      render: (value: string) => (
        <div style={{ maxHeight: 72, overflow: "hidden" }}>
          <RichTextContent value={value} admin />
        </div>
      ),
    },
    {
      title: "部门",
      dataIndex: "department_name",
      width: 140,
      render: (value: string | null) => value ? <Tag color="blue">{value}</Tag> : <Tag>全局</Tag>,
    },
    {
      title: "状态",
      dataIndex: "is_enabled",
      width: 100,
      render: (value: boolean) => value ? <Tag color="green">启用</Tag> : <Tag color="default">停用</Tag>,
    },
    {
      title: "排序",
      dataIndex: "sort_order",
      width: 90,
      align: "right",
    },
    {
      title: "更新时间",
      dataIndex: "updated_at",
      width: 180,
      render: formatDate,
    },
    {
      title: "操作",
      key: "action",
      width: 160,
      align: "right",
      render: (_: unknown, record) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="删除回复模板"
            description={`确认删除「${record.title}」吗？`}
            okText="删除"
            cancelText="取消"
            onConfirm={() => handleDelete(record)}
          >
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  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={(
          <Space>
            <Button icon={<ReloadOutlined />} onClick={() => load()} loading={loading}>刷新</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>新增模板</Button>
          </Space>
        )}
      >
        <Table
          rowKey="id"
          loading={loading}
          dataSource={items}
          columns={columns}
          pagination={{ pageSize: 10, showSizeChanger: false }}
        />
      </Card>

      <Modal
        title={editing ? "编辑回复模板" : "新增回复模板"}
        open={modalOpen}
        width={760}
        onCancel={() => setModalOpen(false)}
        onOk={submit}
        confirmLoading={submitting}
        destroyOnHidden
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入模板标题" }]}>
            <Input maxLength={120} showCount placeholder="例如：重启服务器后仍无法访问" />
          </Form.Item>
          <Space size={16} style={{ width: "100%" }} align="start">
            <Form.Item name="department_id" label="适用部门" style={{ width: 260 }}>
              <Select
                allowClear
                placeholder="全局模板"
                options={departments.map((item) => ({ value: item.id, label: item.name }))}
              />
            </Form.Item>
            <Form.Item name="sort_order" label="排序">
              <InputNumber min={0} precision={0} style={{ width: 120 }} />
            </Form.Item>
            <Form.Item name="is_enabled" label="启用" valuePropName="checked">
              <Switch />
            </Form.Item>
          </Space>
          <Form.Item
            name="content"
            label="回复内容"
            rules={[
              {
                validator: async (_, value: string | undefined) => {
                  if (isRichTextEmpty(value)) throw new Error("请输入回复内容")
                  if (sanitizeRichText(value).length > 8000) throw new Error("回复内容过长")
                },
              },
            ]}
          >
            <RichTextEditor placeholder="填写客服常用回复，可使用加粗、列表、链接等格式。" />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
