'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { ClipboardList, Plus, ChevronRight, ChevronDown, X, Check, Circle, CheckCircle2, Archive, Users } from 'lucide-react'

interface ListItem { id: string; title: string; done: boolean }
interface ChecklistSummary { id: string; name: string; shared?: boolean; items: ListItem[] }

// Dashboard card: active special lists (camping trip, party prep…) with
// progress, inline create, and expandable items. Items drag to the Focus
// card (and between lists); focus items drop onto a list row to move in.
export function ChecklistsCard() {
  const [lists, setLists] = useState<ChecklistSummary[]>([])
  const [creating, setCreating] = useState(false)
  const [name, setName] = useState('')
  const [dragOver, setDragOver] = useState<string | null>(null)
  const [expanded, setExpanded] = useState<Set<string>>(new Set())

  const load = useCallback(async () => {
    const res = await fetch('/api/checklists', { cache: 'no-store' })
    if (res.ok) setLists((await res.json()).lists || [])
  }, [])
  useEffect(() => {
    load()
    const onRefresh = () => load()
    window.addEventListener('lists-refresh', onRefresh)
    return () => window.removeEventListener('lists-refresh', onRefresh)
  }, [load])

  const toggleExpand = (id: string) =>
    setExpanded(s => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n })

  const toggleItem = async (i: ListItem) => {
    setLists(ls => ls.map(l => ({ ...l, items: l.items.map(x => x.id === i.id ? { ...x, done: !i.done } : x) })))
    await fetch(`/api/checklist-items/${i.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ done: !i.done }) })
  }

  // Drop handler for a list row: accepts a reminder (moves it into the list,
  // deleting the reminder — and any Focus pin cascades) or a checklist item
  // from another list (moves it across).
  const onDropOnList = async (e: React.DragEvent, listId: string) => {
    e.preventDefault()
    setDragOver(null)
    try {
      const reminderRaw = e.dataTransfer.getData('application/x-reminder')
      if (reminderRaw) {
        const { id, title } = JSON.parse(reminderRaw) as { id: string; title: string }
        if (!id || !title) return
        const listName = lists.find(l => l.id === listId)?.name || 'this list'
        if (!confirm(`Move to “${listName}”? The reminder will be deleted (also in Apple).\n\n“${title}”`)) return
        const res = await fetch(`/api/checklists/${listId}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) })
        if (!res.ok) return
        await fetch(`/api/reminders/${id}`, { method: 'DELETE' })
        load()
        window.dispatchEvent(new Event('focus-refresh')) // pin (if any) cascaded away
        return
      }
      const itemRaw = e.dataTransfer.getData('application/x-checklist-item')
      if (itemRaw) {
        const { id, title, listId: fromId } = JSON.parse(itemRaw) as { id: string; title: string; listId: string }
        if (!id || !title || fromId === listId) return
        const res = await fetch(`/api/checklists/${listId}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) })
        if (!res.ok) return
        await fetch(`/api/checklist-items/${id}`, { method: 'DELETE' })
        load()
      }
    } catch { /* malformed payload — ignore */ }
  }

  const acceptsDrag = (e: React.DragEvent) =>
    e.dataTransfer.types.includes('application/x-checklist-item') ||
    e.dataTransfer.types.includes('application/x-reminder')

  const create = async () => {
    const n = name.trim()
    if (!n) return
    setName(''); setCreating(false)
    await fetch('/api/checklists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: n }) })
    load()
  }

  return (
    <div className="rounded-2xl border border-border bg-card p-4 space-y-2">
      <div className="flex items-center gap-2">
        <ClipboardList className="h-4 w-4 text-primary" />
        <span className="text-sm font-semibold">Lists</span>
        <Link href="/lists" className="ml-auto p-1.5 rounded hover:bg-muted text-muted-foreground" aria-label="List archive" title="Archived lists — reuse past lists">
          <Archive className="h-4 w-4" />
        </Link>
        <button onClick={() => setCreating(c => !c)} className="p-1.5 rounded hover:bg-muted text-muted-foreground" aria-label="New list">
          {creating ? <X className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
        </button>
      </div>

      {creating && (
        <div className="flex gap-2">
          <input
            autoFocus
            value={name}
            onChange={e => setName(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') create(); if (e.key === 'Escape') setCreating(false) }}
            placeholder="List name (e.g. Camping trip)…"
            className="flex-1 rounded-lg border border-input bg-background px-3 h-9 text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          />
          <button onClick={create} className="rounded-lg bg-primary text-primary-foreground px-3 h-9 inline-flex items-center" aria-label="Create"><Check className="h-4 w-4" /></button>
        </div>
      )}

      {lists.length === 0 && !creating && (
        <p className="text-xs text-muted-foreground">No special lists — tap + for a trip, project, or party list.</p>
      )}

      {lists.length > 0 && (
        <ul className="space-y-1.5">
          {lists.map(l => {
            const done = l.items.filter(i => i.done).length
            const isOpen = expanded.has(l.id)
            const sorted = [...l.items].sort((a, b) => Number(a.done) - Number(b.done))
            return (
              <li key={l.id} className="space-y-1">
                <div
                  draggable
                  onDragStart={e => {
                    e.dataTransfer.setData('application/x-checklist', JSON.stringify({ id: l.id, name: l.name }))
                    e.dataTransfer.effectAllowed = 'copy'
                  }}
                  onDragOver={e => { if (acceptsDrag(e)) { e.preventDefault(); setDragOver(l.id) } }}
                  onDragLeave={() => setDragOver(d => (d === l.id ? null : d))}
                  onDrop={e => onDropOnList(e, l.id)}
                  className={`flex items-center gap-1.5 rounded-xl border bg-background px-2 py-2 transition-colors ${dragOver === l.id ? 'border-primary ring-2 ring-primary/30' : 'border-border hover:border-primary/40'}`}
                >
                  <button onClick={() => toggleExpand(l.id)} className="p-1 rounded hover:bg-muted text-muted-foreground" aria-label={isOpen ? 'Collapse' : 'Expand'}>
                    {isOpen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
                  </button>
                  <Link href={`/list/${l.id}`} draggable={false} className="flex items-center gap-2 min-w-0 flex-1">
                    <span className="text-sm min-w-0 flex-1 truncate">{l.name}</span>
                    {l.shared && <Users className="h-3.5 w-3.5 shrink-0 text-primary" aria-label="Shared with the household" />}
                    <span className="text-xs rounded-full bg-muted px-2 py-0.5 text-muted-foreground">{done}/{l.items.length}</span>
                  </Link>
                </div>
                {isOpen && sorted.length > 0 && (
                  <ul className="pl-8 pr-1 space-y-1">
                    {sorted.map(i => (
                      <li
                        key={i.id}
                        draggable
                        onDragStart={e => {
                          e.dataTransfer.setData('application/x-checklist-item', JSON.stringify({ id: i.id, title: i.title, listId: l.id }))
                          e.dataTransfer.effectAllowed = 'move'
                        }}
                        className="flex items-center gap-2 text-sm"
                      >
                        <button onClick={() => toggleItem(i)} className={i.done ? 'text-emerald-600' : 'text-muted-foreground hover:text-primary'} aria-label="Toggle done">
                          {i.done ? <CheckCircle2 className="h-4 w-4" /> : <Circle className="h-4 w-4" />}
                        </button>
                        <span title={i.title} className={`min-w-0 flex-1 truncate ${i.done ? 'line-through text-muted-foreground' : ''}`}>{i.title}</span>
                      </li>
                    ))}
                  </ul>
                )}
                {isOpen && sorted.length === 0 && (
                  <p className="pl-8 text-xs text-muted-foreground">Empty list.</p>
                )}
              </li>
            )
          })}
        </ul>
      )}
    </div>
  )
}
