'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { ListTodo, CalendarClock, Lightbulb, Flag, ChevronRight, Repeat } from 'lucide-react'

interface Reminder { id: string; title: string; dueDate: string | null; priority: number | null; flagged: boolean; list: string | null; overdue: boolean }
interface EventItem { id: string; title: string; startsAt: string; allDay: boolean; location: string | null; calendar: string | null; recurrence: string | null }
interface Thought { id: string; body: string; tags: string[]; pinned: boolean }

function timeLabel(iso: string, allDay = false): string {
  const d = new Date(iso)
  const today = new Date(); today.setHours(0, 0, 0, 0)
  const day = new Date(d); day.setHours(0, 0, 0, 0)
  const days = Math.round((day.getTime() - today.getTime()) / 86400000)
  const dayStr = days === 0 ? 'Today' : days === 1 ? 'Tomorrow' : d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' })
  if (allDay) return dayStr
  return `${dayStr} ${d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })}`
}

export function Overview() {
  const [data, setData] = useState<{ reminders: Reminder[]; events: EventItem[]; thoughts: Thought[] } | null>(null)

  const load = useCallback(async () => {
    const res = await fetch('/api/overview', { cache: 'no-store' })
    if (res.ok) setData(await res.json())
  }, [])

  useEffect(() => {
    load()
    const onUp = () => load()
    window.addEventListener('capture-uploaded', onUp)
    const t = setInterval(load, 6000)
    return () => { window.removeEventListener('capture-uploaded', onUp); clearInterval(t) }
  }, [load])

  const reminders = data?.reminders || []
  const events = data?.events || []
  const thoughts = data?.thoughts || []

  return (
    <div className="space-y-3">
      <Card icon={ListTodo} title="Today" count={reminders.length} href="/reminders">
        {reminders.length === 0 ? (
          <Empty>Nothing due</Empty>
        ) : (
          <ul className="space-y-1.5">
            {reminders.slice(0, 6).map(r => (
              <li
                key={r.id}
                draggable
                onDragStart={e => {
                  e.dataTransfer.setData('application/x-reminder', JSON.stringify({ id: r.id, title: r.title }))
                  e.dataTransfer.effectAllowed = 'move'
                }}
                className="flex items-center gap-2 text-sm"
              >
                <span className={`h-1.5 w-1.5 rounded-full shrink-0 ${r.overdue ? 'bg-destructive' : 'bg-primary'}`} />
                <span className="truncate" title={r.title}>{r.title}</span>
                {r.flagged && <Flag className="h-3 w-3 text-amber-500 shrink-0" />}
                <span className="ml-auto text-xs text-muted-foreground shrink-0">
                  {r.dueDate ? timeLabel(r.dueDate) : r.list || ''}
                </span>
              </li>
            ))}
          </ul>
        )}
      </Card>

      <Card icon={CalendarClock} title="Up next" count={events.length}>
        {events.length === 0 ? (
          <Empty>No upcoming events</Empty>
        ) : (
          <ul className="space-y-1.5">
            {events.slice(0, 5).map(e => (
              <li key={e.id} className="flex items-center gap-2 text-sm">
                <span className="h-1.5 w-1.5 rounded-full bg-violet-500 shrink-0" />
                <span className="truncate" title={e.title}>{e.title}</span>
                {e.recurrence && <Repeat className="h-3 w-3 text-violet-500 shrink-0" aria-label={e.recurrence} />}
                <span className="ml-auto text-xs text-muted-foreground shrink-0">{timeLabel(e.startsAt, e.allDay)}</span>
              </li>
            ))}
          </ul>
        )}
      </Card>

      <Card icon={Lightbulb} title="Thoughts" count={thoughts.length} href="/thoughts">
        {thoughts.length === 0 ? (
          <Empty>No thoughts logged yet</Empty>
        ) : (
          <ul className="space-y-1.5">
            {thoughts.slice(0, 5).map(t => (
              <li key={t.id} className="text-sm flex items-start gap-2">
                {t.pinned && <span className="text-amber-500 shrink-0">★</span>}
                <span className="line-clamp-2" title={t.body}>{t.body}</span>
              </li>
            ))}
          </ul>
        )}
      </Card>
    </div>
  )
}

function Card({ icon: Icon, title, count, href, children }: { icon: typeof ListTodo; title: string; count: number; href?: string; children: React.ReactNode }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <div className="flex items-center gap-2 mb-2">
        <Icon className="h-4 w-4 text-muted-foreground" />
        {href ? (
          <Link href={href} className="text-sm font-semibold inline-flex items-center gap-0.5 hover:text-primary">
            {title} <ChevronRight className="h-3.5 w-3.5" />
          </Link>
        ) : (
          <span className="text-sm font-semibold">{title}</span>
        )}
        {count > 0 && <span className="ml-auto text-xs rounded-full bg-muted px-2 py-0.5 text-muted-foreground">{count}</span>}
      </div>
      {children}
    </div>
  )
}

function Empty({ children }: { children: React.ReactNode }) {
  return <p className="text-sm text-muted-foreground">{children}</p>
}
