import { useEffect, useState } from "react"
import { Link, useNavigate, useParams } from "react-router-dom"
import { ChevronRight, Server } from "lucide-react"
import { Spinner } from "@heroui/react"
import { fetchGroups, type StoreGroup } from "../api/store"

export default function StoreGroupList() {
  const { categorySlug } = useParams<{ categorySlug: string }>()
  const navigate = useNavigate()
  const [groups, setGroups] = useState<StoreGroup[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!categorySlug) return
    setLoading(true)
    fetchGroups(categorySlug)
      .then((res) => {
        const grps = res.data ?? []
        setGroups(grps)
        if (grps.length > 0) {
          navigate(`/store/${categorySlug}/${grps[0].slug}`, { replace: true })
        }
      })
      .finally(() => setLoading(false))
  }, [categorySlug]) // eslint-disable-line react-hooks/exhaustive-deps

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <Spinner />
      </div>
    )
  }

  if (groups.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center text-sm text-gray-400">
        该分类暂无产品
      </div>
    )
  }

  return (
    <div className="mx-auto max-w-4xl px-6 py-10">
      <h2 className="mb-6 text-xl font-bold text-gray-800">选择产品线</h2>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {groups.map((g) => (
          <Link
            key={g.id}
            to={`/store/${categorySlug}/${g.slug}`}
            className="flex items-center gap-4 rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition-all hover:border-sky-300 hover:shadow-md"
          >
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-sky-50">
              <Server className="h-5 w-5 text-sky-500" />
            </div>
            <div className="min-w-0 flex-1">
              <p className="font-semibold text-gray-800">{g.name}</p>
              {g.headline && (
                <p className="mt-0.5 truncate text-xs text-gray-400">{g.headline}</p>
              )}
            </div>
            <ChevronRight className="h-4 w-4 shrink-0 text-gray-300" />
          </Link>
        ))}
      </div>
    </div>
  )
}
