import { useCallback, useEffect, useMemo, useState } from "react"
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Form,
  Image,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
} from "antd"
import type { ColumnsType } from "antd/es/table"
import {
  createAdminMallCoupon,
  deleteAdminMallItem,
  getAdminMallClaims,
  getAdminMallItems,
  updateAdminMallItem,
  type AdminMallClaimRecord,
  type AdminMallItem,
  type CreateMallCouponPayload,
} from "../api/mall"
import { formatPoints, formatYuan } from "../../utils/format"
import { toast } from "../../utils/toast"

const { Text, Title } = Typography

function couponAmount(item: AdminMallItem) {
  if (item.type === "fixed") return `立减 ${formatYuan(item.value)}`
  if (item.type === "threshold_fixed") return `满 ${formatYuan(item.min_order_amount)} 减 ${formatYuan(item.value)}`
  if (item.type === "percent") return `${item.value / 10} 折`
  return formatYuan(item.value)
}

function formatDate(value: string | null) {
  return value ? new Date(value).toLocaleString() : "-"
}

interface MallFormValues {
  title: string
  subtitle?: string
  cover_image?: string
  description?: string
  category?: string
  points_price: number
  stock_total: number
  sort_order?: number
  max_claims_per_user?: number
  max_claims_per_user_per_day?: number
  required_member_level?: number
  required_member_level_name?: string
  is_hot?: boolean
  type: "fixed" | "threshold_fixed" | "percent"
  value: number
  threshold_amount?: number
  max_discount_amount?: number
  max_uses_per_user?: number
  min_order_amount?: number
  expires_at?: string
  new_users_only?: boolean
  scope?: "public" | "agent_subordinates"
  code?: string
  status?: "active" | "paused" | "expired"
}

export default function AdminMall() {
  const [loading, setLoading] = useState(false)
  const [items, setItems] = useState<AdminMallItem[]>([])
  const [total, setTotal] = useState(0)
  const [activeTab, setActiveTab] = useState("items")
  const [claims, setClaims] = useState<AdminMallClaimRecord[]>([])
  const [claimsTotal, setClaimsTotal] = useState(0)
  const [claimsLoading, setClaimsLoading] = useState(false)
  const [modalOpen, setModalOpen] = useState(false)
  const [saving, setSaving] = useState(false)
  const [editingItem, setEditingItem] = useState<AdminMallItem | null>(null)
  const [form] = Form.useForm<MallFormValues>()
  const couponType = Form.useWatch("type", form)

  const loadItems = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getAdminMallItems({ limit: 100 })
      setItems(res?.items ?? [])
      setTotal(res?.total ?? 0)
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载商城商品失败")
    } finally {
      setLoading(false)
    }
  }, [])

  const loadClaims = useCallback(async () => {
    setClaimsLoading(true)
    try {
      const res = await getAdminMallClaims({ limit: 100 })
      setClaims(res?.items ?? [])
      setClaimsTotal(res?.total ?? 0)
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载领取流水失败")
    } finally {
      setClaimsLoading(false)
    }
  }, [])

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

  useEffect(() => {
    if (activeTab === "claims") {
      void loadClaims()
    }
  }, [activeTab, loadClaims])

  const openCreate = () => {
    setEditingItem(null)
    form.setFieldsValue({
      type: "fixed",
      value: 10,
      points_price: 1000,
      stock_total: 100,
      max_uses_per_user: 1,
      scope: "public",
      new_users_only: false,
      sort_order: 0,
      max_claims_per_user: 1,
      max_claims_per_user_per_day: 0,
      required_member_level: 0,
      is_hot: false,
    })
    setModalOpen(true)
  }

  const openEdit = useCallback((item: AdminMallItem) => {
    setEditingItem(item)
    form.setFieldsValue({
      title: item.title,
      subtitle: item.subtitle || undefined,
      cover_image: item.cover_image || undefined,
      description: item.description || undefined,
      category: item.category || undefined,
      points_price: item.points_price,
      stock_total: item.stock_total,
      sort_order: item.sort_order,
      max_claims_per_user: item.max_claims_per_user,
      max_claims_per_user_per_day: item.max_claims_per_user_per_day,
      required_member_level: item.required_member_level,
      required_member_level_name: item.required_member_level_name || undefined,
      is_hot: item.is_hot,
      status: item.status as "active" | "paused" | "expired",
      scope: item.scope as "public" | "agent_subordinates",
    })
    setModalOpen(true)
  }, [form])

  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setSaving(true)

      if (editingItem) {
        await updateAdminMallItem(editingItem.id, {
          title: values.title,
          subtitle: values.subtitle,
          cover_image: values.cover_image,
          description: values.description,
          category: values.category,
          points_price: values.points_price,
          stock_total: values.stock_total,
          sort_order: values.sort_order,
          max_claims_per_user: values.max_claims_per_user,
          max_claims_per_user_per_day: values.max_claims_per_user_per_day,
          required_member_level: values.required_member_level,
          required_member_level_name: values.required_member_level_name,
          is_hot: values.is_hot,
        })
        toast.success("商品已更新")
      } else {
        const payload: CreateMallCouponPayload = {
          title: values.title,
          subtitle: values.subtitle,
          cover_image: values.cover_image,
          description: values.description,
          category: values.category,
          points_price: values.points_price,
          stock_total: values.stock_total,
          sort_order: values.sort_order,
          max_claims_per_user: values.max_claims_per_user,
          max_claims_per_user_per_day: values.max_claims_per_user_per_day,
          required_member_level: values.required_member_level,
          required_member_level_name: values.required_member_level_name,
          is_hot: values.is_hot,
          type: values.type,
          value: values.type === "percent" ? Math.round(values.value) : Math.round(values.value * 100),
          threshold_amount: values.threshold_amount ? Math.round(values.threshold_amount * 100) : undefined,
          max_discount_amount: values.max_discount_amount ? Math.round(values.max_discount_amount * 100) : undefined,
          max_uses_per_user: values.max_uses_per_user,
          min_order_amount: values.min_order_amount ? Math.round(values.min_order_amount * 100) : undefined,
          expires_at: values.expires_at ? new Date(values.expires_at).toISOString() : null,
          new_users_only: values.new_users_only,
          scope: values.scope,
          code: values.code?.trim() || undefined,
        }
        await createAdminMallCoupon(payload)
        toast.success("商城优惠券已上架")
      }
      setModalOpen(false)
      await loadItems()
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      if (detail) toast.error(detail)
    } finally {
      setSaving(false)
    }
  }

  const handleToggleStatus = useCallback(async (item: AdminMallItem) => {
    const next = item.status === "active" ? "paused" : "active"
    try {
      await updateAdminMallItem(item.id, { status: next })
      toast.success(next === "active" ? "已启用" : "已停用")
      await loadItems()
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "操作失败")
    }
  }, [loadItems])

  const handleDelete = useCallback((item: AdminMallItem) => {
    Modal.confirm({
      title: "删除商城商品",
      content: `确认删除 ${item.title || item.code} 吗？如有领取记录将改为停用。`,
      okText: "删除",
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteAdminMallItem(item.id)
          toast.success("已删除")
          await loadItems()
        } catch (error) {
          const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
          toast.error(detail || "删除失败")
        }
      },
    })
  }, [loadItems])

  const columns = useMemo<ColumnsType<AdminMallItem>>(() => [
    {
      title: "商品",
      render: (_, record) => (
        <Space>
          {record.cover_image ? <Image src={record.cover_image} width={60} height={40} style={{ objectFit: "cover" }} preview={false} /> : null}
          <Space orientation="vertical" size={0}>
            <Text strong>{record.title || record.code}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>{record.subtitle || "-"}</Text>
          </Space>
        </Space>
      ),
    },
    { title: "优惠码", dataIndex: "code", render: (value: string) => <Text strong copyable>{value}</Text> },
    { title: "优惠", render: (_, record) => <Tag>{couponAmount(record)}</Tag> },
    { title: "积分", dataIndex: "points_price", render: (value: number) => formatPoints(value) },
    { title: "库存", render: (_, record) => `${record.stock_remaining}/${record.stock_total}` },
    { title: "范围", dataIndex: "scope" },
    { title: "限购", render: (_, record) => (
      <Space orientation="vertical" size={0}>
        <Text style={{ fontSize: 12 }}>每用户 {record.max_claims_per_user > 0 ? `${record.max_claims_per_user} 张` : "不限"}</Text>
        {record.max_claims_per_user_per_day > 0 && <Text style={{ fontSize: 12 }}>每日 {record.max_claims_per_user_per_day} 张</Text>}
        {record.required_member_level > 0 && <Text style={{ fontSize: 12 }}>需 {record.required_member_level_name || `LV${record.required_member_level}`}</Text>}
      </Space>
    ) },
    { title: "状态", dataIndex: "status", render: (value: string) => <Tag color={value === "active" ? "green" : "default"}>{value}</Tag> },
    { title: "分类", dataIndex: "category" },
    { title: "热门", dataIndex: "is_hot", render: (value: boolean) => value ? <Tag color="red">HOT</Tag> : null },
    { title: "创建时间", dataIndex: "created_at", render: formatDate },
    {
      title: "操作",
      width: 180,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>编辑</Button>
          <Button size="small" onClick={() => handleToggleStatus(record)}>{record.status === "active" ? "停用" : "启用"}</Button>
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ], [handleDelete, handleToggleStatus, openEdit])

  const claimColumns = useMemo<ColumnsType<AdminMallClaimRecord>>(() => [
    { title: "ID", dataIndex: "id", width: 60 },
    { title: "用户", render: (_, record) => <Text>{record.nickname || record.username} <Text type="secondary">(#{record.user_id})</Text></Text> },
    { title: "商品", render: (_, record) => <Text>{record.mall_item_title || "-"}</Text> },
    { title: "优惠", render: (_, record) => <Tag>{record.coupon_type}</Tag> },
    { title: "支付积分", dataIndex: "points_paid", render: (value: number) => formatPoints(value) },
    { title: "状态", dataIndex: "status", render: (value: string) => <Tag color={value === "claimed" ? "blue" : value === "used" ? "green" : "default"}>{value}</Tag> },
    { title: "订单ID", dataIndex: "order_id", render: (value: number | null) => value ?? "-" },
    { title: "使用时间", dataIndex: "used_at", render: formatDate },
    { title: "领取时间", dataIndex: "created_at", render: formatDate },
  ], [])

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>积分商城管理</Title>
          <Text type="secondary">上架、编辑、停用积分商城优惠券商品，查看领取/使用流水。</Text>
        </Col>
        <Col>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>上架优惠券</Button>
        </Col>
      </Row>

      <Tabs activeKey={activeTab} onChange={setActiveTab} items={[
        {
          key: "items",
          label: "商品管理",
          children: (
            <Card variant="outlined" loading={loading}>
              <Table<AdminMallItem> rowKey="id" size="small" columns={columns} dataSource={items} pagination={{ total, pageSize: 100 }} />
            </Card>
          ),
        },
        {
          key: "claims",
          label: "领取流水",
          children: (
            <Card variant="outlined" loading={claimsLoading}>
              <Table<AdminMallClaimRecord> rowKey="id" size="small" columns={claimColumns} dataSource={claims} pagination={{ total: claimsTotal, pageSize: 100 }} />
            </Card>
          ),
        },
      ]} />

      <Modal
        title={editingItem ? "编辑商城商品" : "上架积分商城优惠券"}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        confirmLoading={saving}
        width={720}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          {!editingItem && (
            <>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="type" label="优惠类型" rules={[{ required: true }]}>
                    <Select options={[
                      { value: "fixed", label: "立减" },
                      { value: "threshold_fixed", label: "满减" },
                      { value: "percent", label: "折扣" },
                    ]} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="value" label={couponType === "percent" ? "折扣（%）" : "优惠金额（元）"} rules={[{ required: true }]}>
                    <InputNumber min={couponType === "percent" ? 1 : 0.01} max={couponType === "percent" ? 100 : undefined} precision={couponType === "percent" ? 0 : 2} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
              </Row>
              {couponType === "threshold_fixed" && (
                <Form.Item name="threshold_amount" label="满减门槛（元）" rules={[{ required: true }]}>
                  <InputNumber min={0.01} precision={2} style={{ width: "100%" }} />
                </Form.Item>
              )}
              {couponType === "percent" && (
                <Form.Item name="max_discount_amount" label="最高优惠金额（元）">
                  <InputNumber min={0} precision={2} style={{ width: "100%" }} />
                </Form.Item>
              )}
              <Form.Item name="min_order_amount" label="最低订单金额（元）">
                <InputNumber min={0} precision={2} style={{ width: "100%" }} />
              </Form.Item>
              <Row gutter={16}>
                <Col xs={24} md={12}>
                  <Form.Item name="max_uses_per_user" label="每用户限领" rules={[{ required: true }]}>
                    <InputNumber min={1} precision={0} style={{ width: "100%" }} />
                  </Form.Item>
                </Col>
                <Col xs={24} md={12}>
                  <Form.Item name="expires_at" label="有效期">
                    <Input type="datetime-local" />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item name="new_users_only" valuePropName="checked" label={null}>
                <Switch checkedChildren="仅限新用户" unCheckedChildren="不限新用户" />
              </Form.Item>
            </>
          )}

          <Form.Item name="title" label="商城标题" rules={[{ required: true }]}>
            <Input maxLength={200} />
          </Form.Item>
          <Form.Item name="subtitle" label="副标题">
            <Input maxLength={500} />
          </Form.Item>
          <Form.Item name="category" label="分类">
            <Input maxLength={50} placeholder="例如：新人专享、限时特惠" />
          </Form.Item>
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="points_price" label="所需积分" rules={[{ required: true }]}>
                <InputNumber min={0} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="stock_total" label="总库存" rules={[{ required: true }]}>
                <InputNumber min={1} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={8}>
              <Form.Item name="max_claims_per_user" label="每用户限领总数" tooltip="0 表示不限">
                <InputNumber min={0} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="max_claims_per_user_per_day" label="每用户每日限领" tooltip="0 表示不限">
                <InputNumber min={0} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="required_member_level" label="所需会员等级" tooltip="0 表示不限">
                <InputNumber min={0} precision={0} style={{ width: "100%" }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="required_member_level_name" label="会员等级名称">
                <Input maxLength={50} placeholder="例如：钻石会员" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="is_hot" valuePropName="checked" label={null}>
                <Switch checkedChildren="热门推荐" unCheckedChildren="普通" />
              </Form.Item>
            </Col>
          </Row>
          {!editingItem && (
            <Row gutter={16}>
              <Col xs={24} md={12}>
                <Form.Item name="scope" label="可见范围" rules={[{ required: true }]}>
                  <Select options={[
                    { value: "public", label: "全站公开" },
                    { value: "agent_subordinates", label: "代理专区" },
                  ]} />
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item name="sort_order" label="排序权重">
                  <InputNumber min={0} precision={0} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
            </Row>
          )}
          <Form.Item name="cover_image" label="封面图 URL">
            <Input maxLength={500} placeholder="https://..." />
          </Form.Item>
          <Form.Item name="description" label="详情说明">
            <Input.TextArea rows={3} maxLength={1000} />
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
