import { useTaskBoard } from '../hooks/useTaskBoard'

interface Task {
  task_id: string
  title: string
  status: 'open' | 'claimed' | 'active' | 'done' | 'failed' | 'blocked'
  recommended_tier?: string
  claimed_by?: string
  posted_at?: string
  domain?: string
  complexity?: string
}

function TierBadge({ tier }: { tier?: string }) {
  const colors: Record<string, string> = {
    fast: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
    standard: 'bg-sky-500/20 text-sky-400 border-sky-500/30',
    premium: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
  }
  const tierNormalized = (tier || 'standard').toLowerCase()
  return (
    <span className={`text-xs px-2 py-0.5 rounded-full border ${colors[tierNormalized] || colors.standard}`}>
      {tier || 'standard'}
    </span>
  )
}

function TaskCard({ task }: { task: Task }) {
  const truncateTitle = (title: string) => {
    return title.length > 60 ? title.slice(0, 60) + '...' : title
  }

  const getTimeSince = (timestamp?: string) => {
    if (!timestamp) return 'just now'
    const posted = new Date(timestamp)
    const now = new Date()
    const diffMs = now.getTime() - posted.getTime()
    const diffMins = Math.floor(diffMs / 60000)

    if (diffMins < 1) return 'just now'
    if (diffMins < 60) return `${diffMins}m ago`
    const diffHours = Math.floor(diffMins / 60)
    if (diffHours < 24) return `${diffHours}h ago`
    const diffDays = Math.floor(diffHours / 24)
    return `${diffDays}d ago`
  }

  return (
    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-lg p-3 hover:border-slate-600/50 transition-colors">
      <div className="flex items-start justify-between gap-2 mb-2">
        <p className="text-sm font-medium text-slate-200 leading-snug flex-1">
          {truncateTitle(task.title)}
        </p>
        <TierBadge tier={task.recommended_tier} />
      </div>

      {task.claimed_by && (
        <p className="text-xs text-sky-400 mb-1 truncate">
          ⚡ {task.claimed_by}
        </p>
      )}

      <div className="flex items-center justify-between text-xs text-slate-500">
        <span>{task.domain || 'general'}</span>
        <span>{getTimeSince(task.posted_at)}</span>
      </div>
    </div>
  )
}

function TaskColumn({
  title,
  tasks,
  color
}: {
  title: string
  tasks: Task[]
  color: string
}) {
  const colorClasses: Record<string, string> = {
    yellow: 'border-l-yellow-500/50 bg-yellow-500/5',
    blue: 'border-l-sky-500/50 bg-sky-500/5',
    green: 'border-l-emerald-500/50 bg-emerald-500/5',
  }

  return (
    <div className={`bg-slate-800/30 backdrop-blur-sm border border-slate-700/50 border-l-2 rounded-lg p-4 ${colorClasses[color] || ''}`}>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold text-slate-300 uppercase tracking-wider">
          {title}
        </h3>
        <span className="text-xs font-bold text-slate-400 bg-slate-900/50 px-2 py-1 rounded">
          {tasks.length}
        </span>
      </div>

      <div className="space-y-2 max-h-96 overflow-y-auto">
        {tasks.length === 0 ? (
          <p className="text-xs text-slate-600 text-center py-4">No tasks</p>
        ) : (
          tasks.map((task) => (
            <TaskCard key={task.task_id} task={task} />
          ))
        )}
      </div>
    </div>
  )
}

export default function TaskBoard() {
  const { data: tasksData, loading } = useTaskBoard()

  // Flatten all tasks from all dispatches
  const allTasks: Task[] = (tasksData?.dispatches || []).flatMap((d: any) => d.tasks || [])

  // Split tasks into columns by status
  const openTasks = allTasks.filter(t => t.status === 'open' || t.status === 'blocked')
  const activeTasks = allTasks.filter(t => t.status === 'claimed' || t.status === 'active')
  const doneTasks = allTasks.filter(t => t.status === 'done').reverse()

  if (loading) {
    return (
      <div>
        <h2 className="text-lg font-semibold text-slate-300 mb-4">Task Board</h2>
        <p className="text-sm text-slate-500">Loading tasks...</p>
      </div>
    )
  }

  return (
    <div>
      <h2 className="text-lg font-semibold text-slate-300 mb-4">Task Board</h2>

      {/* 3-column layout — stacks on mobile */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <TaskColumn title="Open" tasks={openTasks} color="yellow" />
        <TaskColumn title="Active" tasks={activeTasks} color="blue" />
        <TaskColumn title="Done" tasks={doneTasks} color="green" />
      </div>
    </div>
  )
}
