'use client'
import React, { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { pb } from '@/lib/pocketbase'
import { getAuthUser } from '@/lib/auth'
import { MicroLearningRenderer } from '@/components/micro-learnings/MicroLearningRenderer'
import { StatusBadge } from '@/components/ui/StatusBadge'
import { postComplete } from '@/lib/services'
import type { Topic, MicroLearning } from '@/types'

const TYPE_LABELS: Record<string, string> = {
  concept_explainer: 'Explainer',
  scenario_quiz: 'Quiz',
  misconceptions: 'Myths',
  how_to: 'How-to',
  comparison_card: 'Compare',
  reflection_prompt: 'Reflect',
  flashcard_set: 'Flashcards',
  case_study: 'Case study',
  glossary_anchor: 'Glossary',
  myth_vs_evidence: 'Evidence',
}

export default function TopicDetailPage() {
  const params = useParams()
  const topicId = typeof params.topicId === 'string' ? params.topicId : ''
  const user = getAuthUser()

  const [topic, setTopic] = useState<Topic | null>(null)
  const [microLearnings, setMicroLearnings] = useState<MicroLearning[]>([])
  const [selectedMlId, setSelectedMlId] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [completed, setCompleted] = useState(false)

  useEffect(() => {
    async function load() {
      setLoading(true)
      try {
        const [t, mls] = await Promise.all([
          pb.collection('topics').getOne<Topic>(topicId, { expand: 'theme,related_topics' }),
          pb.collection('micro_learnings').getFullList<MicroLearning>({
            filter: `topic="${topicId}" && status="published"`,
          }),
        ])
        setTopic(t)
        setMicroLearnings(mls)
        setError(null)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load')
      } finally {
        setLoading(false)
      }
    }
    void load()
  }, [topicId])

  async function handleComplete() {
    if (!user || !selectedMlId) return
    try {
      await postComplete({
        userId: user.id,
        topicId,
        microLearningId: selectedMlId,
        weekNumber: 0, // library mode — no specific week
      })
      setCompleted(true)
    } catch {
      // non-critical in library mode
    }
  }

  const selectedMl = microLearnings.find((ml) => ml.id === selectedMlId)

  if (loading) {
    return (
      <div style={{ color: 'var(--fg-muted)', padding: 'var(--s-6)' }}>Loading…</div>
    )
  }

  if (error || !topic) {
    return (
      <div
        style={{
          background: '#f8d7da',
          color: '#c0392b',
          borderRadius: 'var(--r-sm)',
          padding: 'var(--s-4)',
        }}
      >
        {error ?? 'Topic not found'}
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-5)' }}>
      {/* Back */}
      <Link
        href="/app/library"
        style={{
          color: 'var(--fg-muted)',
          fontSize: 'var(--t-small)',
          textDecoration: 'none',
          display: 'inline-flex',
          alignItems: 'center',
          gap: 'var(--s-1)',
        }}
      >
        ← Library
      </Link>

      {/* Header */}
      <div>
        {topic.expand?.theme && (
          <p
            style={{
              margin: '0 0 var(--s-2)',
              fontSize: 'var(--t-label)',
              fontFamily: 'var(--font-mono)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--label-ls)',
              color: 'var(--fg-muted)',
            }}
          >
            {topic.expand.theme.title}
          </p>
        )}
        <h1
          style={{
            margin: '0 0 var(--s-3)',
            fontSize: 'var(--t-h3)',
            fontWeight: 700,
            color: 'var(--fg)',
          }}
        >
          {topic.title}
        </h1>
        <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap' }}>
          <StatusBadge status={topic.difficulty} />
        </div>
      </div>

      {/* Body */}
      <p style={{ margin: 0, fontSize: 'var(--t-body)', lineHeight: 1.7, color: 'var(--fg)' }}>
        {topic.body}
      </p>

      {/* Key terms */}
      {topic.key_terms.length > 0 && (
        <div>
          <p
            style={{
              margin: '0 0 var(--s-2)',
              fontSize: 'var(--t-label)',
              fontFamily: 'var(--font-mono)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--label-ls)',
              color: 'var(--fg-muted)',
            }}
          >
            Key terms
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--s-2)' }}>
            {topic.key_terms.map((term) => (
              <span
                key={term}
                style={{
                  background: 'var(--bg-warm)',
                  borderRadius: 'var(--r-pill)',
                  padding: '4px var(--s-3)',
                  fontSize: 'var(--t-small)',
                  color: 'var(--fg-muted)',
                  border: '1px solid var(--cream)',
                }}
              >
                {term}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Related topics */}
      {topic.expand?.related_topics && topic.expand.related_topics.length > 0 && (
        <div>
          <p
            style={{
              margin: '0 0 var(--s-2)',
              fontSize: 'var(--t-label)',
              fontFamily: 'var(--font-mono)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--label-ls)',
              color: 'var(--fg-muted)',
            }}
          >
            Related topics
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
            {topic.expand.related_topics.map((rt) => (
              <Link
                key={rt.id}
                href={`/app/library/${rt.id}`}
                style={{ textDecoration: 'none' }}
              >
                <div
                  style={{
                    background: 'var(--bg-warm)',
                    borderRadius: 'var(--r-sm)',
                    padding: 'var(--s-3) var(--s-4)',
                    fontSize: 'var(--t-body)',
                    color: 'var(--fg)',
                    fontWeight: 500,
                    minHeight: '44px',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  {rt.title} →
                </div>
              </Link>
            ))}
          </div>
        </div>
      )}

      {/* Activity picker */}
      {microLearnings.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
          <p
            style={{
              margin: 0,
              fontSize: 'var(--t-label)',
              fontFamily: 'var(--font-mono)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--label-ls)',
              color: 'var(--fg-muted)',
            }}
          >
            Activities
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--s-2)' }}>
            {microLearnings.map((ml) => (
              <button
                key={ml.id}
                onClick={() => setSelectedMlId(ml.id === selectedMlId ? null : ml.id)}
                style={{
                  background: selectedMlId === ml.id ? 'var(--accent)' : 'var(--bg-warm)',
                  color: selectedMlId === ml.id ? 'var(--paper)' : 'var(--fg)',
                  border: `1.5px solid ${selectedMlId === ml.id ? 'var(--accent)' : 'var(--cream)'}`,
                  borderRadius: 'var(--r-pill)',
                  padding: 'var(--s-2) var(--s-4)',
                  fontSize: 'var(--t-small)',
                  fontFamily: 'var(--font-sans)',
                  fontWeight: 500,
                  cursor: 'pointer',
                  minHeight: '44px',
                  transition: 'background 150ms, color 150ms',
                }}
              >
                {TYPE_LABELS[ml.type] ?? ml.type}
              </button>
            ))}
          </div>

          {selectedMl && (
            <div
              style={{
                background: 'var(--bg-warm)',
                borderRadius: 'var(--r-md)',
                padding: 'var(--s-4)',
                marginTop: 'var(--s-2)',
              }}
            >
              {completed ? (
                <div
                  style={{
                    textAlign: 'center',
                    color: 'var(--teal-700)',
                    fontWeight: 600,
                    padding: 'var(--s-4)',
                  }}
                >
                  Completed!
                </div>
              ) : (
                <MicroLearningRenderer
                  content={selectedMl.content}
                  onComplete={() => void handleComplete()}
                />
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
