'use client'
import React, { useState } from 'react'
import type { Topic } from '@/types'
import { StatusBadge } from '@/components/ui/StatusBadge'
import { Button } from '@/components/ui/Button'
import { pb } from '@/lib/pocketbase'

interface TopicEditCardProps {
  topic: Topic
  onUpdate: () => void
}

const DIFFICULTY_COLORS: Record<Topic['difficulty'], string> = {
  introductory: 'var(--success)',
  intermediate: '#fff3cd',
  advanced: 'var(--accent-soft)',
}

export function TopicEditCard({ topic, onUpdate }: TopicEditCardProps) {
  const [expanded, setExpanded] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleApprove() {
    setSaving(true)
    setError(null)
    try {
      await pb.collection('topics').update(topic.id, { status: 'published' })
      onUpdate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to approve')
    } finally {
      setSaving(false)
    }
  }

  async function handleReject() {
    setSaving(true)
    setError(null)
    try {
      await pb.collection('topics').update(topic.id, { status: 'draft' })
      onUpdate()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to reject')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div
      style={{
        background: 'var(--bg)',
        border: '1.5px solid var(--cream)',
        borderRadius: 'var(--r-md)',
        overflow: 'hidden',
      }}
    >
      <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}
      >
        <div style={{ flex: 1, minWidth: 0 }}>
          <h4
            style={{
              margin: '0 0 var(--s-1)',
              fontSize: 'var(--t-body)',
              fontWeight: 600,
              color: 'var(--fg)',
            }}
          >
            {topic.title}
          </h4>
          <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap', alignItems: 'center' }}>
            <span
              style={{
                fontSize: 'var(--t-label)',
                fontFamily: 'var(--font-mono)',
                textTransform: 'uppercase',
                letterSpacing: 'var(--label-ls)',
                padding: '2px var(--s-2)',
                borderRadius: 'var(--r-pill)',
                background: DIFFICULTY_COLORS[topic.difficulty],
                color: 'var(--fg-muted)',
              }}
            >
              {topic.difficulty}
            </span>
            <StatusBadge status={topic.status} />
          </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)',
          }}
        >
          <p
            style={{
              margin: 0,
              fontSize: 'var(--t-body)',
              lineHeight: 1.65,
              color: 'var(--fg)',
            }}
          >
            {topic.body}
          </p>

          {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: '2px var(--s-3)',
                      fontSize: 'var(--t-small)',
                      color: 'var(--fg-muted)',
                    }}
                  >
                    {term}
                  </span>
                ))}
              </div>
            </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)', justifyContent: 'flex-end' }}>
            {topic.status !== 'draft' && (
              <Button
                variant="secondary"
                size="sm"
                onClick={() => void handleReject()}
                loading={saving}
              >
                Revert to draft
              </Button>
            )}
            {topic.status !== 'published' && (
              <Button
                variant="primary"
                size="sm"
                onClick={() => void handleApprove()}
                loading={saving}
              >
                Publish
              </Button>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
