'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { ChevronLeft, Archive, RotateCcw, Copy, Trash2, Loader2 } from 'lucide-react'

interface ArchivedList { id: string; name: string; itemCount: number; createdAt: string }

// Archive of dismissed lists — the reuse history. Reuse clones a list into a
// fresh active one; restore un-dismisses the original; delete prunes it.
export function ListArchive() {
  const router = useRouter()
  const [lists, setLists] = useState<ArchivedList[]>([])
  const [loaded, setLoaded] = useState(false)
  const [busy, setBusy] = useState<string | null>(null)

  const load = useCallback(async () => {
    const res = await fetch('/api/checklists?archived=1', { cache: 'no-store' })
    if (res.ok) setLists((await res.json()).lists || [])
    setLoaded(true)
  }, [])
  useEffect(() => { load() }, [load])

  const reuse = async (l: ArchivedList) => {
    setBusy(l.id)
    const res = await fetch(`/api/checklists/${l.id}/reuse`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
    setBusy(null)
    if (res.ok) { const { id } = await res.json(); router.push(`/list/${id}`) }
  }
  const restore = async (l: ArchivedList) => {
    setBusy(l.id)
    await fetch(`/api/checklists/${l.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ dismissed: false }) })
    setBusy(null)
    router.push(`/list/${l.id}`)
  }
  const del = async (l: ArchivedList) => {
    if (!confirm(`Permanently delete “${l.name}”? This can't be undone.`)) return
    setLists(ls => ls.filter(x => x.id !== l.id))
    await fetch(`/api/checklists/${l.id}`, { method: 'DELETE' })
  }

  return (
    <div className="min-h-screen max-w-md mx-auto flex flex-col">
      <header className="safe-top px-4 pb-3 flex items-center gap-2">
        <Link href="/" className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
          <ChevronLeft className="h-4 w-4" /> Dashboard
        </Link>
        <span className="ml-auto font-semibold inline-flex items-center gap-1.5"><Archive className="h-4 w-4 text-primary" /> List archive</span>
      </header>

      <main className="flex-1 px-4 pb-10 space-y-2">
        <p className="text-xs text-muted-foreground px-1">Dismissed lists are kept here. <strong>Reuse</strong> makes a fresh copy with everything unchecked.</p>

        {!loaded && <div className="py-10 text-center"><Loader2 className="h-5 w-5 animate-spin mx-auto text-muted-foreground" /></div>}
        {loaded && lists.length === 0 && <p className="text-sm text-muted-foreground text-center py-10">No dismissed lists yet.</p>}

        <ul className="space-y-2">
          {lists.map(l => (
            <li key={l.id} className="rounded-xl border border-border bg-card p-3">
              <div className="flex items-center gap-2">
                <div className="min-w-0 flex-1">
                  <div className="text-sm font-medium truncate">{l.name}</div>
                  <div className="text-xs text-muted-foreground">{l.itemCount} item{l.itemCount === 1 ? '' : 's'} · {new Date(l.createdAt).toLocaleDateString()}</div>
                </div>
                {busy === l.id && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
              </div>
              <div className="flex gap-2 mt-2">
                <button onClick={() => reuse(l)} disabled={!!busy} className="flex-1 inline-flex items-center justify-center gap-1.5 text-sm rounded-lg bg-primary text-primary-foreground px-2.5 h-8 disabled:opacity-50">
                  <Copy className="h-4 w-4" /> Reuse
                </button>
                <button onClick={() => restore(l)} disabled={!!busy} className="inline-flex items-center justify-center gap-1.5 text-sm rounded-lg border border-border px-2.5 h-8 hover:bg-muted disabled:opacity-50" title="Bring this exact list back">
                  <RotateCcw className="h-4 w-4" /> Restore
                </button>
                <button onClick={() => del(l)} disabled={!!busy} className="inline-flex items-center justify-center rounded-lg border border-border px-2.5 h-8 text-muted-foreground hover:text-destructive hover:bg-muted disabled:opacity-50" aria-label="Delete permanently">
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            </li>
          ))}
        </ul>
      </main>
    </div>
  )
}
