import { useCallback, useEffect, useState } from "react"
import {
  CalendarOutlined,
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  ReloadOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Divider,
  Empty,
  Form,
  Image,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
  message,
  type TableColumnsType,
} from "antd"
import RichTextEditor from "../../components/RichTextEditor"
import {
  createActivity,
  deleteActivity,
  getActivityOptions,
  listActivities,
  updateActivity,
  type ActivityOptions,
  type ActivityPayload,
  type ActivityProduct,
  type ActivityStatus,
  type AdminActivity,
} from "../api/activity"
import { isCommercialError } from "../api/client"

const { Text, Title } = Typography
const PAGE_SIZE = 20

interface ActivityFormValues extends Omit<ActivityPayload, "starts_at" | "ends_at"> {
  title: string
  description: string
  limited_time: boolean
  starts_at?: string
  ends_at?: string
  is_published: boolean
  is_featured: boolean
  show_on_home: boolean
  sort_order: number
  products: ActivityProduct[]
}

const STATUS_META: Record<ActivityStatus, { color: string; label: string }> = {
  draft: { color: "default", label: "未发布" },
  upcoming: { color: "blue", label: "活动预告" },
  ongoing: { color: "green", label: "正在进行" },
  ended: { color: "red", label: "已结束" },
}

const TEMPLATE_OPTIONS = [
  { value: "standard", label: "标准活动" },
  { value: "product_grid", label: "商品矩阵" },
  { value: "flash_sale", label: "限时抢购" },
  { value: "coupon", label: "优惠码专题" },
]

const PARTICIPATION_OPTIONS = [
  { value: "direct", label: "直接参与" },
  { value: "existing_discount", label: "沿用商品已有折扣" },
  { value: "promo_code", label: "使用优惠码" },
  { value: "activity_price", label: "使用活动专享价" },
]

const AUDIENCE_OPTIONS = [
  { value: "all", label: "全部用户" },
  { value: "new_user", label: "仅新用户" },
  { value: "member", label: "仅会员" },
  { value: "agent", label: "仅代理用户" },
]

const CYCLE_OPTIONS = [
  ["hourly", "小时"], ["daily", "天"], ["monthly", "月付"], ["quarterly", "季付"],
  ["semi_annually", "半年付"], ["annually", "年付"], ["biennially", "两年付"],
  ["triennially", "三年付"], ["one_time", "一次性"],
].map(([value, label]) => ({ value, label }))

function toLocalInput(value: string | null | undefined) {
  if (!value) return undefined
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return undefined
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
  return local.toISOString().slice(0, 16)
}

function toIso(value: string | undefined) {
  if (!value) return null
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? null : date.toISOString()
}

function formatTime(value: string | null) {
  return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "-"
}

function requestError(error: unknown, fallback: string) {
  const detail = (error as { response?: { data?: { detail?: unknown; message?: unknown } } })?.response?.data
  return typeof detail?.detail === "string" ? detail.detail : typeof detail?.message === "string" ? detail.message : fallback
}

export default function AdminActivities() {
  const [form] = Form.useForm<ActivityFormValues>()
  const [items, setItems] = useState<AdminActivity[]>([])
  const [options, setOptions] = useState<ActivityOptions>({ products: [], promo_codes: [] })
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<AdminActivity | null>(null)
	const [productsTouched, setProductsTouched] = useState(false)
  const [keyword, setKeyword] = useState("")
  const [published, setPublished] = useState<boolean | "all">("all")
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const limitedTime = Form.useWatch("limited_time", form)
  const participationMode = Form.useWatch("participation_mode", form)
	const watchedProducts = Form.useWatch("products", form)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const data = await listActivities({ keyword: keyword.trim() || undefined, published, offset: (page - 1) * PAGE_SIZE, limit: PAGE_SIZE })
      setItems(data.items)
      setTotal(data.total)
    } catch (error) {
      if (!isCommercialError(error)) message.error(requestError(error, "加载活动失败"))
    } finally {
      setLoading(false)
    }
  }, [keyword, page, published])

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

  const loadOptions = async () => {
    try {
      setOptions(await getActivityOptions())
    } catch (error) {
      message.error(requestError(error, "加载商品和优惠码失败"))
    }
  }

  const defaults: Partial<ActivityFormValues> = {
    template_key: "standard", participation_mode: "direct", audience: "all", button_text: "立即参与",
    limited_time: true, is_published: true, is_featured: false, show_on_home: true,
    per_user_limit: 0, total_limit: 0, sort_order: 0, products: [],
  }

  const openCreate = () => {
    setEditing(null)
	setProductsTouched(false)
    form.resetFields()
    form.setFieldsValue(defaults)
    setModalOpen(true)
    void loadOptions()
  }

  const openEdit = (record: AdminActivity) => {
    setEditing(record)
	setProductsTouched(false)
    form.resetFields()
    form.setFieldsValue({
      ...record,
      subtitle: record.subtitle ?? undefined,
      content: record.content ?? undefined,
      image_url: record.image_url ?? undefined,
      banner_url: record.banner_url ?? undefined,
      target_url: record.target_url ?? undefined,
      label: record.label ?? undefined,
      rules: record.rules ?? undefined,
      promo_code_id: record.promo_code_id ?? undefined,
      starts_at: toLocalInput(record.starts_at),
      ends_at: toLocalInput(record.ends_at),
      products: record.products ?? [],
    })
    setModalOpen(true)
    void loadOptions()
  }

  const save = async () => {
    try {
      const values = await form.validateFields()
	  const { products: submittedProducts, ...activityValues } = values
      const payload: ActivityPayload = {
		...activityValues,
        title: values.title.trim(),
        subtitle: values.subtitle?.trim() || null,
        description: values.description.trim(),
        content: values.content?.trim() || null,
        image_url: values.image_url?.trim() || null,
        banner_url: values.banner_url?.trim() || null,
        target_url: values.target_url?.trim() || null,
        label: values.label?.trim() || null,
        button_text: values.button_text?.trim() || "立即参与",
        rules: values.rules?.trim() || null,
        promo_code_id: values.participation_mode === "promo_code" ? values.promo_code_id : null,
        starts_at: values.limited_time ? toIso(values.starts_at) : null,
        ends_at: values.limited_time ? toIso(values.ends_at) : null,
	  }
	  if (!editing || productsTouched) {
		payload.products = (submittedProducts ?? []).map((product, index) => ({
          ...product,
          section_name: product.section_name?.trim() || "精选产品",
          section_description: product.section_description?.trim() || null,
          custom_label: product.custom_label?.trim() || null,
          product_description: product.product_description?.trim() || null,
          billing_cycle: product.billing_cycle || null,
          activity_price: values.participation_mode === "activity_price" ? product.activity_price : null,
          discount_percent: values.participation_mode === "existing_discount" ? product.discount_percent : null,
          stock_limit: product.stock_limit ?? 0,
          per_user_limit: product.per_user_limit ?? 0,
          sort_order: product.sort_order ?? index,
		}))
		payload.replace_products = true
      }
      if (payload.starts_at && payload.ends_at && payload.starts_at >= payload.ends_at) {
        message.error("结束时间必须晚于开始时间")
        return
      }
      setSaving(true)
      if (editing) {
        await updateActivity(editing.id, payload)
        message.success("活动已更新")
      } else {
        await createActivity(payload)
        message.success("活动已创建")
      }
      setModalOpen(false)
      await load()
    } catch (error) {
      if (error && typeof error === "object" && "errorFields" in error) return
      message.error(requestError(error, "保存活动失败"))
    } finally {
      setSaving(false)
    }
  }

  const togglePublished = async (record: AdminActivity) => {
    try {
      await updateActivity(record.id, { is_published: !record.is_published })
      message.success(record.is_published ? "活动已下线" : "活动已发布")
      await load()
    } catch (error) {
      message.error(requestError(error, "更新发布状态失败"))
    }
  }

  const remove = (record: AdminActivity) => Modal.confirm({
    title: `删除活动「${record.title}」？`, content: "活动商品配置也会一并删除。", okText: "删除", cancelText: "取消",
    okButtonProps: { danger: true },
    onOk: async () => {
      try { await deleteActivity(record.id); message.success("活动已删除"); await load() }
      catch (error) { message.error(requestError(error, "删除活动失败")) }
    },
  })

  const columns: TableColumnsType<AdminActivity> = [
    {
      title: "活动", key: "activity", width: 390,
      render: (_, record) => (
        <Space size={14} align="start">
          {record.image_url ? <Image src={record.image_url} width={104} height={58} style={{ objectFit: "cover" }} /> : (
            <span style={{ width: 104, height: 58, display: "flex", alignItems: "center", justifyContent: "center", background: "#f5f7fa", color: "#bfbfbf" }}><CalendarOutlined style={{ fontSize: 24 }} /></span>
          )}
          <Space orientation="vertical" size={1}>
            <Space wrap size={6}><Text strong>{record.title}</Text>{record.label && <Tag color="orange">{record.label}</Tag>}</Space>
            <Text type="secondary" ellipsis style={{ maxWidth: 235, fontSize: 12 }}>{record.description}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>{TEMPLATE_OPTIONS.find((item) => item.value === record.template_key)?.label} · {record.products?.length ?? 0} 个商品</Text>
          </Space>
        </Space>
      ),
    },
    { title: "参与方式", dataIndex: "participation_mode", width: 160, render: (value) => PARTICIPATION_OPTIONS.find((item) => item.value === value)?.label ?? value },
    {
      title: "活动时间", key: "time", width: 220,
      render: (_, record) => record.limited_time ? <Space orientation="vertical" size={0}><Text type="secondary" style={{ fontSize: 12 }}>开始：{formatTime(record.starts_at)}</Text><Text type="secondary" style={{ fontSize: 12 }}>结束：{formatTime(record.ends_at)}</Text></Space> : <Tag>长期有效</Tag>,
    },
    { title: "状态", dataIndex: "status", width: 110, render: (value: ActivityStatus) => <Tag color={STATUS_META[value]?.color}>{STATUS_META[value]?.label}</Tag> },
    { title: "发布", dataIndex: "is_published", width: 80, render: (value: boolean, record) => <Switch checked={value} onChange={() => void togglePublished(record)} /> },
    {
      title: "操作", key: "actions", width: 240, align: "right",
      render: (_, record) => <Space size={8}><Button size="small" icon={<EyeOutlined />} href={`/activities/${record.id}`} target="_blank">预览</Button><Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>编辑</Button><Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(record)}>删除</Button></Space>,
    },
  ]

  const productOptions = options.products.map((product) => ({
    value: product.id,
    label: `${product.category_name ? `${product.category_name} / ` : ""}${product.group_name ? `${product.group_name} / ` : ""}${product.name} (${product.sku})${product.status !== "active" ? " [未上架]" : ""}`,
  }))

  const modalTabs = [
    {
      key: "basic", label: "基本信息", children: (
        <>
          <Row gutter={16}><Col xs={24} md={17}><Form.Item name="title" label="活动标题" rules={[{ required: true, whitespace: true, message: "请输入活动标题" }, { max: 128 }]}><Input maxLength={128} showCount /></Form.Item></Col><Col xs={24} md={7}><Form.Item name="label" label="活动标签" rules={[{ max: 32 }]}><Input placeholder="限时特惠" maxLength={32} /></Form.Item></Col></Row>
          <Form.Item name="subtitle" label="活动副标题" rules={[{ max: 255 }]}><Input maxLength={255} /></Form.Item>
          <Form.Item name="description" label="列表摘要" rules={[{ required: true, whitespace: true }, { max: 2000 }]}><Input.TextArea rows={3} maxLength={2000} showCount /></Form.Item>
          <Row gutter={16}><Col xs={24} md={12}><Form.Item name="image_url" label="列表封面" rules={[{ max: 500 }]}><Input placeholder="/activity/cover.jpg" /></Form.Item></Col><Col xs={24} md={12}><Form.Item name="banner_url" label="详情横幅" rules={[{ max: 500 }]}><Input placeholder="/activity/banner.jpg" /></Form.Item></Col></Row>
          <Form.Item name="content" label="活动详情"><RichTextEditor placeholder="填写活动介绍、权益说明和参与须知" /></Form.Item>
        </>
      ),
    },
    {
      key: "display", label: "模板与展示", children: (
        <>
          <Row gutter={16}><Col xs={24} md={8}><Form.Item name="template_key" label="活动模板" rules={[{ required: true }]}><Select options={TEMPLATE_OPTIONS} /></Form.Item></Col><Col xs={24} md={8}><Form.Item name="button_text" label="按钮文字" rules={[{ max: 32 }]}><Input /></Form.Item></Col><Col xs={24} md={8}><Form.Item name="sort_order" label="排序"><InputNumber min={-9999} max={9999} style={{ width: "100%" }} /></Form.Item></Col></Row>
          <Form.Item name="target_url" label="自定义跳转地址" rules={[{ max: 500 }]}><Input placeholder="留空时进入活动详情页" /></Form.Item>
          <Row gutter={16}><Col xs={12} md={6}><Form.Item name="is_published" label="发布" valuePropName="checked"><Switch /></Form.Item></Col><Col xs={12} md={6}><Form.Item name="is_featured" label="重点推荐" valuePropName="checked"><Switch /></Form.Item></Col><Col xs={12} md={6}><Form.Item name="show_on_home" label="首页展示" valuePropName="checked"><Switch /></Form.Item></Col></Row>
        </>
      ),
    },
    {
      key: "rules", label: "参与规则", children: (
        <>
          <Row gutter={16}><Col xs={24} md={8}><Form.Item name="participation_mode" label="参与方式" rules={[{ required: true }]}><Select options={PARTICIPATION_OPTIONS} /></Form.Item></Col><Col xs={24} md={8}><Form.Item name="audience" label="参与用户" rules={[{ required: true }]}><Select options={AUDIENCE_OPTIONS} /></Form.Item></Col><Col xs={24} md={8}>{participationMode === "promo_code" && <Form.Item name="promo_code_id" label="优惠码" rules={[{ required: true, message: "请选择优惠码" }]}><Select showSearch optionFilterProp="label" options={options.promo_codes.map((promo) => ({ value: promo.id, label: `${promo.code}${promo.description ? ` - ${promo.description}` : ""}${promo.is_enabled ? "" : " [停用]"}` }))} /></Form.Item>}</Col></Row>
          <Row gutter={16}><Col xs={24} md={6}><Form.Item name="limited_time" label="限时活动" valuePropName="checked"><Switch checkedChildren="限时" unCheckedChildren="长期" /></Form.Item></Col><Col xs={24} md={9}><Form.Item name="starts_at" label="开始时间" rules={limitedTime ? [{ required: true }] : []}><Input type="datetime-local" disabled={!limitedTime} /></Form.Item></Col><Col xs={24} md={9}><Form.Item name="ends_at" label="结束时间" rules={limitedTime ? [{ required: true }] : []}><Input type="datetime-local" disabled={!limitedTime} /></Form.Item></Col></Row>
          <Row gutter={16}><Col xs={24} md={8}><Form.Item name="per_user_limit" label="每人限购"><InputNumber min={0} addonAfter="件" style={{ width: "100%" }} /></Form.Item></Col><Col xs={24} md={8}><Form.Item name="total_limit" label="活动总名额"><InputNumber min={0} addonAfter="件" style={{ width: "100%" }} /></Form.Item></Col></Row>
          <Form.Item name="rules" label="活动规则"><RichTextEditor placeholder="填写资格、限购、退款和优惠叠加规则" /></Form.Item>
        </>
      ),
    },
    {
	  key: "products", label: `参与产品 (${watchedProducts?.length ?? 0})`, forceRender: true, children: (
        <Form.List name="products">
          {(fields, { add, remove }) => (
            <Space orientation="vertical" size={16} style={{ width: "100%" }}>
              {fields.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未添加参与产品" />}
              {fields.map((field, index) => (
                <Card key={field.key} size="small" title={`参与产品 ${index + 1}`} extra={<Button danger type="text" icon={<DeleteOutlined />} onClick={() => remove(field.name)}>移除</Button>}>
                  <Row gutter={16}><Col xs={24} md={16}><Form.Item name={[field.name, "product_id"]} label="商城产品" rules={[{ required: true, message: "请选择产品" }]}><Select showSearch optionFilterProp="label" options={productOptions} /></Form.Item></Col><Col xs={12} md={4}><Form.Item name={[field.name, "card_style"]} label="卡片样式"><Select options={["a", "b", "c", "d"].map((value) => ({ value, label: `样式 ${value.toUpperCase()}` }))} /></Form.Item></Col><Col xs={12} md={4}><Form.Item name={[field.name, "sort_order"]} label="排序"><InputNumber style={{ width: "100%" }} /></Form.Item></Col></Row>
                  <Row gutter={16}><Col xs={24} md={12}><Form.Item name={[field.name, "section_name"]} label="所属分区" rules={[{ required: true }]}><Input placeholder="例如：云服务器特惠" /></Form.Item></Col><Col xs={24} md={12}><Form.Item name={[field.name, "section_description"]} label="分区说明"><Input /></Form.Item></Col></Row>
                  <Row gutter={16}><Col xs={24} md={8}><Form.Item name={[field.name, "custom_label"]} label="商品标签"><Input placeholder="爆款 / 新客专享" /></Form.Item></Col><Col xs={24} md={8}><Form.Item name={[field.name, "billing_cycle"]} label="活动周期"><Select allowClear options={CYCLE_OPTIONS} /></Form.Item></Col><Col xs={12} md={4}><Form.Item name={[field.name, "stock_limit"]} label="活动库存"><InputNumber min={0} style={{ width: "100%" }} /></Form.Item></Col><Col xs={12} md={4}><Form.Item name={[field.name, "per_user_limit"]} label="单人限购"><InputNumber min={0} style={{ width: "100%" }} /></Form.Item></Col></Row>
                  <Form.Item name={[field.name, "product_description"]} label="活动商品说明"><Input.TextArea rows={2} maxLength={500} /></Form.Item>
                  {participationMode === "activity_price" && <Form.Item name={[field.name, "activity_price"]} label="活动专享价" rules={[{ required: true, message: "请填写活动价" }]}><InputNumber min={0} precision={2} prefix="¥" style={{ width: 240 }} /></Form.Item>}
                  {participationMode === "existing_discount" && <Form.Item name={[field.name, "discount_percent"]} label="展示折扣"><InputNumber min={0.01} max={100} precision={2} addonAfter="%" style={{ width: 240 }} /></Form.Item>}
                </Card>
              ))}
              <Button type="dashed" block icon={<PlusOutlined />} onClick={() => add({ section_name: "精选产品", card_style: "a", stock_limit: 0, per_user_limit: 0, sort_order: fields.length })}>添加参与产品</Button>
            </Space>
          )}
        </Form.List>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom" gutter={[16, 16]}><Col><Title level={3} style={{ margin: 0 }}>活动管理</Title></Col><Col><Space><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button><Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>创建活动</Button></Space></Col></Row>
      <Card variant="outlined">
        <Row gutter={[12, 12]} style={{ marginBottom: 16 }}><Col xs={24} md={12} lg={8}><Input.Search allowClear placeholder="搜索活动标题或描述" onSearch={(value) => { setPage(1); setKeyword(value) }} /></Col><Col xs={24} md={8} lg={5}><Select value={published} style={{ width: "100%" }} onChange={(value) => { setPage(1); setPublished(value) }} options={[{ label: "全部发布状态", value: "all" }, { label: "已发布", value: true }, { label: "未发布", value: false }]} /></Col></Row>
        <Table rowKey="id" loading={loading} columns={columns} dataSource={items} scroll={{ x: 1200 }} pagination={{ current: page, pageSize: PAGE_SIZE, total, showSizeChanger: false, showTotal: (value) => `共 ${value} 个活动`, onChange: setPage }} locale={{ emptyText: <Empty description="暂无活动" /> }} />
      </Card>
      <Modal title={editing ? "编辑活动" : "创建活动"} open={modalOpen} onOk={() => void save()} onCancel={() => setModalOpen(false)} confirmLoading={saving} okText={editing ? "保存" : "创建"} cancelText="取消" width={1060} styles={{ body: { maxHeight: "72vh", overflowY: "auto" } }} destroyOnHidden>
        <Divider style={{ margin: "12px 0 4px" }} />
		<Form
		  form={form}
		  layout="vertical"
		  onValuesChange={(changedValues) => {
		    if (
		      Object.prototype.hasOwnProperty.call(changedValues, "products")
		      || Object.prototype.hasOwnProperty.call(changedValues, "participation_mode")
		    ) setProductsTouched(true)
		  }}
		>
		  <Tabs items={modalTabs} />
		</Form>
      </Modal>
    </Space>
  )
}
