import Link from 'next/link'
import { serverGet } from '@/lib/api'
import type { Product, Category, Paginated } from '@/lib/types'
import { ProductRow } from '@/components/ProductRow'
import { BannerSlider } from '@/components/BannerSlider'
import { CategoryCarousel } from '@/components/CategoryCarousel'
import { CareByCondition } from '@/components/CareByCondition'
import { CategoryIconGrid } from '@/components/CategoryIconGrid'
import { BrandLogo } from '@/components/BrandLogo'

export const revalidate = 300

async function getProducts(params = ''): Promise<Product[]> {
  try {
    const r = await serverGet<Paginated<Product>>(`/products${params}`, 300)
    return r.data ?? []
  } catch { return [] }
}
async function getCategories(): Promise<Category[]> {
  try {
    const r = await serverGet<{ data: Category[] } | Category[]>('/categories', 3600)
    return (r as { data?: Category[] }).data ?? (r as Category[])
  } catch { return [] }
}
interface HomeBrand { id: number; name: string; slug?: string | null; logo?: string | null }
async function getBrands(): Promise<HomeBrand[]> {
  try {
    const r = await serverGet<any[] | { data: any[] }>('/brands', 3600)
    const arr = Array.isArray(r) ? r : (r.data ?? [])
    return arr.map((b: any) => ({ id: b.id, name: b.name, slug: b.slug, logo: b.logo ?? b.logo_url ?? null }))
  } catch { return [] }
}
interface HomePost { id: number; title: string; slug?: string; excerpt?: string | null; image?: string | null }
async function getPosts(): Promise<HomePost[]> {
  try {
    const r = await serverGet<{ data?: any[] } | any[]>('/posts?per_page=3', 3600)
    const arr = Array.isArray(r) ? r : (r.data ?? [])
    return arr.map((p: any) => ({ id: p.id, title: p.title, slug: p.slug, excerpt: p.excerpt, image: p.image ?? p.cover_image ?? null }))
  } catch { return [] }
}

export default async function HomePage() {
  const [topSelling, featured, products, categories, brands, posts] = await Promise.all([
    getProducts('?per_page=14&sort=trending'),
    getProducts('?per_page=14'),
    getProducts('?per_page=14&sort=on_sale'),
    getCategories(),
    getBrands(),
    getPosts(),
  ])

  const catTiles = categories.length ? categories.slice(0, 16) : []

  return (
    <div className="pb-10">
      <BannerSlider placement="home_top" />

      <ProductRow title="Top Selling Items" products={topSelling} viewAllHref="/categories" />
      <ProductRow title="Featured Products" products={featured} viewAllHref="/categories" />
      <ProductRow title="Products" products={products} viewAllHref="/categories" />

      <CareByCondition />

      {/* app download band */}
      <section className="container-x py-8">
        <div className="flex flex-col items-center justify-between gap-4 rounded-2xl bg-brand-strong p-6 text-white sm:flex-row sm:p-8">
          <div>
            <div className="text-2xl font-extrabold">Download the Fitorza App</div>
            <p className="mt-1 text-sm text-white/85">Get Rs. 300 off your first order. Use code <span className="font-bold">FITORZA300</span>.</p>
          </div>
          <div className="flex gap-3">
            <span className="rounded-lg bg-white/15 px-4 py-2 text-sm font-semibold ring-1 ring-white/25">App Store</span>
            <span className="rounded-lg bg-white/15 px-4 py-2 text-sm font-semibold ring-1 ring-white/25">Google Play</span>
          </div>
        </div>
      </section>

      {/* promo strips — artwork served from /banners */}
      <section className="container-x">
        <div className="grid gap-4 md:grid-cols-2">
          <BannerSlider placement="home_grid_left" />
          <BannerSlider placement="home_grid_right" />
        </div>
      </section>

      <BannerSlider placement="home_wide" />

      {/* Dvago-style category icon grid (incl. A to Z Medicine) */}
      <CategoryIconGrid />

      <CategoryCarousel categories={catTiles} />

      {/* Blogs */}
      {posts.length > 0 && (
        <section className="container-x py-8">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="sec-title">Blogs</h2>
            <Link href="/blog" className="view-all">VIEW ALL</Link>
          </div>
          <div className="grid gap-6 sm:grid-cols-3">
            {posts.map((p) => (
              <Link key={p.id} href={`/blog/${p.slug ?? p.id}`} className="flex items-center gap-4">
                <div className="h-20 w-20 shrink-0 overflow-hidden rounded-full bg-soft">
                  {p.image && (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={p.image} alt={p.title} className="h-full w-full object-cover" loading="lazy" />
                  )}
                </div>
                <span className="line-clamp-3 text-[15px] font-semibold text-ink hover:text-brand">{p.title}</span>
              </Link>
            ))}
          </div>
        </section>
      )}

      {/* Brands */}
      {brands.length > 0 && (
        <section className="container-x py-4">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="sec-title">Brands</h2>
            <Link href="/brands" className="view-all">VIEW ALL</Link>
          </div>
          <div className="grid grid-cols-3 items-center gap-6 sm:grid-cols-4 md:grid-cols-6">
            {brands.slice(0, 12).map((b) => (
              <Link key={b.id} href={`/brands/${b.slug ?? b.id}`} className="grid h-16 place-items-center grayscale transition hover:grayscale-0">
                <BrandLogo src={b.logo} name={b.name} />
              </Link>
            ))}
          </div>
        </section>
      )}

      {/* SEO */}
      <section className="border-t border-hair">
        <div className="container-x py-10 text-sm leading-relaxed text-muted">
          <h2 className="text-2xl font-medium text-ink">Fitorza — Pakistan&rsquo;s Health &amp; Fitness Marketplace</h2>
          <p className="mt-3">Shop authentic medicines, multivitamins, protein and supplements, personal care, baby care and medical devices online from verified sellers. Fitorza brings e-commerce, gym memberships, trainers, doctor and dietitian consultations, and lab diagnostics together on one trusted platform, with secure checkout, order tracking, and nationwide delivery.</p>
          <p className="mt-3">For prescription medicines, upload your prescription at checkout. For OTC and wellness items, add to cart and order in a few clicks. Members can subscribe to plans for gym access and exclusive perks.</p>
        </div>
      </section>
    </div>
  )
}
