import type { ReactNode } from "react";
import type { LucideIcon } from "lucide-react";
import {
  AlertTriangle,
  BarChart3,
  CircleGauge,
  CircleDashed,
  Home,
  Flame,
  MapPinned,
  ShieldAlert,
  Sparkles,
  Baby,
  UserRound,
  TrendingUp,
  Users,
  Users2,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { semanticBadgeClass } from "@/lib/badge-variants";
import type { AlertTone } from "@/lib/semantic-tokens";
import {
  badgeClassForAlert,
  surfaceClassForAlertTone,
  vulnerabilityLevelTone,
} from "@/lib/state-variants";
import { DASHBOARD_RSH_CHART_COLORS } from "@/lib/chart-theme";
import { cn } from "@/lib/utils";
import { labelTramoRsh } from "@/lib/tramo-rsh";
import type { DashboardAnalytics } from "@/server/queries/dashboard";

export function DashboardIntro({
  vulnerability,
  stats,
}: {
  vulnerability: DashboardAnalytics["vulnerability"];
  stats: DashboardAnalytics["stats"];
}) {
  return (
    <Card className="border-border bg-gradient-to-br from-muted to-card shadow-sm">
      <CardContent className="grid gap-6 p-6 xl:grid-cols-[1.45fr_1fr]">
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <Badge className="rounded-full bg-primary px-3 py-1 text-[11px] font-semibold tracking-[0.18em] text-primary-foreground">
              PANEL TERRITORIAL
            </Badge>
            <Badge variant="outline" className="rounded-full border-border bg-card text-muted-foreground">
              Empadronamiento VFB
            </Badge>
          </div>
          <div className="space-y-2">
            <h2 className="text-3xl font-semibold tracking-tight text-foreground">Dashboard territorial</h2>
            <p className="max-w-3xl text-sm leading-6 text-muted-foreground">
              Lectura institucional del sector con foco en vulnerabilidad social, completitud documental,
              composición etaria y prioridades territoriales para apoyo a decisión.
            </p>
          </div>
          <div className="grid gap-3 sm:grid-cols-3">
            <MiniStat icon={MapPinned} label="Fichas activas" value={stats.totalFichas} />
            <MiniStat icon={Users2} label="Ocupantes responsables" value={stats.totalOcupantesResponsables} />
            <MiniStat icon={Sparkles} label="Vulnerabilidad promedio" value={`${Math.round(vulnerability.averageVulnerability)}%`} />
          </div>
        </div>

        <div className="grid gap-4 rounded-2xl border border-border bg-card p-4 shadow-sm">
          <div className="flex items-center justify-between gap-2">
            <div>
              <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">Vulnerabilidad promedio</p>
              <p className="text-2xl font-semibold text-foreground">{Math.round(vulnerability.averageVulnerability)}%</p>
            </div>
            <Badge className={semanticBadgeClass(vulnerabilityLevelTone(vulnerability.vulnerabilityLevel), { shape: "pill" })}>
              {vulnerability.vulnerabilityLevel}
            </Badge>
          </div>
          <div className="space-y-2">
            <div className="h-3 rounded-full bg-muted">
              <div
                className="h-3 rounded-full"
                style={{
                  width: `${Math.min(100, Math.max(0, vulnerability.vulnerabilityPercent))}%`,
                  background: "linear-gradient(to right, var(--warning), var(--destructive))",
                }}
              />
            </div>
            <p className="text-sm text-muted-foreground">
              Escala de prioridad territorial basada en tramo RSH del ocupante responsable.
            </p>
          </div>
          <div className="grid gap-3 sm:grid-cols-3">
            <BadgePill label="60+" value={`${formatNumber(vulnerability.adultsOver60)} personas`} />
            <BadgePill label="75+" value={`${formatNumber(vulnerability.adultsOver75)} personas`} />
            <BadgePill label="Menores" value={`${formatNumber(vulnerability.minors)} personas`} />
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

export function KPIGrid({ analysis }: { analysis: DashboardAnalytics }) {
  const { stats, vulnerability } = analysis;
  const items = [
    { label: "Total de fichas", value: stats.totalFichas, icon: MapPinned, tone: "info" as const },
    { label: "Total de ocupantes", value: stats.totalOcupantes, icon: Users, tone: "info" as const },
    { label: "Lotes con resolución", value: stats.lotesConResolucion, icon: Sparkles, tone: "success" as const },
    { label: "Lotes sin resolución", value: stats.lotesSinResolucion, icon: AlertTriangle, tone: "warning" as const },
    { label: "Fichas completas", value: stats.fichasCompletas, icon: CircleGauge, tone: "success" as const },
    { label: "Fichas incompletas", value: stats.fichasIncompletas, icon: CircleDashed, tone: "warning" as const },
    { label: "Documentos pendientes", value: stats.documentosPendientes, icon: ShieldAlert, tone: "warning" as const },
    { label: "Documentos validados", value: stats.documentosValidados, icon: TrendingUp, tone: "success" as const },
    { label: "Documentos rechazados", value: stats.documentosRechazados, icon: Flame, tone: "danger" as const },
    { label: "Lotes con dueño", value: stats.lotesConDueno, icon: Users2, tone: "info" as const },
    { label: "Sin ocupante", value: stats.lotesSinOcupante, icon: AlertTriangle, tone: "danger" as const },
    { label: "Mayores de 60 años", value: vulnerability.adultsOver60, icon: UserRound, tone: "info" as const },
    { label: "Mayores de 75 años", value: vulnerability.adultsOver75, icon: UserRound, tone: "warning" as const },
    { label: "Lotes con adultos mayores", value: vulnerability.lotsWithOlderAdults, icon: Home, tone: "warning" as const },
    { label: "Menores de edad", value: vulnerability.minors, icon: Baby, tone: "info" as const },
    { label: "Menores de 5 años", value: vulnerability.minorsUnder5, icon: Baby, tone: "danger" as const },
    { label: "Promedio personas por lote", value: Math.round(vulnerability.avgPeoplePerLot * 10) / 10, icon: Users, tone: "info" as const },
  ];

  return (
    <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
      {items.map((item) => (
        <MetricCard key={item.label} {...item} />
      ))}
    </section>
  );
}

export function TerritorialInsights({
  analysis,
}: {
  analysis: DashboardAnalytics;
}) {
  return (
    <section className="grid gap-6 xl:grid-cols-[1.1fr_1fr]">
      <Card className="border-border shadow-sm">
        <CardHeader className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-lg">
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
            Distribución de tramo RSH
          </CardTitle>
        </CardHeader>
        <CardContent>
          <DonutMetricCard data={analysis.tramoDistribution} />
        </CardContent>
      </Card>

      <Card className="border-border shadow-sm">
        <CardHeader className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-lg">
            <CircleGauge className="h-4 w-4 text-muted-foreground" />
            Estado de fichas
          </CardTitle>
        </CardHeader>
        <CardContent>
          <BarMetricCard
            items={[
              { label: "Completas", value: analysis.fichaStatusCounts.COMPLETA, tone: "success" },
              { label: "Incompletas", value: analysis.fichaStatusCounts.INCOMPLETA, tone: "warning" },
              { label: "En revisión", value: analysis.fichaStatusCounts.EN_REVISION, tone: "warning" },
            ]}
          />
        </CardContent>
      </Card>

      <Card className="border-border shadow-sm">
        <CardHeader className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-lg">
            <Users2 className="h-4 w-4 text-muted-foreground" />
            Estado documental
          </CardTitle>
        </CardHeader>
        <CardContent>
          <BarMetricCard
            items={[
              { label: "Pendientes", value: analysis.documentStatusCounts.PENDIENTE, tone: "warning" },
              { label: "Validados", value: analysis.documentStatusCounts.VALIDADO, tone: "success" },
              { label: "Rechazados", value: analysis.documentStatusCounts.RECHAZADO, tone: "danger" },
            ]}
          />
        </CardContent>
      </Card>

      <Card className="border-border shadow-sm">
        <CardHeader className="space-y-1">
          <CardTitle className="flex items-center gap-2 text-lg">
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
            Ranking de manzanas con mayor vulnerabilidad
          </CardTitle>
        </CardHeader>
        <CardContent>
          <RankingList rows={analysis.territorialRows} />
        </CardContent>
      </Card>
    </section>
  );
}

export function TerritorySummaryTable({
  rows,
}: {
  rows: DashboardAnalytics["territorialRows"];
}) {
  return (
    <Card className="border-border shadow-sm">
      <CardHeader className="space-y-1">
        <CardTitle className="flex items-center gap-2 text-lg">
          <MapPinned className="h-4 w-4 text-muted-foreground" />
          Análisis territorial por manzana
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[760px] text-sm">
            <thead className="border-b bg-muted text-muted-foreground">
              <tr>
                <Th>Manzana</Th>
                <Th className="text-right">Total fichas</Th>
                <Th className="text-right">Vulnerabilidad</Th>
                <Th className="text-right">Completitud</Th>
                <Th className="text-right">Ocupantes</Th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => (
                <tr key={row.manzana} className="border-b last:border-0">
                  <Td className="font-medium">{row.manzana}</Td>
                  <Td className="text-right">{row.totalFichas}</Td>
                  <Td className="text-right">
                    <Badge
                      className={semanticBadgeClass(vulnerabilityLevelTone(scoreToLevel(row.avgVulnerability)), {
                        shape: "pill",
                      })}
                    >
                      {Math.round(row.avgVulnerability)}%
                    </Badge>
                  </Td>
                  <Td className="text-right">
                    <div className="ml-auto flex w-full max-w-[180px] flex-col items-end gap-1">
                      <span className="text-xs text-muted-foreground">{Math.round(row.completionRate)}%</span>
                      <div className="h-2 w-full rounded-full bg-muted">
                        <div
                          className="h-2 rounded-full bg-success"
                          style={{ width: `${Math.min(100, row.completionRate)}%` }}
                        />
                      </div>
                    </div>
                  </Td>
                  <Td className="text-right">{row.occupants}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </CardContent>
    </Card>
  );
}

export function AlertsPanel({
  items,
}: {
  items: DashboardAnalytics["alerts"];
}) {
  return (
    <Card className="border-border shadow-sm">
      <CardHeader className="space-y-1">
        <CardTitle className="flex items-center gap-2 text-lg">
          <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          Alertas prioritarias
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-3">
        {items.map((item) => (
          <div key={item.title} className={surfaceClassForAlertTone(item.tone)}>
            <div className="flex items-center justify-between gap-3">
              <div>
                <p className="font-medium text-foreground">{item.title}</p>
                <p className="text-sm text-muted-foreground">{item.detail}</p>
              </div>
              <Badge className={badgeClassForAlert(item.tone, { pill: true, ring: true })}>{item.value}</Badge>
            </div>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

function MetricCard({
  label,
  value,
  icon: Icon,
  tone,
}: {
  label: string;
  value: number;
  icon: LucideIcon;
  tone: AlertTone;
}) {
  return (
    <Card className="border-border shadow-sm transition-shadow hover:shadow-md">
      <CardContent className="flex items-center gap-4 p-5">
        <div className={cn("flex h-12 w-12 items-center justify-center rounded-2xl", iconSurfaceClass(tone))}>
          <Icon className="h-5 w-5" />
        </div>
        <div className="min-w-0">
          <p className="text-sm font-medium text-muted-foreground">{label}</p>
          <p className="truncate text-2xl font-semibold text-foreground">{formatNumber(value)}</p>
        </div>
      </CardContent>
    </Card>
  );
}

function MiniStat({
  icon: Icon,
  label,
  value,
}: {
  icon: LucideIcon;
  label: string;
  value: number | string;
}) {
  return (
    <div className="rounded-2xl border border-border bg-card px-4 py-3 shadow-sm">
      <div className="flex items-center gap-3">
        <Icon className="h-4 w-4 text-muted-foreground" />
        <div>
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{label}</p>
          <p className="text-lg font-semibold text-foreground">{value}</p>
        </div>
      </div>
    </div>
  );
}

function BadgePill({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-2xl border border-border bg-muted px-4 py-3">
      <p className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">{label}</p>
      <p className="mt-1 text-lg font-semibold text-foreground">{value}</p>
    </div>
  );
}

function DonutMetricCard({
  data,
}: {
  data: Array<{ value: string; label: string; count: number; percent: number; score: number }>;
}) {
  const total = data.reduce((sum, item) => sum + item.count, 0);
  const segments = data.filter((item) => item.count > 0);
  const gradient = buildDonutGradient(segments);

  return (
    <div className="grid gap-5 lg:grid-cols-[220px_1fr]">
      <div className="flex items-center justify-center">
        <div className="relative h-52 w-52">
          <div className="absolute inset-0 rounded-full" style={{ background: gradient }} />
          <div className="absolute inset-5 rounded-full border border-border bg-card shadow-inner" />
          <div className="absolute inset-0 flex flex-col items-center justify-center text-center">
            <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">Promedio</p>
            <p className="text-4xl font-semibold text-foreground">{Math.round(weightedAverage(data, total))}%</p>
            <p className="mt-1 text-xs text-muted-foreground">RSH territorial</p>
          </div>
        </div>
      </div>
      <div className="space-y-3">
        {data.map((item, index) => (
          <div key={item.value} className="space-y-1.5">
            <div className="flex items-center justify-between gap-3 text-sm">
              <span className="font-medium text-foreground">{labelTramoRsh(item.value)}</span>
              <span className="text-muted-foreground">
                {item.count} · {Math.round(item.percent)}%
              </span>
            </div>
            <div className="h-3 rounded-full bg-muted">
              <div
                className="h-3 rounded-full"
                style={{
                  width: `${item.percent}%`,
                  backgroundColor: DASHBOARD_RSH_CHART_COLORS[index % DASHBOARD_RSH_CHART_COLORS.length],
                }}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BarMetricCard({
  items,
}: {
  items: Array<{ label: string; value: number; tone: "success" | "warning" | "danger" }>;
}) {
  const maxValue = Math.max(...items.map((item) => item.value), 1);
  return (
    <div className="space-y-4">
      {items.map((item) => {
        const percent = (item.value / maxValue) * 100;
        return (
          <div key={item.label} className="space-y-1.5">
            <div className="flex items-center justify-between gap-3 text-sm">
              <span className="font-medium text-foreground">{item.label}</span>
              <span className="text-muted-foreground">{item.value}</span>
            </div>
            <div className="h-3 rounded-full bg-muted">
              <div className={cn("h-3 rounded-full", barToneClass(item.tone))} style={{ width: `${percent}%` }} />
            </div>
          </div>
        );
      })}
    </div>
  );
}

function RankingList({
  rows,
}: {
  rows: DashboardAnalytics["territorialRows"];
}) {
  const sorted = [...rows].sort((a, b) => b.avgVulnerability - a.avgVulnerability).slice(0, 5);
  if (sorted.length === 0) {
    return <p className="text-sm text-muted-foreground">Sin datos suficientes para ranking territorial.</p>;
  }
  return (
    <div className="space-y-3">
      {sorted.map((row, index) => (
        <div key={row.manzana} className="rounded-2xl border border-border p-4">
          <div className="flex items-center justify-between gap-3">
            <div>
              <p className="text-sm font-semibold text-foreground">
                #{index + 1} Manzana {row.manzana}
              </p>
              <p className="text-xs text-muted-foreground">{row.totalFichas} fichas · {row.occupants} ocupantes estimados</p>
            </div>
            <Badge className={semanticBadgeClass(vulnerabilityLevelTone(scoreToLevel(row.avgVulnerability)), { shape: "pill" })}>
              {Math.round(row.avgVulnerability)}%
            </Badge>
          </div>
        </div>
      ))}
    </div>
  );
}

function Th({ children, className }: { children: ReactNode; className?: string }) {
  return <th className={cn("px-4 py-3 text-left font-medium", className)}>{children}</th>;
}

function Td({ children, className }: { children: ReactNode; className?: string }) {
  return <td className={cn("px-4 py-3 align-top text-foreground", className)}>{children}</td>;
}

function iconSurfaceClass(tone: AlertTone) {
  const classes: Record<AlertTone, string> = {
    success: "bg-success-subtle text-success",
    warning: "bg-warning-subtle text-warning",
    danger: "bg-danger-subtle text-destructive",
    info: "bg-info-subtle text-info",
  };
  return classes[tone];
}

function barToneClass(tone: "success" | "warning" | "danger") {
  if (tone === "success") return "bg-success";
  if (tone === "warning") return "bg-warning";
  return "bg-destructive";
}

function scoreToLevel(score: number) {
  if (score >= 70) return "Alta vulnerabilidad";
  if (score >= 40) return "Media";
  return "Baja";
}

function weightedAverage(
  items: Array<{ score: number; count: number }>,
  total: number,
) {
  if (total === 0) return 0;
  const weighted = items.reduce((sum, item) => sum + item.score * item.count, 0);
  return weighted / total;
}

function formatNumber(value: number) {
  return new Intl.NumberFormat("es-CL").format(value);
}

function buildDonutGradient(items: Array<{ count: number }>) {
  const total = items.reduce((sum, item) => sum + item.count, 0);
  if (total === 0) return "conic-gradient(var(--chart-muted) 0 100%)";

  let start = 0;
  const stops: string[] = [];
  items.forEach((item, index) => {
    if (item.count <= 0) return;
    const percent = (item.count / total) * 100;
    const end = start + percent;
    stops.push(`${DASHBOARD_RSH_CHART_COLORS[index % DASHBOARD_RSH_CHART_COLORS.length]} ${start}% ${end}%`);
    start = end;
  });
  return `conic-gradient(${stops.join(", ")})`;
}
