import { FolderOpen } from 'lucide-react'
import { Link } from 'react-router-dom'

import { AppShell } from '@/components/layout/AppShell'
import { Alert, Card, EmptyState, PageSpinner } from '@/components/ui'
import { useCategories } from '@/features/marketplace/queries'

export function CategoriesPage() {
  const { data: categories, isLoading, isError } = useCategories()

  return (
    <AppShell>
      <div className="container-page py-10 lg:py-14">
        <div className="max-w-2xl">
          <h1 className="text-2xl font-semibold tracking-[-0.02em] text-text-primary sm:text-3xl">
            Categories
          </h1>
          <p className="mt-2 text-text-secondary">
            Browse the marketplace by what a name is for.
          </p>
        </div>

        {isLoading ? (
          <PageSpinner label="Loading categories" />
        ) : isError ? (
          <Alert tone="error" title="Could not load categories" className="mt-8">
            Refresh the page to try again.
          </Alert>
        ) : categories === undefined || categories.length === 0 ? (
          <EmptyState
            className="mt-8"
            icon={<FolderOpen className="size-5" />}
            title="No categories yet"
            description="Categories appear here once an administrator sets them up."
          />
        ) : (
          <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {categories.map((category) => (
              <Link key={category.slug} to={`/domains?category=${category.slug}`}>
                <Card interactive className="h-full p-5">
                  <div className="flex items-start justify-between gap-3">
                    <h2 className="text-base font-semibold text-text-primary">{category.name}</h2>
                    <span data-numeric className="shrink-0 text-sm text-text-muted">
                      {category.listings_count}
                    </span>
                  </div>

                  {category.description !== null && (
                    <p className="mt-2 text-sm text-text-secondary">{category.description}</p>
                  )}

                  {category.children !== undefined && category.children.length > 0 && (
                    <p className="mt-3 text-xs text-text-muted">
                      {category.children.map((child) => child.name).join(' · ')}
                    </p>
                  )}
                </Card>
              </Link>
            ))}
          </div>
        )}
      </div>
    </AppShell>
  )
}
