'use client'

import { useEffect, useState } from 'react'
import {
  ArrowLeft, ArrowRight, CheckCircle2, Circle, ListTree, Loader2, Trophy, X,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/lib/store'
import { getTheme } from '@/lib/theme'
import { DynIcon } from '@/lib/blocks/icons'
import { Button } from '@/components/ui/button'
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'
import { BlockRenderer } from '@/components/blocks/BlockRenderer'

export function PreviewView() {
  const course = useAppStore((s) => s.course)
  const courseLoading = useAppStore((s) => s.courseLoading)
  const closePreview = useAppStore((s) => s.closePreview)

  const [requestedLessonId, setRequestedLessonId] = useState<string | null>(null)
  const [explicitVisited, setExplicitVisited] = useState<Set<string>>(new Set())
  const [outlineOpen, setOutlineOpen] = useState(false)

  const lessons = course?.lessons ?? []
  // A aula ativa deriva da seleção explícita ou cai na primeira aula
  const activeLessonId = requestedLessonId ?? lessons[0]?.id ?? null
  const currentIndex = Math.max(
    0,
    lessons.findIndex((l) => l.id === activeLessonId)
  )
  const lesson = lessons.find((l) => l.id === activeLessonId)

  // Aulas visitadas = navegação explícita + a aula atual
  const visited = new Set(explicitVisited)
  if (activeLessonId) visited.add(activeLessonId)

  // Rola para o topo ao trocar de aula
  useEffect(() => {
    document.getElementById('preview-scroll')?.scrollTo({ top: 0 })
    window.scrollTo({ top: 0 })
  }, [activeLessonId])

  const progress = lessons.length > 0 ? Math.round((visited.size / lessons.length) * 100) : 0
  const allVisited = lessons.length > 0 && visited.size >= lessons.length
  const isLast = currentIndex >= lessons.length - 1

  const theme = getTheme(course?.theme)

  if (courseLoading || !course) {
    return (
      <div className="flex h-screen flex-col items-center justify-center gap-3 bg-white text-slate-500">
        <Loader2 className="h-8 w-8 animate-spin text-emerald-600" />
        <p className="text-sm">Carregando visualização...</p>
      </div>
    )
  }

  if (lessons.length === 0 || !lesson) {
    return (
      <div className="flex h-screen flex-col items-center justify-center gap-4 bg-white">
        <p className="text-sm text-slate-500">Este curso ainda não tem aulas.</p>
        <Button variant="outline" onClick={closePreview} className="gap-2">
          <X className="h-4 w-4" /> Fechar
        </Button>
      </div>
    )
  }

  const go = (index: number) => {
    if (index < 0 || index >= lessons.length) return
    selectLesson(lessons[index].id)
  }

  const selectLesson = (id: string) => {
    setExplicitVisited((prev) => {
      const next = new Set(prev)
      // Marca também a aula da qual estamos saindo (inclusive a aula inicial)
      if (activeLessonId) next.add(activeLessonId)
      next.add(id)
      return next
    })
    setRequestedLessonId(id)
  }

  const outline = (
    <nav aria-label="Conteúdo do curso" className="space-y-1">
      <p className="mb-3 px-2 text-[11px] font-bold tracking-widest text-slate-400 uppercase">
        Conteúdo do curso
      </p>
      {lessons.map((l, i) => {
        const active = l.id === lesson.id
        const done = visited.has(l.id) && !active
        return (
          <button
            key={l.id}
            type="button"
            onClick={() => {
              selectLesson(l.id)
              setOutlineOpen(false)
            }}
            className={cn(
              'flex w-full items-center gap-3 rounded-xl border px-3 py-2.5 text-left transition-colors',
              active
                ? 'border-transparent text-white shadow-sm'
                : 'border-transparent text-slate-600 hover:bg-slate-100'
            )}
            style={active ? { backgroundColor: theme.primary } : undefined}
            aria-current={active ? 'page' : undefined}
          >
            <span
              className={cn(
                'flex h-8 w-8 shrink-0 items-center justify-center rounded-lg',
                active ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-500'
              )}
            >
              <DynIcon name={l.icon} className="h-4 w-4" />
            </span>
            <span className="min-w-0 flex-1">
              <span className="block text-[11px] font-medium opacity-70">Aula {i + 1}</span>
              <span className="block truncate text-[13px] font-semibold">{l.title}</span>
            </span>
            {done && (
              <CheckCircle2 className={cn('h-4 w-4 shrink-0', active ? 'text-white' : 'text-emerald-500')} />
            )}
            {!done && !active && <Circle className="h-3 w-3 shrink-0 text-slate-300" />}
          </button>
        )
      })}
    </nav>
  )

  return (
    <div className="flex h-screen flex-col overflow-hidden bg-white">
      {/* Barra superior */}
      <header className="z-10 shrink-0 border-b border-slate-200 bg-white">
        <div className="flex h-14 items-center justify-between gap-3 px-4">
          <div className="flex min-w-0 items-center gap-2.5">
            <Button variant="ghost" size="icon" className="h-9 w-9" onClick={closePreview} aria-label="Fechar visualização">
              <X className="h-4.5 w-4.5" />
            </Button>
            <Button
              variant="outline" size="sm" className="h-9 gap-2 lg:hidden"
              onClick={() => setOutlineOpen(true)}
            >
              <ListTree className="h-4 w-4" />
              <span className="hidden sm:inline">Conteúdo</span>
            </Button>
            <div className="min-w-0">
              <p className="truncate text-sm font-bold text-slate-900">{course.title}</p>
              <p className="text-[11px] text-slate-400">
                Aula {currentIndex + 1} de {lessons.length} — visualização do aluno
              </p>
            </div>
          </div>
          <span
            className="shrink-0 rounded-full px-3 py-1 text-xs font-bold text-white"
            style={{ backgroundColor: theme.primary }}
          >
            {progress}% concluído
          </span>
        </div>
        {/* Barra de progresso */}
        <div className="h-1 w-full bg-slate-100" role="progressbar" aria-valuenow={progress} aria-valuemin={0} aria-valuemax={100}>
          <div
            className="h-full transition-all duration-500"
            style={{ width: `${progress}%`, backgroundColor: theme.primary }}
          />
        </div>
      </header>

      <div className="flex min-h-0 flex-1">
        {/* Índice (desktop) */}
        <aside className="hidden w-[280px] shrink-0 overflow-y-auto border-r border-slate-100 bg-slate-50/60 p-3 lg:block">
          {outline}
        </aside>

        {/* Conteúdo */}
        <main id="preview-scroll" className="flex-1 overflow-y-auto">
          <div
            className="mx-auto w-full max-w-3xl px-4 py-10 md:px-8"
            style={
              {
                '--cp': theme.primary,
                '--cpd': theme.primaryDark,
                '--cps': theme.soft,
                '--cpt': theme.tint,
                '--cg': theme.gradient,
              } as React.CSSProperties
            }
          >
            {/* Cabeçalho da aula */}
            <div className="mb-8">
              <p
                className="text-xs font-bold tracking-widest uppercase"
                style={{ color: theme.primaryDark }}
              >
                Aula {currentIndex + 1}
              </p>
              <h1 className="mt-1 text-2xl font-extrabold tracking-tight text-slate-900 md:text-3xl">
                {lesson.title}
              </h1>
            </div>

            {/* Blocos */}
            <div className="space-y-10">
              {lesson.blocks.length === 0 && (
                <p className="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-6 py-10 text-center text-sm text-slate-400">
                  Esta aula ainda não possui conteúdo.
                </p>
              )}
              {lesson.blocks.map((block) => (
                <BlockRenderer
                  key={block.id}
                  type={block.type}
                  data={block.data}
                  theme={theme}
                  mode="view"
                />
              ))}
            </div>

            {/* Conclusão */}
            {allVisited && isLast && (
              <div
                className="mt-12 flex items-center gap-4 rounded-2xl border p-6"
                style={{ borderColor: theme.soft, backgroundColor: theme.tint }}
                role="status"
              >
                <span
                  className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full text-white"
                  style={{ backgroundColor: theme.primary }}
                >
                  <Trophy className="h-6 w-6" />
                </span>
                <div>
                  <p className="text-base font-bold text-slate-900">Parabéns, curso concluído!</p>
                  <p className="text-sm text-slate-600">
                    Você visitou todas as {lessons.length} aulas deste curso.
                  </p>
                </div>
              </div>
            )}

            {/* Navegação */}
            <div className="mt-12 flex items-center justify-between gap-3 border-t border-slate-200 pt-6 pb-4">
              <Button
                variant="outline"
                className="gap-2"
                disabled={currentIndex === 0}
                onClick={() => go(currentIndex - 1)}
              >
                <ArrowLeft className="h-4 w-4" />
                <span className="hidden sm:inline">Aula anterior</span>
                <span className="sm:hidden">Anterior</span>
              </Button>
              <span className="text-xs font-medium text-slate-400 tabular-nums">
                {currentIndex + 1} / {lessons.length}
              </span>
              <Button
                className="gap-2 text-white"
                style={{ backgroundColor: theme.primary }}
                disabled={isLast}
                onClick={() => go(currentIndex + 1)}
              >
                <span className="hidden sm:inline">Próxima aula</span>
                <span className="sm:hidden">Próxima</span>
                <ArrowRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </main>
      </div>

      {/* Índice (mobile) */}
      <Sheet open={outlineOpen} onOpenChange={setOutlineOpen}>
        <SheetContent side="left" className="w-[300px] sm:max-w-[300px]">
          <SheetHeader className="sr-only">
            <SheetTitle>Conteúdo do curso</SheetTitle>
          </SheetHeader>
          <div className="pt-2">{outline}</div>
        </SheetContent>
      </Sheet>
    </div>
  )
}
