import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
import {
  ApartmentOutlined,
  AppstoreOutlined,
  EditOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  FolderOpenOutlined,
  GlobalOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  TagsOutlined,
} from "@ant-design/icons"
import {
  Avatar,
  Badge,
  Button,
  Card,
  Col,
  Empty,
  Input,
  Row,
  Space,
  Statistic,
  Table,
  Tag,
  Tooltip,
  Typography,
  theme,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import ProductCategoryFormModal from "../components/ProductCategoryFormModal"
import ProductGroupFormModal from "../components/ProductGroupFormModal"
import { getIconByName } from "../components/iconsCatalog"
import { getNetworkType } from "../components/networkTypes"
import {
  listCategories,
  listGroups,
  type OsOption,
  type ProductCategory,
  type ProductGroup,
} from "../api/product_catalog"

const { Title, Paragraph, Text } = Typography

type ProductGroupListItem = Omit<ProductGroup, "os_options"> & {
  os_count: number
}

const CATEGORY_STATUS_META: Record<ProductCategory["status"], { label: string; color: string; icon: ReactNode }> = {
  active: { label: "展示中", color: "success", icon: <EyeOutlined /> },
  hidden: { label: "已隐藏", color: "default", icon: <EyeInvisibleOutlined /> },
}

function normalizeText(value: string | null | undefined) {
  return (value ?? "").toLowerCase()
}

function formatDate(value: string | null | undefined) {
  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 AdminProductCatalog() {
  const { token } = theme.useToken()
  const [loading, setLoading] = useState(true)
  const [categories, setCategories] = useState<ProductCategory[]>([])
  const [groups, setGroups] = useState<ProductGroupListItem[]>([])
  const [groupOsOptionsById, setGroupOsOptionsById] = useState<Map<number, OsOption[]>>(new Map())
  const [activeCatId, setActiveCatId] = useState<number | null>(null)
  const [keyword, setKeyword] = useState("")
  const [catModalOpen, setCatModalOpen] = useState(false)
  const [editingCat, setEditingCat] = useState<ProductCategory | null>(null)
  const [groupModalOpen, setGroupModalOpen] = useState(false)
  const [editingGroup, setEditingGroup] = useState<ProductGroup | null>(null)

  const reload = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    try {
      const [catRes, grpRes] = await Promise.all([listCategories(), listGroups()])
      const nextCategories = catRes.data ?? []
      const nextGroups = grpRes.data ?? []
      const nextOsOptionsById = new Map<number, OsOption[]>()
      const nextGroupRows = nextGroups.map(({ os_options, ...group }) => {
        const options = os_options ?? []
        nextOsOptionsById.set(group.id, options)
        return { ...group, os_count: options.length }
      })
      setCategories(nextCategories)
      setGroupOsOptionsById(nextOsOptionsById)
      setGroups(nextGroupRows)
      setActiveCatId((prev) => {
        if (prev === null) return nextCategories[0]?.id ?? null
        return nextCategories.some((category) => category.id === prev)
          ? prev
          : nextCategories[0]?.id ?? null
      })
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const groupCountByCategory = useMemo(() => {
    const map = new Map<number, number>()
    groups.forEach((group) => {
      map.set(group.category_id, (map.get(group.category_id) ?? 0) + 1)
    })
    return map
  }, [groups])

  const activeCategory = useMemo(
    () => categories.find((category) => category.id === activeCatId) ?? null,
    [activeCatId, categories],
  )

  const shownGroups = useMemo(() => {
    const source = activeCatId ? groups.filter((group) => group.category_id === activeCatId) : groups
    const q = keyword.trim().toLowerCase()
    if (!q) return source
    return source.filter((group) =>
      [
        group.name,
        group.slug,
        group.headline,
        group.description,
        group.network_type,
        String(group.area ?? ""),
        String(group.node ?? ""),
      ].some((value) => normalizeText(value).includes(q)),
    )
  }, [activeCatId, groups, keyword])

  const stats = useMemo(() => {
    const activeCategories = categories.filter((category) => category.status === "active").length
    const hiddenCategories = categories.length - activeCategories
    const boundGroups = groups.filter((group) => group.area !== null || group.node !== null).length
    return { activeCategories, hiddenCategories, boundGroups }
  }, [categories, groups])

  const openCreateCategory = () => {
    setEditingCat(null)
    setCatModalOpen(true)
  }

  const openEditCategory = (category: ProductCategory) => {
    setEditingCat(category)
    setCatModalOpen(true)
  }

  const openCreateGroup = () => {
    setEditingGroup(null)
    setGroupModalOpen(true)
  }

  const openEditGroup = (group: ProductGroupListItem) => {
    setEditingGroup({
      ...group,
      os_options: groupOsOptionsById.get(group.id) ?? [],
    })
    setGroupModalOpen(true)
  }

  const columns: TableColumnsType<ProductGroupListItem> = [
    {
      title: "产品组",
      dataIndex: "name",
      width: 280,
      render: (_value, record) => {
        const iconMeta = getIconByName(record.icon)
        const RowIcon = iconMeta?.Icon
        return (
          <Space size={12}>
            <Avatar
              shape="square"
              size={38}
              style={{
                color: token.colorPrimary,
                background: token.colorPrimaryBg,
              }}
              icon={RowIcon ? <RowIcon className="h-[18px] w-[18px]" /> : <TagsOutlined />}
            />
            <Space orientation="vertical" size={0}>
              <Text strong>{record.name}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>{record.slug}</Text>
            </Space>
          </Space>
        )
      },
    },
    {
      title: "分类",
      dataIndex: "category_id",
      width: 160,
      render: (value: number) => {
        const category = categories.find((item) => item.id === value)
        return category ? <Tag icon={<FolderOpenOutlined />}>{category.name}</Tag> : <Text type="secondary">-</Text>
      },
    },
    {
      title: "网络",
      dataIndex: "network_type",
      width: 130,
      render: (value: string | null) => {
        const net = getNetworkType(value)
        return net ? <Tag color="blue" icon={<GlobalOutlined />}>{net.label}</Tag> : <Text type="secondary">未指定</Text>
      },
    },
    {
      title: "上游",
      key: "upstream",
      width: 160,
      render: (_value, record) => (
        <Space size={4} wrap>
          <Tag color={record.area === null ? "default" : "geekblue"}>区域 {record.area ?? "-"}</Tag>
          <Tag color={record.node === null ? "default" : "cyan"}>节点 {record.node ?? "-"}</Tag>
        </Space>
      ),
    },
    {
      title: "卖点",
      dataIndex: "headline",
      ellipsis: true,
      render: (value: string | null) => value || <Text type="secondary">-</Text>,
    },
    {
      title: "更新时间",
      dataIndex: "updated_at",
      width: 170,
      render: formatDate,
    },
    {
      title: "操作",
      key: "action",
      width: 90,
      align: "right",
      render: (_value, record) => (
        <Tooltip title="编辑产品组">
          <Button type="text" icon={<EditOutlined />} onClick={() => openEditGroup(record)} />
        </Tooltip>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>产品分类与组</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            维护前台产品目录的两级结构，分类负责入口展示，产品组负责线路、区域和节点绑定。
          </Paragraph>
        </Col>
        <Col>
          <Space wrap>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={() => reload()}>
              刷新
            </Button>
            <Button icon={<PlusOutlined />} onClick={openCreateCategory}>
              添加分类
            </Button>
            <Button type="primary" icon={<PlusOutlined />} disabled={categories.length === 0} onClick={openCreateGroup}>
              添加产品组
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic title="产品分类" value={categories.length} suffix="个" prefix={<AppstoreOutlined />} />
          </Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic
              title="展示中分类"
              value={stats.activeCategories}
              suffix="个"
              prefix={<EyeOutlined />}
              styles={{ content: { color: token.colorSuccess } }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic title="产品组" value={groups.length} suffix="个" prefix={<TagsOutlined />} />
          </Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic
              title="已绑定上游"
              value={stats.boundGroups}
              suffix="组"
              prefix={<ApartmentOutlined />}
              styles={{ content: { color: token.colorPrimary } }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} align="stretch">
        <Col xs={24} xl={7}>
          <Card
            variant="outlined"
            title={<Space><FolderOpenOutlined /> 分类</Space>}
            extra={<Text type="secondary">{stats.hiddenCategories > 0 ? `${stats.hiddenCategories} 个隐藏` : "全部展示"}</Text>}
            styles={{ body: { padding: 0 } }}
          >
            {categories.length === 0 ? (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未建立分类" style={{ padding: "48px 16px" }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={openCreateCategory}>添加分类</Button>
              </Empty>
            ) : (
              <div>
                {loading ? <Text type="secondary" style={{ display: "block", padding: "12px 16px" }}>加载中...</Text> : null}
                {categories.map((category) => {
                  const active = category.id === activeCatId
                  const statusMeta = CATEGORY_STATUS_META[category.status] ?? { label: category.status || "未知", color: "default", icon: null }
                  const iconMeta = getIconByName(category.icon)
                  const RowIcon = iconMeta?.Icon
                  return (
                    <div
                      key={category.id}
                      onClick={() => setActiveCatId(category.id)}
                      style={{
                        cursor: "pointer",
                        padding: "14px 16px",
                        background: active ? token.colorPrimaryBg : token.colorBgContainer,
                        borderInlineStart: `3px solid ${active ? token.colorPrimary : "transparent"}`,
                      }}
                    >
                      <Space align="start" style={{ width: "100%", justifyContent: "space-between" }}>
                        <Space align="start" size={12}>
                          <Badge dot={category.is_featured} color={token.colorWarning}>
                            <Avatar
                              shape="square"
                              style={{
                                color: active ? token.colorPrimary : token.colorTextSecondary,
                                background: active ? token.colorPrimaryBgHover : token.colorFillAlter,
                              }}
                              icon={RowIcon ? <RowIcon className="h-[17px] w-[17px]" /> : <FolderOpenOutlined />}
                            />
                          </Badge>
                          <Space orientation="vertical" size={2}>
                            <Space size={8}>
                              <Text strong={active}>{category.name}</Text>
                              <Tag color={statusMeta.color} icon={statusMeta.icon}>{statusMeta.label}</Tag>
                            </Space>
                            <Space size={8} wrap>
                              <Text type="secondary" style={{ fontSize: 12 }}>{category.slug}</Text>
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                {groupCountByCategory.get(category.id) ?? 0} 个产品组
                              </Text>
                            </Space>
                          </Space>
                        </Space>
                        <Tooltip title="编辑分类" key="edit">
                          <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={(event) => {
                              event.stopPropagation()
                              openEditCategory(category)
                            }}
                          />
                        </Tooltip>
                      </Space>
                    </div>
                  )
                })}
              </div>
            )}
          </Card>
        </Col>

        <Col xs={24} xl={17}>
          <Card
            variant="outlined"
            title={
              <Space>
                <TagsOutlined />
                {activeCategory ? `${activeCategory.name} · 产品组` : "全部产品组"}
                <Tag>{shownGroups.length}</Tag>
              </Space>
            }
            extra={
              <Input
                allowClear
                prefix={<SearchOutlined />}
                placeholder="搜索名称 / slug / 卖点 / 上游"
                value={keyword}
                onChange={(event) => setKeyword(event.target.value)}
                style={{ width: 280 }}
              />
            }
          >
            <Table
              rowKey="id"
              loading={loading}
              columns={columns}
              dataSource={shownGroups}
              pagination={{ pageSize: 8, showSizeChanger: false }}
              scroll={{ x: 1100 }}
              locale={{
                emptyText: (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={categories.length === 0 ? "请先建立至少一个分类" : "当前筛选下暂无产品组"}
                  />
                ),
              }}
            />
          </Card>
        </Col>
      </Row>

      <ProductCategoryFormModal
        open={catModalOpen}
        onClose={() => setCatModalOpen(false)}
        onSaved={() => reload(true)}
        initial={editingCat}
      />
      <ProductGroupFormModal
        open={groupModalOpen}
        onClose={() => setGroupModalOpen(false)}
        onSaved={() => reload(true)}
        categories={categories}
        initial={editingGroup}
        defaultCategoryId={activeCatId}
      />
    </Space>
  )
}
