import Link from "next/link"
import { Fragment } from "react"
import { AlertTriangle, CalendarClock, Clock, CheckCircle2, Circle } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { priorityStyles } from "@/lib/ticket-priority-style"
import { cn } from "@/lib/utils"
import type { AgendaDataset, AgendaTicketSummary } from "@/lib/agenda-utils"

type AgendaSummaryViewProps = {
  data: AgendaDataset
  isLoading?: boolean
}

const statusIndicator: Record<string, { label: string; icon: React.ComponentType<{ className?: string }>; className: string }> = {
  on_track: { label: "No prazo", icon: Circle, className: "text-emerald-500" },
  at_risk: { label: "Em risco", icon: AlertTriangle, className: "text-amber-500" },
  breached: { label: "Violado", icon: AlertTriangle, className: "text-rose-500" },
  met: { label: "Concluído", icon: CheckCircle2, className: "text-emerald-500" },
}

export function AgendaSummaryView({ data, isLoading }: AgendaSummaryViewProps) {
  if (isLoading) {
    return (
      <Card>
        <CardContent className="space-y-4 py-6">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-24 w-full rounded-xl" />
          <Skeleton className="h-24 w-full rounded-xl" />
        </CardContent>
      </Card>
    )
  }

  const sections: Array<{
    key: keyof AgendaDataset["sections"]
    title: string
    empty: string
    icon: React.ComponentType<{ className?: string }>
    iconClass?: string
  }> = [
    { key: "upcoming", title: "Próximas", empty: "Nenhum compromisso para o período selecionado.", icon: CalendarClock, iconClass: "text-foreground" },
    { key: "overdue", title: "Atrasadas", empty: "Sem pendências atrasadas — ótimo trabalho!", icon: AlertTriangle, iconClass: "text-amber-500" },
    { key: "unscheduled", title: "Sem agendamento", empty: "Todos os tickets críticos têm agenda.", icon: Clock, iconClass: "text-foreground" },
    { key: "completed", title: "Concluídas", empty: "Ainda não há visitas concluídas neste período.", icon: CheckCircle2, iconClass: "text-foreground" },
  ]

  return (
    <div className="space-y-6">
      <KpiGrid data={data} />
      <div className="grid gap-6 lg:grid-cols-2">
        {sections.map((section) => {
          const items = data.sections[section.key]
          const SectionIcon = section.icon
          const visibleItems = items.slice(0, 3)
          const viewAllHref = buildSectionLink(section.key)
          return (
            <Card key={section.key} className="min-h-[320px]">
              <CardHeader className="flex flex-row items-center justify-between gap-2">
                <CardTitle className="flex items-center gap-2">
                  <SectionIcon className={cn("size-4", section.iconClass ?? "text-foreground")} />
                  {section.title}
                  {items.length > 0 ? (
                    <Badge variant="secondary" className="ml-2">
                      {items.length}
                    </Badge>
                  ) : null}
                </CardTitle>
                <Link
                  href={viewAllHref}
                  className="text-sm font-semibold text-[#006879] underline-offset-4 transition-colors hover:text-[#004d5a] hover:underline"
                >
                  Ver todos
                </Link>
              </CardHeader>
              <CardContent className="space-y-3">
                {items.length === 0 ? (
                  <p className="text-sm text-muted-foreground">{section.empty}</p>
                ) : (
                  <div className="space-y-3">
                    {visibleItems.map((item) => (
                      <AgendaSummaryRow key={`${section.key}-${item.id}`} item={item} />
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          )
        })}
      </div>
    </div>
  )
}

function KpiGrid({ data }: { data: AgendaDataset }) {
  const kpis = [
    { label: "Pendentes", value: data.kpis.pending, description: "Aguardando início" },
    { label: "Em andamento", value: data.kpis.inProgress, description: "Atividades em curso" },
    { label: "Pausados", value: data.kpis.paused, description: "Dependem de cliente/terceiros" },
    { label: "% fora do SLA", value: data.kpis.outsideSla, description: "Chamados com risco/violação" },
  ]

  return (
    <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
      {kpis.map((item) => (
        <Card
          key={item.label}
          className="rounded-2xl border border-border/60 bg-gradient-to-br from-white/95 via-white to-primary/5 shadow-sm"
        >
          <CardContent className="space-y-3 px-5 py-5">
            <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground/80">{item.label}</p>
            <p className="text-4xl font-semibold leading-tight text-neutral-900">{item.value}</p>
            <p className="text-sm text-muted-foreground">{item.description}</p>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

function AgendaSummaryRow({ item }: { item: AgendaTicketSummary }) {
  const status = statusIndicator[item.slaStatus ?? "on_track"] ?? statusIndicator.on_track

  return (
    <Link
      href={item.href}
      prefetch={false}
      className="block rounded-xl border border-border/60 bg-background/70 p-3 shadow-sm transition hover:border-primary/60 hover:shadow-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
      aria-label={`Abrir ticket #${item.reference}`}
    >
      <div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <div className="flex items-center gap-2 text-sm font-semibold text-foreground">
            <span>
              #{item.reference} · {item.subject}
            </span>
            {item.queue ? (
              <Badge variant="outline" className="rounded-full border-dashed px-2.5 py-0.5 text-[11px] font-medium">
                {item.queue}
              </Badge>
            ) : null}
            <Badge className={cn("rounded-full px-2.5 py-0.5 text-[11px] font-semibold", priorityStyles[item.priority]?.badgeClass ?? "")}>
              {priorityStyles[item.priority]?.label ?? item.priority}
            </Badge>
          </div>
          <div className="mt-1 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
            {item.company ? <span>{item.company}</span> : null}
            {item.location ? <span className="flex items-center gap-1"><Clock className="size-3" /> {item.location}</span> : null}
            {item.startAt ? (
              <span className="flex items-center gap-1">
                <CalendarClock className="size-3" />
                {formatDateRange(item.startAt, item.endAt)}
              </span>
            ) : (
              <span className="flex items-center gap-1 text-foreground">
                <AlertTriangle className="size-3" />
                Não agendado
              </span>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide">
          <status.icon className={cn("size-4", status.className)} />
          <span className={status.className}>{status.label}</span>
        </div>
      </div>
    </Link>
  )
}

function formatDateRange(start?: Date | null, end?: Date | null) {
  if (!start) return "Sem data"
  if (!end) return new Intl.DateTimeFormat("pt-BR", { dateStyle: "medium", timeStyle: "short" }).format(start)
  const sameDay = start.toDateString() === end.toDateString()
  if (sameDay) {
    return `${new Intl.DateTimeFormat("pt-BR", { dateStyle: "short" }).format(start)} · ${new Intl.DateTimeFormat("pt-BR", { timeStyle: "short" }).format(start)} - ${new Intl.DateTimeFormat("pt-BR", { timeStyle: "short" }).format(end)}`
  }
  return `${new Intl.DateTimeFormat("pt-BR", { dateStyle: "short", timeStyle: "short" }).format(start)} → ${new Intl.DateTimeFormat("pt-BR", { dateStyle: "short", timeStyle: "short" }).format(end)}`
}

function buildSectionLink(section: keyof AgendaDataset["sections"]) {
  const params = new URLSearchParams()
  params.set("focus", "visits")
  params.set("view", section === "completed" ? "completed" : "active")
  if (section === "completed") {
    params.set("status", "RESOLVED")
  }
  return `/tickets?${params.toString()}`
}
