import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Inbox, ArrowUpRight, Pause, Clock } from 'lucide-react'
import { useHandoff } from '@/hooks/useHandoff'

export default function SessionQueuePage() {
  const navigate = useNavigate()
  const { queue, isLoadingQueue, loadQueue, claimHandoff } = useHandoff()

  useEffect(() => { loadQueue() }, [loadQueue])

  const handleClaim = async (item: typeof queue[0]) => {
    const result = await claimHandoff(item.session_id, item.handoff_id)
    if (result) navigate(`/pilot?sessionId=${item.session_id}`)
  }

  return (
    <div className="flex-1 p-6">
      <div className="flex items-center gap-2 mb-6">
        <Inbox size={20} className="text-accent" />
        <h1 className="text-xl font-heading font-bold text-heading">Session Queue</h1>
      </div>
      {isLoadingQueue ? (
        <p className="text-sm text-muted">Loading queue...</p>
      ) : queue.length === 0 ? (
        <div className="text-center py-12">
          <Inbox size={40} className="text-muted mx-auto mb-3" />
          <p className="text-sm text-muted">No sessions waiting</p>
        </div>
      ) : (
        <div className="space-y-2">
          {queue.map(item => (
            <div key={item.handoff_id} className="bg-card border border-default rounded-lg p-4 flex items-center justify-between hover:border-hover transition-colors">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  {item.intent === 'escalate' ? <ArrowUpRight size={14} className="text-danger" /> : <Pause size={14} className="text-warning" />}
                  <span className="text-sm font-medium text-heading">{item.problem_summary || 'Untitled session'}</span>
                  {item.priority === 'elevated' && <span className="text-[10px] px-1.5 py-0.5 rounded-full bg-danger-dim text-danger">Elevated</span>}
                </div>
                {item.engineer_notes && <p className="text-xs text-secondary">{item.engineer_notes}</p>}
                <div className="flex items-center gap-2 mt-1 text-xs text-muted">
                  <Clock size={10} />
                  <span>{new Date(item.created_at).toLocaleString()}</span>
                  {item.problem_domain && <span>· {item.problem_domain}</span>}
                </div>
              </div>
              <button onClick={() => handleClaim(item)} className="px-3 py-1.5 text-xs bg-accent text-white rounded-[5px] hover:bg-accent/90">Claim</button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
