import { useState } from 'react'
import type { PendingQuestion } from '../lib/api'
import { api } from '../lib/api'
import { relativeTime, absoluteTime } from '../lib/time'

const priorityBadge: Record<string, string> = {
  critical: 'bg-red-600 text-white',
  '1': 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
  '2': 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
  '3': 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
  '4': 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200',
  '5': 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',
}

const roleColor: Record<string, string> = {
  lead: 'text-emerald-600 dark:text-emerald-400',
  agent: 'text-amber-600 dark:text-amber-400',
}

function QuestionCard({ q, onAnswered }: { q: PendingQuestion; onAnswered: () => void }) {
  const [open, setOpen] = useState(false)
  const [answer, setAnswer] = useState('')
  const [busy, setBusy] = useState(false)

  async function submit() {
    if (!answer.trim() || busy) return
    setBusy(true)
    try {
      await api.questions.answer(q.id, answer.trim())
      setAnswer('')
      setOpen(false)
      onAnswered()
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 hover:border-gray-400 dark:hover:border-gray-500 transition-colors">
      <div className="p-3">
        <div className="flex items-start justify-between gap-3 mb-2">
          <div className="flex items-baseline gap-2 flex-wrap min-w-0">
            <span className={`font-mono text-[10px] uppercase tracking-wider font-semibold ${roleColor[q.from_role] ?? 'text-gray-700'}`}>
              {q.from_role}
            </span>
            <span className="font-mono text-[10px] text-gray-500 dark:text-gray-400">
              {q.from_id}
            </span>
            {q.plan_title && (
              <span className="font-mono text-[10px] text-gray-400 dark:text-gray-500 truncate">
                · {q.plan_title}
              </span>
            )}
            {q.task_title && (
              <span className="font-mono text-[10px] text-gray-400 dark:text-gray-500 truncate">
                / {q.task_title}
              </span>
            )}
          </div>
          <span className={`shrink-0 text-[10px] font-mono font-medium uppercase tracking-wider px-1.5 py-0.5 rounded ${priorityBadge[q.priority] ?? ''}`}>
            {q.priority === 'critical' ? 'crit' : `p${q.priority}`}
          </span>
        </div>

        <div className="text-sm text-gray-900 dark:text-gray-100 leading-relaxed mb-2">
          {q.question}
        </div>

        {q.context && (
          <div className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed mb-2 italic">
            {q.context}
          </div>
        )}

        <div className="flex items-center justify-between pt-2 border-t border-gray-100 dark:border-gray-700/50">
          <span className="font-mono text-[10px] tabular text-gray-400 dark:text-gray-500" title={absoluteTime(q.created_at)}>
            asked {relativeTime(q.created_at)}
          </span>
          {!open && (
            <button
              onClick={() => setOpen(true)}
              className="font-mono text-[10px] uppercase tracking-wider px-3 py-1 rounded bg-blue-600 hover:bg-blue-700 text-white cursor-pointer"
            >
              answer →
            </button>
          )}
        </div>

        {open && (
          <div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700/50">
            <div className="font-mono text-[9px] uppercase tracking-[0.12em] font-semibold text-blue-600 dark:text-blue-400 mb-1">
              &gt; director [joe]:
            </div>
            <textarea
              value={answer}
              onChange={(e) => setAnswer(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); submit() }
                if (e.key === 'Escape') { e.preventDefault(); setOpen(false); setAnswer('') }
              }}
              placeholder="Your answer…"
              autoFocus
              rows={3}
              className="w-full px-2.5 py-1.5 rounded border border-blue-200 dark:border-blue-900 bg-blue-50/30 dark:bg-blue-950/20 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-900"
            />
            <div className="flex items-center justify-end gap-2 mt-2">
              <span className="font-mono text-[9px] text-gray-400 mr-auto">cmd+enter to submit · esc to cancel</span>
              <button
                onClick={() => { setOpen(false); setAnswer('') }}
                disabled={busy}
                className="px-2.5 py-1 rounded text-[10px] font-mono uppercase tracking-wider text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer"
              >
                cancel
              </button>
              <button
                onClick={submit}
                disabled={busy || !answer.trim()}
                className="px-3 py-1 rounded text-[10px] font-mono uppercase tracking-wider bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50 cursor-pointer"
              >
                {busy ? 'sending…' : 'send answer'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export function PendingQuestions({
  questions,
  onChange,
}: {
  questions: PendingQuestion[]
  onChange: () => void
}) {
  return (
    <div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
      <div className="flex items-baseline justify-between mb-4">
        <h2 className="font-display text-xl font-medium text-gray-900 dark:text-gray-100">
          Pending Questions
        </h2>
        <span className="font-mono text-[10px] uppercase tracking-wider text-gray-400">
          {questions.length} {questions.length === 1 ? 'question' : 'questions'}
        </span>
      </div>

      {questions.length === 0 ? (
        <p className="font-mono text-xs text-gray-500 italic">No pending questions</p>
      ) : (
        <div className="space-y-2">
          {questions.map((q) => (
            <QuestionCard key={q.id} q={q} onAnswered={onChange} />
          ))}
        </div>
      )}
    </div>
  )
}
