import { useCallback, useEffect, useState } from "react"
import {
  Button,
  Card,
  Empty,
  Form,
  Input,
  Modal,
  Radio,
  Select,
  Space,
  Table,
  Tag,
  Typography,
  message,
  type TableColumnsType,
} from "antd"
import { DeleteOutlined, PlusOutlined, ReloadOutlined } from "@ant-design/icons"
import {
  broadcastNotification,
  createAnnouncement,
  deleteAnnouncement,
  listAnnouncements,
  type AdminAnnouncement,
} from "../api/announcement"
import RichTextEditor from "../../components/RichTextEditor"
import RichTextContent from "../../components/RichTextContent"

const { Text, Title, Paragraph } = Typography

const CATEGORY_OPTIONS = [
  { value: "announcement", label: "公告" },
  { value: "promotion", label: "活动" },
  { value: "system", label: "系统" },
]

const NOTIFICATION_CATEGORY_OPTIONS = [
  { value: "system", label: "系统" },
  { value: "order", label: "订单" },
  { value: "instance", label: "服务器" },
  { value: "finance", label: "财务" },
  { value: "ticket", label: "工单" },
  { value: "promotion", label: "推广" },
  { value: "membership", label: "会员" },
]

const LEVEL_OPTIONS = [
  { value: "info", label: "普通" },
  { value: "success", label: "成功" },
  { value: "warning", label: "提醒" },
  { value: "error", label: "异常" },
  { value: "urgent", label: "紧急" },
]

const CATEGORY_LABEL: Record<string, string> = {
  announcement: "公告",
  promotion: "活动",
  system: "系统",
}

interface FormValues {
  title: string
  category: string
  target_type: "all" | "specific"
  target_user_ids?: string
  content: string
}

interface BroadcastFormValues {
  title: string
  content: string
  category: string
  level: "info" | "success" | "warning" | "error" | "urgent"
  target_type: "all" | "specific" | "role" | "member_level" | "agent"
  target_user_ids?: string
  target_role?: "user" | "admin" | "super_admin"
  target_member_level_ids?: string
  active_agents_only?: boolean
  action_label?: string
  action_url?: string
}

function formatTime(value: string | null) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

export default function AdminAnnouncements() {
  const [items, setItems] = useState<AdminAnnouncement[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const [modalOpen, setModalOpen] = useState(false)
  const [broadcastOpen, setBroadcastOpen] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [broadcastSubmitting, setBroadcastSubmitting] = useState(false)
  const [viewing, setViewing] = useState<AdminAnnouncement | null>(null)
  const [form] = Form.useForm<FormValues>()
  const [broadcastForm] = Form.useForm<BroadcastFormValues>()
  const targetType = Form.useWatch("target_type", form)
  const broadcastTargetType = Form.useWatch("target_type", broadcastForm)

  const PAGE_SIZE = 10

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await listAnnouncements({ limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE })
      setItems(data.items)
      setTotal(data.total)
    } catch {
      message.error("加载公告失败")
    } finally {
      setLoading(false)
    }
  }, [page])

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

  const openCreate = () => {
    form.resetFields()
    form.setFieldsValue({ category: "announcement", target_type: "all", content: "" })
    setModalOpen(true)
  }

  const openBroadcast = () => {
    broadcastForm.resetFields()
    broadcastForm.setFieldsValue({
      category: "system",
      level: "info",
      target_type: "all",
      active_agents_only: true,
    })
    setBroadcastOpen(true)
  }

  const submit = async () => {
    try {
      const values = await form.validateFields()
      setSubmitting(true)
      let targetIds: number[] | null = null
      if (values.target_type === "specific") {
        targetIds = (values.target_user_ids || "")
          .split(/[,，\s]+/)
          .map((s) => Number(s.trim()))
          .filter((n) => Number.isFinite(n) && n > 0)
        if (targetIds.length === 0) {
          message.error("请填写至少一个有效的用户ID")
          setSubmitting(false)
          return
        }
      }
      await createAnnouncement({
        title: values.title,
        content: values.content,
        category: values.category,
        target_type: values.target_type,
        target_user_ids: targetIds,
      })
      message.success("公告已发布")
      setModalOpen(false)
      await load()
    } catch (err: unknown) {
      if (err && typeof err === "object" && "errorFields" in err) return
      const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "发布失败")
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = (record: AdminAnnouncement) => {
    Modal.confirm({
      title: "删除公告？",
      okText: "确认删除",
      cancelText: "取消",
      okButtonProps: { danger: true },
      content: <Text>公告「{record.title}」将被删除，已读记录一并清除。</Text>,
      onOk: async () => {
        try {
          await deleteAnnouncement(record.id)
          message.success("已删除")
          await load()
        } catch {
          message.error("删除失败")
        }
      },
    })
  }

  const parseIds = (value?: string) => (value || "")
    .split(/[,，\s]+/)
    .map((s) => Number(s.trim()))
    .filter((n) => Number.isFinite(n) && n > 0)

  const submitBroadcast = async () => {
    try {
      const values = await broadcastForm.validateFields()
      const targetUserIds = values.target_type === "specific" ? parseIds(values.target_user_ids) : null
      const targetMemberLevelIds = values.target_type === "member_level" ? parseIds(values.target_member_level_ids) : null
      const payload = {
        title: values.title,
        content: values.content,
        category: values.category,
        level: values.level,
        target_type: values.target_type,
        target_user_ids: targetUserIds,
        target_role: values.target_type === "role" ? values.target_role : null,
        target_member_level_ids: targetMemberLevelIds,
        active_agents_only: values.active_agents_only ?? true,
        action_label: values.action_label || null,
        action_url: values.action_url || null,
      }
      if (values.target_type === "specific" && targetUserIds?.length === 0) {
        message.error("请填写至少一个有效用户ID")
        return
      }
      if (values.target_type === "member_level" && targetMemberLevelIds?.length === 0) {
        message.error("请填写至少一个会员等级ID")
        return
      }
      setBroadcastSubmitting(true)
      const res = await broadcastNotification(payload)
      message.success(`已发送 ${res.sent} 条站内信，匹配 ${res.matched} 个用户`)
      setBroadcastOpen(false)
    } catch (err: unknown) {
      if (err && typeof err === "object" && "errorFields" in err) return
      const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "群发失败")
    } finally {
      setBroadcastSubmitting(false)
    }
  }

  const columns: TableColumnsType<AdminAnnouncement> = [
    {
      title: "标题",
      dataIndex: "title",
      render: (value: string, record) => (
        <Button type="link" style={{ padding: 0 }} onClick={() => setViewing(record)}>{value}</Button>
      ),
    },
    {
      title: "分类",
      dataIndex: "category",
      width: 90,
      render: (value: string) => <Tag>{CATEGORY_LABEL[value] ?? value}</Tag>,
    },
    {
      title: "目标",
      dataIndex: "target_type",
      width: 150,
      render: (value: string, record) =>
        value === "all"
          ? <Tag color="green">全站</Tag>
          : <Tag color="blue">指定 {record.target_user_ids?.length ?? 0} 人</Tag>,
    },
    {
      title: "发布时间",
      dataIndex: "published_at",
      width: 170,
      render: (value: string | null, record) => (
        <Text type="secondary">{formatTime(value || record.created_at)}</Text>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 90,
      render: (_, record) => (
        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
          删除
        </Button>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={16} style={{ width: "100%" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
        <div>
          <Title level={3} style={{ marginBottom: 4 }}>公告管理</Title>
          <Paragraph type="secondary" style={{ marginBottom: 0 }}>
            发布全站或指定用户公告，用户在站内信「系统公告」中查看。
          </Paragraph>
        </div>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>
          <Button onClick={openBroadcast}>群发站内信</Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>发布公告</Button>
        </Space>
      </div>

      <Card variant="outlined">
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={items}
          pagination={{
            current: page,
            pageSize: PAGE_SIZE,
            total,
            showSizeChanger: false,
            onChange: setPage,
          }}
          locale={{ emptyText: <Empty description="暂无公告" /> }}
        />
      </Card>

      <Modal
        title="发布公告"
        open={modalOpen}
        onOk={submit}
        onCancel={() => setModalOpen(false)}
        confirmLoading={submitting}
        width={760}
        style={{ maxWidth: "94vw" }}
        okText="发布"
        cancelText="取消"
        destroyOnHidden
      >
        <Form form={form} layout="vertical" style={{ marginTop: 12 }}>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入标题" }, { max: 128 }]}>
            <Input placeholder="公告标题" maxLength={128} />
          </Form.Item>
          <Space size={16} style={{ width: "100%" }} align="start">
            <Form.Item name="category" label="分类" style={{ minWidth: 160 }}>
              <Select options={CATEGORY_OPTIONS} />
            </Form.Item>
            <Form.Item name="target_type" label="发送对象">
              <Radio.Group>
                <Radio.Button value="all">全站</Radio.Button>
                <Radio.Button value="specific">指定用户</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Space>
          {targetType === "specific" && (
            <Form.Item
              name="target_user_ids"
              label="用户ID列表"
              rules={[{ required: true, message: "请输入用户ID（逗号分隔）" }]}
              extra="多个用户ID用逗号分隔，例如：1,2,3"
            >
              <Input placeholder="1,2,3" />
            </Form.Item>
          )}
          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: "请输入公告内容" }]}
          >
            <RichTextEditor />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="群发站内信"
        open={broadcastOpen}
        onOk={submitBroadcast}
        onCancel={() => setBroadcastOpen(false)}
        confirmLoading={broadcastSubmitting}
        width={760}
        style={{ maxWidth: "94vw" }}
        okText="发送"
        cancelText="取消"
        destroyOnHidden
      >
        <Form form={broadcastForm} layout="vertical" style={{ marginTop: 12 }}>
          <Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入标题" }, { max: 128 }]}>
            <Input placeholder="站内信标题" maxLength={128} />
          </Form.Item>
          <Space size={16} style={{ width: "100%" }} align="start" wrap>
            <Form.Item name="category" label="分类" style={{ minWidth: 160 }}>
              <Select options={NOTIFICATION_CATEGORY_OPTIONS} />
            </Form.Item>
            <Form.Item name="level" label="等级" style={{ minWidth: 160 }}>
              <Select options={LEVEL_OPTIONS} />
            </Form.Item>
            <Form.Item name="target_type" label="发送对象">
              <Radio.Group>
                <Radio.Button value="all">全站</Radio.Button>
                <Radio.Button value="specific">指定用户</Radio.Button>
                <Radio.Button value="role">角色</Radio.Button>
                <Radio.Button value="member_level">会员等级</Radio.Button>
                <Radio.Button value="agent">代理</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Space>
          {broadcastTargetType === "specific" && (
            <Form.Item
              name="target_user_ids"
              label="用户ID列表"
              rules={[{ required: true, message: "请输入用户ID（逗号分隔）" }]}
              extra="多个用户ID用逗号分隔，例如：1,2,3"
            >
              <Input placeholder="1,2,3" />
            </Form.Item>
          )}
          {broadcastTargetType === "role" && (
            <Form.Item name="target_role" label="角色" rules={[{ required: true, message: "请选择角色" }]}>
              <Select
                options={[
                  { value: "user", label: "普通用户" },
                  { value: "admin", label: "管理员" },
                  { value: "super_admin", label: "超级管理员" },
                ]}
              />
            </Form.Item>
          )}
          {broadcastTargetType === "member_level" && (
            <Form.Item
              name="target_member_level_ids"
              label="会员等级ID列表"
              rules={[{ required: true, message: "请输入会员等级ID（逗号分隔）" }]}
              extra="多个等级ID用逗号分隔，例如：1,2,3"
            >
              <Input placeholder="1,2,3" />
            </Form.Item>
          )}
          {broadcastTargetType === "agent" && (
            <Form.Item name="active_agents_only" label="代理范围">
              <Radio.Group>
                <Radio.Button value={true}>仅有效代理</Radio.Button>
                <Radio.Button value={false}>全部代理记录</Radio.Button>
              </Radio.Group>
            </Form.Item>
          )}
          <Form.Item name="content" label="内容" rules={[{ required: true, message: "请输入站内信内容" }]}>
            <Input.TextArea placeholder="站内信内容" rows={5} showCount maxLength={2000} />
          </Form.Item>
          <Space size={16} style={{ width: "100%" }} align="start">
            <Form.Item name="action_label" label="操作按钮文案" style={{ flex: 1 }}>
              <Input placeholder="例如：查看订单" maxLength={40} />
            </Form.Item>
            <Form.Item name="action_url" label="操作跳转地址" style={{ flex: 1 }}>
              <Input placeholder="/orders/123" maxLength={256} />
            </Form.Item>
          </Space>
        </Form>
      </Modal>

      <Modal
        open={!!viewing}
        title={viewing?.title}
        footer={<Button type="primary" onClick={() => setViewing(null)}>关闭</Button>}
        onCancel={() => setViewing(null)}
        width={760}
        style={{ maxWidth: "94vw" }}
        destroyOnHidden
      >
        {viewing && <RichTextContent value={viewing.content} admin />}
      </Modal>
    </Space>
  )
}
