import { Compass, Sparkles, Wand2 } 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 { 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 { dashboardService } from '@/services/dashboard-service'
import { mediaBadgeVariant, mediaTypeLabel } from '@/utils/media'

const reasonTone = (score: number): 'accent' | 'neutral' | 'secondary' => {
  if (score >= 90) return 'accent'
  if (score >= 80) return 'neutral'
  return 'secondary'
}

export const RecommendationsPage = () => {
  const [dashboardData, { refetch }] = createResource(() => dashboardService.getDashboard())
  const recommendations = createMemo(() => dashboardData()?.recommendations ?? [])
  const topPicks = createMemo(() => recommendations().slice(0, 3))
  const moreLikeThis = createMemo(() => recommendations().slice(3))

  return (
    <section class="space-y-6" data-testid="recommendations-page">
      <Card class="animate-stagger overflow-hidden">
        <CardContent class="space-y-6 pt-6">
          <SectionHeading
            eyebrow="Recommendations"
            title="Personalized picks shaped by your history, queue, and genre signal."
            description="A compact recommendation lane designed to feel editorial rather than algorithmic noise."
            badge={<Badge variant="accent">{recommendations().length} ranked picks</Badge>}
            action={
              <button
                class="inline-flex h-8 items-center rounded-lg border border-border px-3 text-sm text-fg transition hover:border-accent/40 hover:text-accent"
                onClick={() => refetch()}
              >
                Refresh
              </button>
            }
          />

          <div class="grid gap-4 sm:grid-cols-3">
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <div class="flex items-center gap-2 text-sm text-muted-fg">
                <Sparkles class="h-4 w-4 text-accent" />
                Match quality
              </div>
              <p class="mt-2 text-2xl font-semibold text-fg">
                {recommendations().length > 0
                  ? `${Math.round(
                      recommendations().reduce((acc, item) => acc + item.score, 0) / recommendations().length,
                    )}%`
                  : '0%'}
              </p>
            </div>
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <div class="flex items-center gap-2 text-sm text-muted-fg">
                <Compass class="h-4 w-4 text-accent" />
                Distinct genres
              </div>
              <p class="mt-2 text-2xl font-semibold text-fg">
                {
                  new Set(recommendations().flatMap((item) => item.media.genres.map((genre) => genre.toLowerCase())))
                    .size
                }
              </p>
            </div>
            <div class="rounded-2xl border border-border bg-muted/40 p-4">
              <div class="flex items-center gap-2 text-sm text-muted-fg">
                <Wand2 class="h-4 w-4 text-accent" />
                High confidence
              </div>
              <p class="mt-2 text-2xl font-semibold text-fg">
                {recommendations().filter((item) => item.score >= 90).length}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

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

      <Show
        when={recommendations().length > 0}
        fallback={
          <Card>
            <CardContent class="pt-6">
              <EmptyState
                title="No recommendations yet"
                description="Start watching and adding titles to watch later to generate better signal."
              />
            </CardContent>
          </Card>
        }
      >
        <Card>
          <CardContent class="space-y-4 pt-6">
            <SectionHeading title="Top picks" description="Highest confidence matches based on your profile." />
            <div class="grid gap-4 md:grid-cols-3">
              <For each={topPicks()}>
                {(entry) => (
                  <div class="space-y-2">
                    <MediaCard item={entry.media} />
                    <DataRow
                      tone={reasonTone(entry.score)}
                      eyebrow={`Match ${entry.score}%`}
                      title={entry.media.title}
                      description={entry.reason}
                      meta={`${mediaTypeLabel(entry.media.type)} · ${entry.media.genres.slice(0, 2).join(' • ')}`}
                      badges={<Badge variant={mediaBadgeVariant(entry.media.type)}>{mediaTypeLabel(entry.media.type)}</Badge>}
                    />
                  </div>
                )}
              </For>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent class="space-y-4 pt-6">
            <SectionHeading title="More like this" description="Additional recommendations with lower but relevant confidence." />
            <div class="space-y-3">
              <For each={moreLikeThis()}>
                {(entry) => (
                  <DataRow
                    tone={reasonTone(entry.score)}
                    eyebrow={`Match ${entry.score}%`}
                    title={entry.media.title}
                    description={entry.reason}
                    meta={`${mediaTypeLabel(entry.media.type)} · ${entry.media.genres.slice(0, 2).join(' • ')}`}
                    badges={<Badge variant={mediaBadgeVariant(entry.media.type)}>{mediaTypeLabel(entry.media.type)}</Badge>}
                  />
                )}
              </For>
            </div>
          </CardContent>
        </Card>
      </Show>

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