import { useEffect, useState } from 'react'
import { Clock, CheckCircle, XCircle } from 'lucide-react'

interface PendingSkill {
  id: string
  name: string
  description: string
  code: string
  created_at: string
  tags: string[]
}

export function usePending() {
  const [pending, setPending] = useState<PendingSkill[]>([])

  const reload = () => {
    fetch('/bibividi/api/pending')
      .then(r => r.json())
      .then(setPending)
      .catch(() => {})
  }

  useEffect(() => {
    reload()
    const id = setInterval(reload, 15_000)
    return () => clearInterval(id)
  }, [])

  return { pending, reload }
}

interface Props {
  pending: PendingSkill[]
  reload: () => void
}

export default function PendingQueue({ pending, reload }: Props) {
  const act = (id: string, action: 'approve' | 'reject') => {
    fetch(`/bibividi/api/pending/${id}/${action}`, { method: 'POST' })
      .then(() => reload())
      .catch(() => {})
  }

  return (
    <div>
      <div className="page-title">
        <Clock size={20} color="var(--accent-light)" />
        Pending Skills
        <span className="muted fine" style={{ marginLeft: 4 }}>({pending.length})</span>
      </div>

      {pending.length === 0 ? (
        <div className="empty-state">
          <CheckCircle size={32} />
          <p>No skills awaiting review.</p>
          <p className="fine" style={{ marginTop: 4 }}>
            Auto-generated skills appear here for approval before execution.
          </p>
        </div>
      ) : (
        pending.map(s => (
          <div key={s.id} className="pending-card">
            <div className="pending-card-header">
              <strong>{s.name}</strong>
              <span className="mono muted fine">{s.id}</span>
            </div>
            <p className="muted">{s.description}</p>
            {s.tags.length > 0 && (
              <div className="tags">
                {s.tags.map(t => <span key={t} className="tag">{t}</span>)}
              </div>
            )}
            <pre className="code-preview">
              {s.code.slice(0, 800)}{s.code.length > 800 ? '\n…' : ''}
            </pre>
            <p className="muted fine">
              Generated: {new Date(s.created_at).toLocaleString()}
            </p>
            <div className="pending-actions">
              <button className="btn btn-success" onClick={() => act(s.id, 'approve')}>
                <CheckCircle size={14} /> Approve
              </button>
              <button className="btn btn-danger" onClick={() => act(s.id, 'reject')}>
                <XCircle size={14} /> Reject
              </button>
            </div>
          </div>
        ))
      )}
    </div>
  )
}
