import { useNavigate } from '@solidjs/router'
import { ArrowRight, Film, Gamepad2, Shield, Tv } from 'lucide-solid'
import { For, Show, createSignal, type Component } from 'solid-js'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { DataRow } from '@/components/ui/data-row'
import { Input } from '@/components/ui/input'
import { SectionHeading } from '@/components/ui/section-heading'
import { isMockApiEnabled } from '@/services/api-client'
import { useAuth } from '@/stores/auth-store'
import { useTheme } from '@/stores/theme-store'
import type { ThemeMode } from '@/types/domain'
import { mediaMonogram } from '@/utils/media'
import { cn } from '@/utils/cn'

type IconComponent = Component<{ class?: string; size?: number | string }>

const formModes = [
  { value: 'login', label: 'Sign In' },
  { value: 'register', label: 'Register' },
] as const

const themeModes: { value: ThemeMode; label: string }[] = [
  { value: 'dark', label: 'Dark' },
  { value: 'light', label: 'Light' },
  { value: 'system', label: 'System' },
]

const featureHighlights: { title: string; description: string; icon: IconComponent; tone: 'accent' | 'secondary' | 'neutral' }[] = [
  {
    title: 'Unified queue',
    description: 'Movies, shows, and games stay on one quieter surface instead of across several dashboards.',
    icon: Film,
    tone: 'accent',
  },
  {
    title: 'Playback memory',
    description: 'Resume points, backlog context, and queue state stay synced to your local session.',
    icon: Tv,
    tone: 'secondary',
  },
  {
    title: 'Private by default',
    description: 'Seen is built around a self-hosted setup, not a hosted SaaS posture.',
    icon: Shield,
    tone: 'neutral',
  },
]

const previewRows = [
  {
    label: 'Continue watching',
    title: 'The Bear',
    detail: 'Episode 4 at 61%',
    tone: 'accent' as const,
  },
  {
    label: 'Queue',
    title: 'Blade Runner 2049',
    detail: 'Saved for tonight',
    tone: 'secondary' as const,
  },
  {
    label: 'Backlog',
    title: 'Hades II',
    detail: 'Tracked for the next long session',
    tone: 'neutral' as const,
  },
]

export const LoginPage = () => {
  const auth = useAuth()
  const theme = useTheme()
  const navigate = useNavigate()

  const [mode, setMode] = createSignal<'login' | 'register'>('login')
  const [email, setEmail] = createSignal('demo@seen.local')
  const [password, setPassword] = createSignal('password123')
  const [displayName, setDisplayName] = createSignal('Demo User')
  const [error, setError] = createSignal<string | null>(null)

  const sessionLabel = (): string => (isMockApiEnabled() ? 'Demo-ready auth' : 'Live auth connected')
  const sessionSummary = (): string =>
    isMockApiEnabled()
      ? 'Demo credentials are prefilled so the frontend can be validated immediately.'
      : 'Authentication is using the configured backend session for this instance.'
  const sessionDetails = (): string =>
    isMockApiEnabled()
      ? 'Use demo@seen.local with password123, or register a fresh local profile.'
      : 'Sign in with an existing account, or create a new local session.'

  const redirectPath = (): string => {
    const search = typeof window === 'undefined' ? '' : window.location.search
    const redirect = new URLSearchParams(search).get('redirect')

    if (!redirect || !redirect.startsWith('/app/')) {
      return '/app/dashboard'
    }

    return redirect
  }

  const submit = async (): Promise<void> => {
    if (auth.isBusy()) {
      return
    }

    setError(null)

    try {
      if (mode() === 'register') {
        await auth.register({
          email: email().trim(),
          password: password(),
          displayName: displayName().trim(),
        })
      } else {
        await auth.login({
          email: email().trim(),
          password: password(),
        })
      }

      navigate(redirectPath(), { replace: true })
    } catch (submissionError) {
      const message =
        submissionError instanceof Error ? submissionError.message : 'Authentication request failed'
      setError(message)
    }
  }

  return (
    <main class="min-h-screen bg-surface-dim px-6 py-6 sm:px-8 lg:px-10">
      <div class="mx-auto grid min-h-[calc(100vh-3rem)] max-w-6xl gap-6 lg:grid-cols-[1.05fr_0.95fr]">
        <section class="panel flex flex-col justify-between p-8 sm:p-10">
          <div class="space-y-10">
            <div class="flex items-center justify-between gap-4">
              <div class="flex items-center gap-4">
                <div class="grid h-12 w-12 place-items-center rounded-xl bg-primary text-on-primary shadow-glow">
                  <span class="font-display text-xl font-semibold">S</span>
                </div>
                <div>
                  <p class="text-xs font-semibold uppercase tracking-widest text-muted-fg">Seen</p>
                  <p class="mt-1 text-sm text-muted-fg">Personal streaming control center</p>
                </div>
              </div>

              <Badge variant="neutral">Self-hosted</Badge>
            </div>

            <SectionHeading
              eyebrow="Private control"
              title="Keep your media stack on one cleaner surface."
              description="Seen brings your next watch, resume history, downloads, and backlog into a single calm interface with no dashboard clutter."
            />

            <div class="grid gap-4">
              <For each={featureHighlights}>
                {(highlight) => {
                  const Icon = highlight.icon

                  return (
                    <DataRow
                      tone={highlight.tone}
                      title={highlight.title}
                      description={highlight.description}
                      trailing={
                        <div
                          class={cn(
                            'flex h-11 w-11 items-center justify-center rounded-xl transition-all duration-200',
                            highlight.tone === 'accent'
                              ? 'bg-primary/15 text-primary'
                              : highlight.tone === 'secondary'
                                ? 'bg-secondary/15 text-secondary'
                                : 'bg-surface-high text-muted-fg',
                          )}
                        >
                          <Icon class="h-4 w-4" />
                        </div>
                      }
                    />
                  )
                }}
              </For>
            </div>
          </div>

          <div class="rounded-3xl bg-surface-low p-6">
            <div class="flex items-center justify-between gap-4">
              <div>
                <p class="text-[10px] font-semibold uppercase tracking-widest text-muted-fg">Surface preview</p>
                <p class="mt-2 text-lg font-semibold text-fg">One session, three catalogs</p>
              </div>
              <Gamepad2 class="h-5 w-5 text-muted-fg" />
            </div>

            <div class="mt-5 grid gap-3">
              <For each={previewRows}>
                {(row) => (
                  <div class="rounded-2xl bg-surface-container px-5 py-4 transition-all duration-200 hover:bg-surface-high">
                    <div class="flex items-start justify-between gap-4">
                      <div class="min-w-0">
                        <p class="text-[10px] font-semibold uppercase tracking-widest text-muted-fg">{row.label}</p>
                        <p class="mt-2 text-sm font-semibold text-fg">{row.title}</p>
                        <p class="mt-1 text-sm text-muted-fg">{row.detail}</p>
                      </div>
                      <div
                        class={cn(
                          'flex h-12 w-12 items-center justify-center rounded-xl font-display text-lg font-semibold',
                          row.tone === 'accent'
                            ? 'bg-primary/15 text-primary'
                            : row.tone === 'secondary'
                              ? 'bg-secondary/15 text-secondary'
                              : 'bg-surface-high text-muted-fg',
                        )}
                      >
                        {mediaMonogram(row.title)}
                      </div>
                    </div>
                  </div>
                )}
              </For>
            </div>
          </div>
        </section>

        <section class="panel flex items-center justify-center p-8 sm:p-10">
          <div class="w-full max-w-md space-y-8">
            <div class="flex flex-wrap items-center justify-between gap-4">
              <Badge variant={isMockApiEnabled() ? 'accent' : 'secondary'}>{sessionLabel()}</Badge>

              <div class="inline-flex rounded-xl bg-surface-container p-1">
                <For each={themeModes}>
                  {(themeMode) => (
                    <button
                      type="button"
                      class={cn(
                        'rounded-lg px-3 py-1.5 text-[10px] font-semibold uppercase tracking-widest transition-all duration-200',
                        theme.mode() === themeMode.value
                          ? 'bg-surface-high text-fg'
                          : 'text-muted-fg hover:text-fg',
                      )}
                      onClick={() => theme.setMode(themeMode.value)}
                    >
                      {themeMode.label}
                    </button>
                  )}
                </For>
              </div>
            </div>

            <div>
              <p class="text-[10px] font-semibold uppercase tracking-widest text-muted-fg">Access your library</p>
              <h2 class="mt-4 text-4xl font-semibold text-fg leading-tight">
                {mode() === 'login' ? 'Enter Seen.' : 'Create your local session.'}
              </h2>
              <p class="mt-4 text-sm text-muted-fg leading-relaxed">{sessionSummary()}</p>
            </div>

            <form
              class="space-y-6"
              onSubmit={(event) => {
                event.preventDefault()
                void submit()
              }}
            >
              <div class="rounded-xl bg-surface-low p-1.5">
                <div class="grid grid-cols-2 gap-1.5">
                  <For each={formModes}>
                    {(formMode) => (
                      <button
                        type="button"
                        class={cn(
                          'rounded-lg px-4 py-3 text-sm font-semibold transition-all duration-200',
                          mode() === formMode.value
                            ? 'bg-surface-container text-fg'
                            : 'text-muted-fg hover:text-fg',
                        )}
                        onClick={() => setMode(formMode.value)}
                      >
                        {formMode.label}
                      </button>
                    )}
                  </For>
                </div>
              </div>

              <fieldset class="space-y-5" disabled={auth.isBusy()}>
                <label class="block space-y-2.5">
                  <span class="text-sm font-medium text-muted-fg">Email</span>
                  <Input
                    aria-label="Email"
                    type="email"
                    autocomplete="email"
                    autocapitalize="none"
                    placeholder="you@seen.local"
                    spellcheck={false}
                    value={email()}
                    onInput={(event) => setEmail(event.currentTarget.value)}
                    class="h-12"
                  />
                </label>

                <Show when={mode() === 'register'}>
                  <label class="block space-y-2.5">
                    <span class="text-sm font-medium text-muted-fg">Display Name</span>
                    <Input
                      aria-label="Display Name"
                      autocomplete="name"
                      placeholder="Movie Night Operator"
                      value={displayName()}
                      onInput={(event) => setDisplayName(event.currentTarget.value)}
                      class="h-12"
                    />
                  </label>
                </Show>

                <label class="block space-y-2.5">
                  <span class="text-sm font-medium text-muted-fg">Password</span>
                  <Input
                    aria-label="Password"
                    type="password"
                    autocomplete={mode() === 'register' ? 'new-password' : 'current-password'}
                    placeholder="Enter your password"
                    value={password()}
                    onInput={(event) => setPassword(event.currentTarget.value)}
                    class="h-12"
                  />
                </label>
              </fieldset>

              <div class="rounded-2xl bg-surface-low p-5">
                <p class="text-[10px] font-semibold uppercase tracking-widest text-muted-fg">Session details</p>
                <p class="mt-2 text-sm text-fg leading-relaxed">{sessionDetails()}</p>
              </div>

              <Show when={error()}>
                <div class="rounded-2xl bg-danger/15 px-5 py-4 text-sm text-danger">
                  {error()}
                </div>
              </Show>

              <Button type="submit" class="h-12 w-full justify-between px-5 text-base">
                <span>
                  {auth.isBusy()
                    ? 'Please wait...'
                    : mode() === 'login'
                      ? 'Sign In to Dashboard'
                      : 'Create Local Account'}
                </span>
                <ArrowRight class="h-4 w-4" />
              </Button>

              <div class="flex flex-wrap items-center justify-between gap-4 text-xs text-muted-fg">
                <p>Private by default. Your library stays attached to your own stack.</p>
                <button
                  type="button"
                  class="font-semibold text-fg transition-colors hover:text-primary"
                  onClick={() => setMode(mode() === 'login' ? 'register' : 'login')}
                >
                  {mode() === 'login' ? 'Need an account?' : 'Already have one?'}
                </button>
              </div>
            </form>
          </div>
        </section>
      </div>
    </main>
  )
}
