'use client'
import React, { useState } from 'react'
import type { Topic, MicroLearning, CompletePayload } from '@/types'
import { MicroLearningRenderer } from '@/components/micro-learnings/MicroLearningRenderer'
import { StatusBadge } from '@/components/ui/StatusBadge'
import { Button } from '@/components/ui/Button'
import { postComplete } from '@/lib/services'
import { usePBCollection } from '@/lib/hooks/usePBCollection'

interface TopicCardProps {
  topic: Topic
  weekNumber: number
  userId: string
  isCompleted?: boolean
  onComplete: (topicId: string) => void
}

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 function TopicCard({ topic, weekNumber, userId, isCompleted, onComplete }: TopicCardProps) {
  const [expanded, setExpanded] = useState(false)
  const [selectedMlId, setSelectedMlId] = useState<string | null>(null)
  const [completing, setCompleting] = useState(false)

  const { items: microLearnings } = usePBCollection<MicroLearning>('micro_learnings', {
    filter: `topic="${topic.id}" && status="published"`,
  })

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

  async function handleComplete() {
    if (!selectedMl) return
    setCompleting(true)
    try {
      const payload: CompletePayload = {
        userId,
        topicId: topic.id,
        microLearningId: selectedMl.id,
        weekNumber,
      }
      await postComplete(payload)
      onComplete(topic.id)
    } catch {
      // user can retry
    } finally {
      setCompleting(false)
    }
  }

  return (
    <div
      style={{
        background: isCompleted ? 'var(--bg-warm)' : 'var(--bg)',
        border: `1.5px solid ${isCompleted ? 'var(--success)' : 'var(--cream)'}`,
        borderRadius: 'var(--r-md)',
        overflow: 'hidden',
        transition: 'border-color 200ms',
      }}
    >
      <button
        onClick={() => setExpanded((e) => !e)}
        style={{
          width: '100%',
          background: 'none',
          border: 'none',
          padding: 'var(--s-4)',
          textAlign: 'left',
          cursor: 'pointer',
          display: 'flex',
          gap: 'var(--s-3)',
          alignItems: 'flex-start',
          minHeight: '44px',
          fontFamily: 'var(--font-sans)',
        }}
        aria-expanded={expanded}
      >
        <span
          style={{
            width: '24px',
            height: '24px',
            borderRadius: '50%',
            background: isCompleted ? 'var(--success)' : 'var(--bg-warm)',
            color: isCompleted ? 'var(--teal-900)' : 'var(--fg-muted)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '14px',
            fontWeight: 700,
            flexShrink: 0,
            marginTop: '2px',
          }}
        >
          {isCompleted ? '✓' : '○'}
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h4
            style={{
              margin: '0 0 var(--s-1)',
              fontSize: 'var(--t-body)',
              fontWeight: 600,
              color: isCompleted ? 'var(--fg-muted)' : 'var(--fg)',
              textDecoration: isCompleted ? 'line-through' : 'none',
            }}
          >
            {topic.title}
          </h4>
          <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap', alignItems: 'center' }}>
            <StatusBadge status={topic.difficulty} />
            <span
              style={{
                fontSize: 'var(--t-label)',
                fontFamily: 'var(--font-mono)',
                color: 'var(--fg-subtle)',
                textTransform: 'uppercase',
                letterSpacing: 'var(--label-ls)',
              }}
            >
              {microLearnings.length} activities
            </span>
          </div>
        </div>
        <span style={{ color: 'var(--fg-muted)', fontSize: '18px', flexShrink: 0 }}>
          {expanded ? '−' : '+'}
        </span>
      </button>

      {expanded && (
        <div
          style={{
            padding: 'var(--s-4)',
            borderTop: '1px solid var(--cream)',
            display: 'flex',
            flexDirection: 'column',
            gap: 'var(--s-4)',
          }}
        >
          {/* Topic body */}
          <p style={{ margin: 0, fontSize: 'var(--t-body)', lineHeight: 1.65, color: 'var(--fg)' }}>
            {topic.body}
          </p>

          {/* Type picker */}
          {microLearnings.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)',
                }}
              >
                Choose an activity
              </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-1) var(--s-3)',
                      fontSize: 'var(--t-small)',
                      fontFamily: 'var(--font-sans)',
                      fontWeight: 500,
                      cursor: 'pointer',
                      minHeight: '36px',
                      transition: 'background 150ms, color 150ms',
                    }}
                  >
                    {TYPE_LABELS[ml.type] ?? ml.type}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Selected micro-learning */}
          {selectedMl && (
            <div
              style={{
                background: 'var(--bg-warm)',
                borderRadius: 'var(--r-md)',
                padding: 'var(--s-4)',
              }}
            >
              <MicroLearningRenderer
                content={selectedMl.content}
                onComplete={() => void handleComplete()}
              />
            </div>
          )}

          {isCompleted && !selectedMl && (
            <div
              style={{
                textAlign: 'center',
                color: 'var(--teal-700)',
                fontSize: 'var(--t-small)',
                fontWeight: 500,
              }}
            >
              Completed — well done!
            </div>
          )}
        </div>
      )}
    </div>
  )
}
