'use client'
import React, { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { pb } from '@/lib/pocketbase'
import { postGenerateAll } from '@/lib/services'
import { TopicEditCard } from '@/components/admin/TopicEditCard'
import { Button } from '@/components/ui/Button'
import { StatusBadge } from '@/components/ui/StatusBadge'
import type { Theme, Topic } from '@/types'

export default function ThemeDetailPage() {
  const params = useParams()
  const themeId = typeof params.themeId === 'string' ? params.themeId : ''

  const [theme, setTheme] = useState<Theme | null>(null)
  const [topics, setTopics] = useState<Topic[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [publishingAll, setPublishingAll] = useState(false)
  const [approveToast, setApproveToast] = useState<string | null>(null)

  async function load() {
    setLoading(true)
    try {
      const [t, tList] = await Promise.all([
        pb.collection('themes').getOne<Theme>(themeId),
        pb.collection('topics').getFullList<Topic>({
          filter: `theme="${themeId}"`,
          sort: 'difficulty,title',
        }),
      ])
      setTheme(t)
      setTopics(tList)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [themeId])

  async function handleApproveBatch() {
    setPublishingAll(true)
    setApproveToast(null)
    try {
      // Publish all draft topics
      await Promise.all(
        topics
          .filter((t) => t.status === 'draft')
          .map((t) => pb.collection('topics').update(t.id, { status: 'published' })),
      )
      // Publish the theme
      await pb.collection('themes').update(themeId, { status: 'published' })
      // Trigger generation
      const { queued } = await postGenerateAll(themeId)
      setApproveToast(`Approved. Generation queued for ${queued} micro-learnings.`)
      void load()
    } catch (err) {
      setApproveToast(err instanceof Error ? err.message : 'Approval failed')
      void load()
    } finally {
      setPublishingAll(false)
    }
  }

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

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

  const draftCount = topics.filter((t) => t.status === 'draft').length
  const publishedCount = topics.filter((t) => t.status === 'published').length

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

      {/* Header */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--s-3)', marginBottom: 'var(--s-2)' }}>
          <h1
            style={{
              margin: 0,
              fontSize: 'var(--t-h3)',
              fontWeight: 700,
              color: 'var(--fg)',
              flex: 1,
            }}
          >
            {theme.title}
          </h1>
          <StatusBadge status={theme.status} />
        </div>
        <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)', lineHeight: 1.6 }}>
          {theme.description}
        </p>
      </div>

      {/* Stats + batch action */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--s-4)',
          flexWrap: 'wrap',
        }}
      >
        <span style={{ fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
          {publishedCount} published · {draftCount} draft
        </span>
        {theme.status !== 'published' && (
          <Button
            variant="primary"
            size="sm"
            onClick={() => void handleApproveBatch()}
            loading={publishingAll}
          >
            Approve batch{draftCount > 0 ? ` (${draftCount} draft${draftCount !== 1 ? 's' : ''})` : ''}
          </Button>
        )}
        {approveToast && (
          <span style={{ fontSize: 'var(--t-small)', color: 'var(--teal)', fontWeight: 500 }}>
            {approveToast}
          </span>
        )}
      </div>

      {/* Topics list */}
      {topics.length === 0 ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)' }}>
          No topics in this theme yet.
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
          {topics.map((topic) => (
            <TopicEditCard key={topic.id} topic={topic} onUpdate={() => void load()} />
          ))}
        </div>
      )}
    </div>
  )
}
