import { CalendarClock, Layers3, PlayCircle, Tv } from 'lucide-solid'
import { For, Show, createMemo, createResource } from 'solid-js'
import { MediaCard } from '@/components/media/media-card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { DataRow } from '@/components/ui/data-row'
import { EmptyState } from '@/components/ui/empty-state'
import { SectionHeading } from '@/components/ui/section-heading'
import { Skeleton } from '@/components/ui/skeleton'
import { discoverService } from '@/services/discover-service'
import type { MediaItem } from '@/types/domain'
import { formatDate } from '@/utils/format'
import { mediaBadgeVariant, mediaTypeLabel } from '@/utils/media'

const showsOnly = (items: MediaItem[]) => items.filter((item) => item.type === 'show')

export const ShowsPage = () => {
  const [discoverData, { refetch }] = createResource(() => discoverService.getSections({ page: 1, pageSize: 6 }))
  const allSections = createMemo(() => discoverData() ?? [])
  const airingToday = createMemo(() => showsOnly(allSections().find((section) => section.kind === 'airing-today')?.items ?? []))
  const popularShows = createMemo(() => showsOnly(allSections().find((section) => section.kind === 'popular')?.items ?? []))
  const trendingShows = createMemo(() => showsOnly(allSections().find((section) => section.kind === 'trending')?.items ?? []))

  const averageRuntime = createMemo(() => {
    const items = [...airingToday(), ...popularShows()]
    if (items.length === 0) return 0
    return Math.round(items.reduce((acc, item) => acc + item.runtimeMinutes, 0) / items.length)
  })

  return (
    <section class="space-y-6" data-testid="shows-page">
      <Card class="animate-stagger">
        <CardContent class="space-y-6 pt-6">
          <SectionHeading
            eyebrow="Shows"
            title="Episode-first surface for ongoing series and fresh drops."
            description="Built for tracking what is airing, what is trending, and what deserves your next session."
            badge={<Badge variant="neutral">{airingToday().length} airing now</Badge>}
            action={<Button variant="subtle" size="sm" onClick={() => refetch()}>Refresh</Button>}
          />

          <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <p class="text-xs uppercase tracking-[0.2em] text-muted-fg">Airing today</p>
              <p class="mt-2 text-2xl font-semibold text-fg">{airingToday().length}</p>
            </div>
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <p class="text-xs uppercase tracking-[0.2em] text-muted-fg">Popular</p>
              <p class="mt-2 text-2xl font-semibold text-fg">{popularShows().length}</p>
            </div>
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <p class="text-xs uppercase tracking-[0.2em] text-muted-fg">Trending</p>
              <p class="mt-2 text-2xl font-semibold text-fg">{trendingShows().length}</p>
            </div>
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <p class="text-xs uppercase tracking-[0.2em] text-muted-fg">Avg runtime</p>
              <p class="mt-2 text-2xl font-semibold text-fg">{averageRuntime()}m</p>
            </div>
          </div>
        </CardContent>
      </Card>

      <Show when={discoverData.loading && allSections().length === 0}>
        <div class="grid gap-4 md:grid-cols-3">
          <For each={Array.from({ length: 6 }, (_, index) => index)}>{() => <Skeleton class="h-64" />}</For>
        </div>
      </Show>

      <div class="grid gap-6 xl:grid-cols-[minmax(0,1.05fr)_360px]">
        <Card>
          <CardContent class="space-y-5 pt-6">
            <SectionHeading
              title="Airing today"
              description="Series episodes available now."
              badge={<Badge variant="accent">{airingToday().length} episodes</Badge>}
            />
            <Show
              when={airingToday().length > 0}
              fallback={<EmptyState title="No shows airing today" description="Airing schedule is currently quiet." />}
            >
              <div class="grid gap-4 md:grid-cols-2">
                <For each={airingToday().slice(0, 6)}>{(item) => <MediaCard item={item} />}</For>
              </div>
            </Show>
          </CardContent>
        </Card>

        <Card>
          <CardContent class="space-y-5 pt-6">
            <SectionHeading
              title="Signals"
              description="Operational show-feed indicators."
              badge={<Badge variant="secondary">Live</Badge>}
            />
            <div class="space-y-3">
              <DataRow
                tone="accent"
                eyebrow="Current feed"
                title={`${airingToday().length} titles live today`}
                description="Airing data synced into the discover rail."
                trailing={<PlayCircle class="h-4 w-4" />}
              />
              <DataRow
                tone="neutral"
                eyebrow="Catalog depth"
                title={`${popularShows().length + trendingShows().length} show cards loaded`}
                description="Popular and trending cards available for quick browse."
                trailing={<Layers3 class="h-4 w-4" />}
              />
              <DataRow
                tone="secondary"
                eyebrow="Runtime profile"
                title={`${averageRuntime()}m average runtime`}
                description="Useful for planning next watch session length."
                trailing={<CalendarClock class="h-4 w-4" />}
              />
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent class="space-y-5 pt-6">
          <SectionHeading
            title="Popular shows"
            description="High-interest series with stable engagement."
            badge={<Badge variant="neutral">{popularShows().length} popular</Badge>}
          />
          <Show
            when={popularShows().length > 0}
            fallback={<EmptyState title="No popular shows" description="Popular show feed is empty." />}
          >
            <div class="space-y-3">
              <For each={popularShows()}>
                {(item) => (
                  <DataRow
                    tone={mediaBadgeVariant(item.type)}
                    eyebrow={mediaTypeLabel(item.type)}
                    title={item.title}
                    description={item.genres.slice(0, 2).join(' • ')}
                    meta={formatDate(item.releaseDate)}
                    badges={<Badge variant={mediaBadgeVariant(item.type)}>{mediaTypeLabel(item.type)}</Badge>}
                    trailing={<Tv class="h-4 w-4" />}
                  />
                )}
              </For>
            </div>
          </Show>
        </CardContent>
      </Card>

      <Show when={discoverData.error}>
        <div class="rounded-[1.5rem] border border-secondary/24 bg-secondary/10 px-4 py-4 text-sm text-fg">
          {discoverData.error instanceof Error ? discoverData.error.message : 'Failed to load shows'}
        </div>
      </Show>
    </section>
  )
}
