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

interface ThemeCardProps {
  theme: Theme
  onUpdate: () => void
}

export function ThemeCard({ theme, onUpdate }: ThemeCardProps) {
  const [approving, setApproving] = useState(false)
  const [rejecting, setRejecting] = useState(false)
  const [toast, setToast] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  async function handleApprove() {
    setApproving(true)
    setError(null)
    setToast(null)
    try {
      // 1. Fetch all topics in this theme
      const topics = await pb.collection('topics').getFullList<{ id: string }>({
        filter: `theme="${theme.id}"`,
        fields: 'id',
      })

      // 2. Publish all topics
      await Promise.all(
        topics.map((t) => pb.collection('topics').update(t.id, { status: 'published' }))
      )

      // 3. Publish the theme
      await pb.collection('themes').update(theme.id, { status: 'published' })

      // 4. Trigger generation service
      const { queued } = await postGenerateAll(theme.id)
      setToast(`Generation queued for ${queued} micro-learnings`)
      onUpdate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Approval failed')
    } finally {
      setApproving(false)
    }
  }

  async function handleReject() {
    setRejecting(true)
    setError(null)
    try {
      await pb.collection('themes').update(theme.id, { status: 'rejected' })
      onUpdate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Rejection failed')
    } finally {
      setRejecting(false)
    }
  }

  const isPublished = theme.status === 'published'
  const isRejected = theme.status === 'rejected'

  return (
    <div
      style={{
        background: 'var(--bg)',
        border: '1.5px solid var(--cream)',
        borderRadius: 'var(--r-md)',
        padding: 'var(--s-4)',
        display: 'flex',
        flexDirection: 'column',
        gap: 'var(--s-3)',
        opacity: isRejected ? 0.6 : 1,
      }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 'var(--s-3)' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h3 style={{ margin: '0 0 var(--s-1)', fontSize: 'var(--t-body)', fontWeight: 700, color: 'var(--fg)' }}>
            {theme.title}
          </h3>
          <p style={{ margin: 0, fontSize: 'var(--t-small)', color: 'var(--fg-muted)', lineHeight: 1.5 }}>
            {theme.description}
          </p>
        </div>
        <StatusBadge status={theme.status} />
      </div>

      <div
        style={{
          fontSize: 'var(--t-label)',
          fontFamily: 'var(--font-mono)',
          color: 'var(--fg-subtle)',
          textTransform: 'uppercase',
          letterSpacing: 'var(--label-ls)',
        }}
      >
        {theme.source_documents.length} source doc{theme.source_documents.length !== 1 ? 's' : ''}
      </div>

      {toast && (
        <div style={{ background: 'var(--success)', color: 'var(--teal-900)', borderRadius: 'var(--r-sm)', padding: 'var(--s-2) var(--s-3)', fontSize: 'var(--t-small)', fontWeight: 500 }}>
          {toast}
        </div>
      )}

      {error && (
        <div style={{ background: '#f8d7da', color: '#c0392b', borderRadius: 'var(--r-sm)', padding: 'var(--s-2) var(--s-3)', fontSize: 'var(--t-small)' }}>
          {error}
        </div>
      )}

      <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap' }}>
        {!isRejected && (
          <Link href={`/admin/knowledge/${theme.id}`} style={{ textDecoration: 'none' }}>
            <Button variant="secondary" size="sm">Edit topics</Button>
          </Link>
        )}
        {!isPublished && !isRejected && (
          <>
            <Button variant="primary" size="sm" onClick={() => void handleApprove()} loading={approving}>
              Approve batch
            </Button>
            <Button variant="danger" size="sm" onClick={() => void handleReject()} loading={rejecting}>
              Reject
            </Button>
          </>
        )}
      </div>
    </div>
  )
}
