import { FolderOpenOutlined } from "@ant-design/icons"
import { Avatar, Badge, Card, Empty, Space, Tag, Typography, theme } from "antd"
import { getIconByName } from "./iconsCatalog"
import type { ProductCategory, ProductGroup } from "../api/product_catalog"

const { Text } = Typography

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

interface Props {
  categories: ProductCategory[]
  groups: ProductGroupListItem[]
  activeCategoryId: number | null
  activeGroupId: number | null
  productsCount: number
  productsLoading: boolean
  groupCountByCategory: Map<number, number>
  onSelectCategory: (category: ProductCategory, firstGroup: ProductGroupListItem | null) => void
  onSelectGroup: (group: ProductGroupListItem) => void
}

export default function ProductGroupSidebar({
  categories,
  groups,
  activeCategoryId,
  activeGroupId,
  productsCount,
  productsLoading,
  groupCountByCategory,
  onSelectCategory,
  onSelectGroup,
}: Props) {
  const { token } = theme.useToken()

  return (
    <Card
      variant="outlined"
      title={<Space><FolderOpenOutlined /> 分类与产品组</Space>}
      styles={{ body: { padding: 0 } }}
    >
      {categories.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未建立分类" style={{ padding: "48px 16px" }} />
      ) : (
        <div>
          {categories.map((category) => {
            const active = category.id === activeCategoryId && activeGroupId === null
            const categoryGroups = groups.filter((group) => group.category_id === category.id)
            const iconMeta = getIconByName(category.icon)
            const RowIcon = iconMeta?.Icon

            return (
              <div key={category.id}>
                <div
                  onClick={() => onSelectCategory(category, categoryGroups[0] ?? null)}
                  style={{
                    cursor: "pointer",
                    padding: "14px 16px",
                    background: active ? token.colorPrimaryBg : token.colorBgContainer,
                    borderInlineStart: `3px solid ${active ? token.colorPrimary : "transparent"}`,
                  }}
                >
                  <Space align="start" size={12}>
                    <span>
                      <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 />}
                      />
                    </span>
                    <Space orientation="vertical" size={2}>
                      <Space size={8}>
                        <Text strong={active}>{category.name}</Text>
                        <Badge count={categoryGroups.length} size="small" />
                      </Space>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {groupCountByCategory.get(category.id) ?? 0} 个产品组
                      </Text>
                    </Space>
                  </Space>
                </div>

                {categoryGroups.length > 0 && (
                  <div style={{ padding: "0 10px 8px 36px" }}>
                    <Space orientation="vertical" size={4} style={{ width: "100%" }}>
                      {categoryGroups.map((group) => {
                        const groupActive = activeGroupId === group.id
                        return (
                          <button
                            key={group.id}
                            type="button"
                            onClick={() => onSelectGroup(group)}
                            style={{
                              width: "100%",
                              border: 0,
                              borderRadius: 6,
                              cursor: "pointer",
                              background: groupActive ? token.colorPrimaryBg : "transparent",
                              color: groupActive ? token.colorPrimary : token.colorTextSecondary,
                              padding: "6px 8px",
                              textAlign: "left",
                            }}
                          >
                            <Space style={{ width: "100%", justifyContent: "space-between" }}>
                              <Text style={{ color: "inherit", fontSize: 12 }} ellipsis>{group.name}</Text>
                              {groupActive && (
                                <Tag style={{ marginInlineEnd: 0 }}>
                                  {productsLoading ? "..." : productsCount}
                                </Tag>
                              )}
                            </Space>
                          </button>
                        )
                      })}
                    </Space>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}
    </Card>
  )
}
