'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

interface Task {
  id: string
  title: string
  description: string | null
  phase: number
  status: string
  assignee: string | null
  sortOrder: number
}

const statusLabels: Record<string, string> = { todo: 'To Do', in_progress: 'In Progress', done: 'Done' }
const statusColors: Record<string, string> = {
  todo: 'bg-slate-500/10 border-slate-500/20',
  in_progress: 'bg-amber-500/10 border-amber-500/20',
  done: 'bg-green-500/10 border-green-500/20',
}
const dotColors: Record<string, string> = { todo: 'bg-slate-400', in_progress: 'bg-amber-400', done: 'bg-green-400' }
const phaseNames: Record<number, string> = { 1: 'Phase 1 — Seed Content', 2: 'Phase 2 — Build Presence', 3: 'Phase 3 — Launch' }

export default function ChecklistPage() {
  const [tasks, setTasks] = useState<Task[]>([])
  const [loading, setLoading] = useState(true)
  const [showAdd, setShowAdd] = useState(false)
  const [newTitle, setNewTitle] = useState('')
  const [newPhase, setNewPhase] = useState(1)
  const [newDesc, setNewDesc] = useState('')
  const router = useRouter()

  const fetchTasks = () => {
    fetch('/api/tasks')
      .then(res => { if (res.status === 401) { router.push('/login'); return null } return res.json() })
      .then(d => { if (d) setTasks(d.tasks); setLoading(false) })
  }

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

  const updateStatus = async (id: string, status: string) => {
    await fetch('/api/tasks', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, status }) })
    fetchTasks()
  }

  const addTask = async () => {
    if (!newTitle.trim()) return
    await fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: newTitle, description: newDesc || null, phase: newPhase, sortOrder: tasks.length }) })
    setNewTitle(''); setNewDesc(''); setShowAdd(false)
    fetchTasks()
  }

  if (loading) return <div className="flex items-center justify-center h-full"><div className="text-brand-muted">Loading...</div></div>

  const columns = ['todo', 'in_progress', 'done']

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-brand-text">Launch Checklist</h1>
          <p className="text-brand-muted text-sm mt-1">Track progress across all launch phases</p>
        </div>
        <button onClick={() => setShowAdd(!showAdd)} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">
          + Add Task
        </button>
      </div>

      {/* Add Task Modal */}
      {showAdd && (
        <div className="bg-brand-card border border-brand-border rounded-xl p-6 space-y-4">
          <input value={newTitle} onChange={e => setNewTitle(e.target.value)} placeholder="Task title" className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text placeholder-brand-muted/50 focus:outline-none focus:border-brand-accent" />
          <textarea value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="Description (optional)" rows={2} className="w-full bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text placeholder-brand-muted/50 focus:outline-none focus:border-brand-accent" />
          <div className="flex items-center gap-4">
            <select value={newPhase} onChange={e => setNewPhase(Number(e.target.value))} className="bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text focus:outline-none focus:border-brand-accent">
              <option value={1}>Phase 1</option>
              <option value={2}>Phase 2</option>
              <option value={3}>Phase 3</option>
            </select>
            <button onClick={addTask} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">Add</button>
            <button onClick={() => setShowAdd(false)} className="text-brand-muted hover:text-brand-text text-sm px-4 py-2 transition-colors">Cancel</button>
          </div>
        </div>
      )}

      {/* Kanban Board */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {columns.map(status => (
          <div key={status}>
            <div className="flex items-center gap-2 mb-4">
              <div className={`w-2.5 h-2.5 rounded-full ${dotColors[status]}`} />
              <h3 className="text-sm font-semibold text-brand-text uppercase tracking-wider">{statusLabels[status]}</h3>
              <span className="text-xs text-brand-muted ml-auto">{tasks.filter(t => t.status === status).length}</span>
            </div>
            <div className="space-y-3">
              {[1, 2, 3].map(phase => {
                const phaseTasks = tasks.filter(t => t.status === status && t.phase === phase)
                if (phaseTasks.length === 0) return null
                return (
                  <div key={phase}>
                    <p className="text-xs text-brand-muted font-medium mb-2 px-1">{phaseNames[phase]}</p>
                    {phaseTasks.map(task => (
                      <div key={task.id} className={`${statusColors[status]} border rounded-lg p-4 mb-2`}>
                        <p className="text-sm font-medium text-brand-text">{task.title}</p>
                        {task.description && <p className="text-xs text-brand-muted mt-1">{task.description}</p>}
                        {task.assignee && <p className="text-xs text-brand-accent mt-1">@{task.assignee}</p>}
                        <div className="flex gap-2 mt-3">
                          {status !== 'todo' && (
                            <button onClick={() => updateStatus(task.id, status === 'done' ? 'in_progress' : 'todo')} className="text-xs text-brand-muted hover:text-brand-text transition-colors">← Back</button>
                          )}
                          {status !== 'done' && (
                            <button onClick={() => updateStatus(task.id, status === 'todo' ? 'in_progress' : 'done')} className="text-xs text-brand-accent hover:text-brand-accent-hover transition-colors ml-auto">
                              {status === 'todo' ? 'Start →' : 'Complete ✓'}
                            </button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )
              })}
              {tasks.filter(t => t.status === status).length === 0 && (
                <div className="border border-dashed border-brand-border rounded-lg p-6 text-center">
                  <p className="text-xs text-brand-muted">No tasks</p>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
