import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { Calendar, AlertTriangle, Clock, CheckCircle2, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { deadlinesApi, type DeadlineMessageResponse } from '@/api/deadlines.api'
import { formatDate } from '@/lib/utils'

function groupDeadlines(items: DeadlineMessageResponse[]) {
  const now = new Date()
  const todayEnd = new Date(now)
  todayEnd.setHours(23, 59, 59, 999)
  const weekEnd = new Date(now)
  weekEnd.setDate(weekEnd.getDate() + 7)
  const monthEnd = new Date(now)
  monthEnd.setDate(monthEnd.getDate() + 30)

  const overdue: DeadlineMessageResponse[] = []
  const today: DeadlineMessageResponse[] = []
  const thisWeek: DeadlineMessageResponse[] = []
  const later: DeadlineMessageResponse[] = []

  for (const item of items) {
    if (!item.deadline_at) continue
    const d = new Date(item.deadline_at)
    if (d < now) {
      overdue.push(item)
    } else if (d <= todayEnd) {
      today.push(item)
    } else if (d <= weekEnd) {
      thisWeek.push(item)
    } else {
      later.push(item)
    }
  }
  return { overdue, today, thisWeek, later }
}

function DeadlineItem({ item }: { item: DeadlineMessageResponse }) {
  const navigate = useNavigate()
  const deadlineDate = item.deadline_at ? new Date(item.deadline_at) : null

  return (
    <div
      className={`flex items-center gap-4 p-4 rounded-lg border bg-card hover:shadow-sm transition-shadow cursor-pointer ${item.is_overdue ? 'border-destructive/30 bg-destructive/5' : ''}`}
      onClick={() => navigate(`/messages/${item.id}`)}
    >
      <div className="flex-shrink-0">
        {item.is_overdue ? (
          <AlertTriangle className="h-5 w-5 text-destructive" />
        ) : (
          <Clock className="h-5 w-5 text-amber-500" />
        )}
      </div>
      <div className="flex-1 min-w-0">
        <p className="font-medium truncate">{item.subject || '(nessun oggetto)'}</p>
        <p className="text-xs text-muted-foreground">
          {item.direction === 'inbound' ? `Da: ${item.from_address}` : `A: ${(item.to_addresses ?? []).join(', ')}`}
        </p>
        {item.deadline_note && (
          <p className="text-xs text-muted-foreground italic mt-0.5">{item.deadline_note}</p>
        )}
      </div>
      <div className="flex-shrink-0 text-right">
        <p className={`text-sm font-semibold ${item.is_overdue ? 'text-destructive' : 'text-amber-600'}`}>
          {deadlineDate ? formatDate(deadlineDate.toISOString()) : '-'}
        </p>
        {item.is_overdue && (
          <p className="text-xs text-destructive">Scaduto</p>
        )}
      </div>
      <ExternalLink className="h-4 w-4 text-muted-foreground flex-shrink-0" />
    </div>
  )
}

function DeadlineGroup({ title, items, icon: Icon, color }: {
  title: string
  items: DeadlineMessageResponse[]
  icon: React.ComponentType<{ className?: string }>
  color: string
}) {
  if (items.length === 0) return null
  return (
    <div className="space-y-2">
      <div className={`flex items-center gap-2 ${color}`}>
        <Icon className="h-4 w-4" />
        <h3 className="font-semibold text-sm">{title} ({items.length})</h3>
      </div>
      <div className="space-y-2">
        {items.map((item) => (
          <DeadlineItem key={item.id} item={item} />
        ))}
      </div>
    </div>
  )
}

export function DeadlinesPage() {
  const [daysAhead, setDaysAhead] = useState(30)
  const [includeOverdue, setIncludeOverdue] = useState(true)

  const { data = [], isLoading } = useQuery({
    queryKey: ['deadlines', daysAhead, includeOverdue],
    queryFn: () => deadlinesApi.list({ days_ahead: daysAhead, include_overdue: includeOverdue }),
  })

  const groups = groupDeadlines(data)
  const total = data.length

  return (
    <div className="flex flex-col h-full">
      <div className="border-b bg-background px-6 py-4 flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold flex items-center gap-2">
            <Calendar className="h-5 w-5 text-primary" />
            Scadenzario
          </h1>
          <p className="text-sm text-muted-foreground">
            {total} messaggi con scadenze
          </p>
        </div>
        <div className="flex items-center gap-4">
          <label className="flex items-center gap-2 text-sm cursor-pointer">
            <input
              type="checkbox"
              checked={includeOverdue}
              onChange={(e) => setIncludeOverdue(e.target.checked)}
              className="rounded"
            />
            Includi scaduti
          </label>
          <select
            value={daysAhead}
            onChange={(e) => setDaysAhead(Number(e.target.value))}
            className="text-sm border rounded-md px-3 py-1.5 bg-background"
          >
            <option value={7}>Prossimi 7 giorni</option>
            <option value={30}>Prossimi 30 giorni</option>
            <option value={90}>Prossimi 90 giorni</option>
            <option value={365}>Prossimo anno</option>
          </select>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-6">
        {isLoading ? (
          <div className="flex justify-center py-12">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          </div>
        ) : total === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <CheckCircle2 className="h-12 w-12 mx-auto mb-4 opacity-30 text-green-500" />
            <p className="text-lg font-medium">Nessuna scadenza trovata</p>
            <p className="text-sm mt-1">
              Le scadenze si impostano dal dettaglio di ogni messaggio.
            </p>
          </div>
        ) : (
          <div className="max-w-3xl mx-auto space-y-8">
            <DeadlineGroup
              title="Scaduti"
              items={groups.overdue}
              icon={AlertTriangle}
              color="text-destructive"
            />
            <DeadlineGroup
              title="Oggi"
              items={groups.today}
              icon={Clock}
              color="text-amber-600"
            />
            <DeadlineGroup
              title="Questa settimana"
              items={groups.thisWeek}
              icon={Calendar}
              color="text-blue-600"
            />
            <DeadlineGroup
              title="Successivamente"
              items={groups.later}
              icon={Calendar}
              color="text-muted-foreground"
            />
          </div>
        )}
      </div>
    </div>
  )
}
