"use client";

import { useEffect, useMemo, useState } from "react";
import { useQuery } from "convex/react";
import {
  Activity,
  BarChart3,
  CheckCircle2,
  Filter,
  MailCheck,
  MousePointerClick,
  SearchCheck,
  ShieldCheck,
  TrendingUp,
  type LucideIcon,
} from "lucide-react";

import { api } from "@/convex/_generated/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";

const metricLabels: Record<string, string> = {
  foundLeads: "Gefundene Leads",
  leadsWithContact: "Mit Kontakt",
  missingContact: "Kontakt fehlt",
  auditsCreated: "Audits erstellt",
  approvalsOpen: "Freigaben offen",
  emailsSent: "E-Mails gesendet",
  followUpsPlanned: "Follow-ups geplant",
  followUpsSent: "Follow-ups gesendet",
  responses: "Antworten",
  conversations: "Gespräche",
  offers: "Angebote",
  wins: "Gewonnen",
  losses: "Verloren",
  skippedDuplicates: "Duplikate übersprungen",
  skippedBlacklisted: "Sperrliste übersprungen",
  rybbitAuditOpens: "Audit-Öffnungen",
  rybbitCtaClicks: "CTA-Klicks",
};

type MetricKey = keyof typeof metricLabels;

const heroMetrics: Array<{
  key: MetricKey;
  note: string;
  icon: LucideIcon;
  surface: string;
}> = [
  {
    key: "approvalsOpen",
    note: "Wartet auf manuelle Prüfung",
    icon: ShieldCheck,
    surface: "review-surface",
  },
  {
    key: "auditsCreated",
    note: "Belege im System",
    icon: SearchCheck,
    surface: "evidence-surface",
  },
  {
    key: "foundLeads",
    note: "Aus Kampagnenläufen",
    icon: BarChart3,
    surface: "safe-surface",
  },
  {
    key: "leadsWithContact",
    note: "E-Mail oder Telefon vorhanden",
    icon: CheckCircle2,
    surface: "bg-muted text-muted-foreground",
  },
];

const metricGroups: Array<{
  title: string;
  description: string;
  icon: LucideIcon;
  keys: MetricKey[];
}> = [
  {
    title: "Kontaktlage",
    description: "Lead-Qualität und fehlende Kontaktwege.",
    icon: SearchCheck,
    keys: ["missingContact", "skippedBlacklisted", "skippedDuplicates"],
  },
  {
    title: "Outreach",
    description: "Freigaben, Versand und geplante nächste Schritte.",
    icon: MailCheck,
    keys: ["emailsSent", "followUpsPlanned", "followUpsSent"],
  },
  {
    title: "Pipeline",
    description: "Antworten, Gespräche, Angebote und Abschlüsse.",
    icon: TrendingUp,
    keys: ["responses", "conversations", "offers", "wins", "losses"],
  },
];

export function AnalyticsDashboard() {
  const dashboard = useQuery(api.campaignMetrics.getDashboard, { limit: 20 });
  const [rybbitData, setRybbitData] = useState<{
    auditOpens: number;
    ctaClicks: number;
    outboundClicks: number;
    byPath?: Record<string, {
      auditOpens: number;
      ctaClicks: number;
      outboundClicks: number;
    }>;
  } | null>(null);
  const [rybbitError, setRybbitError] = useState<string | null>(null);
  const rybbitGroups = useMemo(() => {
    if (!dashboard || !rybbitData?.byPath) {
      return [];
    }

    const grouped = new Map<string, { label: string; auditOpens: number; ctaClicks: number }>();
    for (const segment of dashboard.auditSegments) {
      const metrics = rybbitData.byPath[segment.path];
      if (!metrics) {
        continue;
      }

      for (const [kind, label] of [
        ["Kampagne", segment.campaignName],
        ["Nische", segment.niche],
        ["Region", segment.region],
      ] as const) {
        const key = `${kind}:${label}`;
        const current = grouped.get(key) ?? {
          label: `${kind}: ${label}`,
          auditOpens: 0,
          ctaClicks: 0,
        };
        current.auditOpens += metrics.auditOpens;
        current.ctaClicks += metrics.ctaClicks;
        grouped.set(key, current);
      }
    }

    return [...grouped.values()].slice(0, 8);
  }, [dashboard, rybbitData]);

  useEffect(() => {
    let isMounted = true;

    fetch("/api/internal/rybbit/campaign")
      .then(async (response) => {
        const payload = await response.json();
        if (!isMounted) {
          return;
        }
        if (!payload.ok) {
          setRybbitError("Rybbit-Daten konnten nicht geladen werden.");
        }
        setRybbitData(payload.data ?? null);
      })
      .catch(() => {
        if (isMounted) {
          setRybbitError("Rybbit-Daten konnten nicht geladen werden.");
        }
      });

    return () => {
      isMounted = false;
    };
  }, []);

  if (dashboard === undefined) {
    return (
      <section className="space-y-4">
        <Skeleton className="h-32 rounded-lg" />
        <Skeleton className="h-80 rounded-lg" />
      </section>
    );
  }

  const metricValue = (key: MetricKey) => dashboard.metrics[key] ?? 0;

  return (
    <section className="space-y-4">
      <header className="agency-panel flex flex-col gap-3 p-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <p className="agency-kicker">Kampagnen-Reporting</p>
          <h1 className="mt-2 font-heading text-3xl font-semibold tracking-normal">
            Analytics
          </h1>
          <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">
            Funnel-Signale, Freigaben und Tracking bleiben zusammen sichtbar,
            ohne die operative Prüfung aus dem Blick zu verlieren.
          </p>
        </div>
        <div className="rounded-md border border-border/75 bg-background/65 px-3 py-2 text-sm">
          <p className="font-semibold">{dashboard.filters.campaigns.length} Kampagnen</p>
          <p className="text-xs text-muted-foreground">
            {dashboard.filters.niches.length} Nischen · {dashboard.filters.postalCodes.length} PLZ
          </p>
        </div>
      </header>

      <div className="agency-panel p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <p className="inline-flex items-center gap-2 text-sm font-semibold">
              <Filter className="size-4 text-primary" />
              Filter
            </p>
            <p className="mt-1 text-sm text-muted-foreground">
              Kampagne, Nische, PLZ, Radius, Priorität, Status und Zeitraum.
            </p>
          </div>
          <div className="flex flex-wrap gap-2 text-xs font-semibold text-muted-foreground">
            <span className="rounded-md bg-muted/65 px-2.5 py-1">
              Radius: Kampagnenradius
            </span>
            <span className="rounded-md bg-muted/65 px-2.5 py-1">
              Priorität: Hoch/Mittel/Niedrig
            </span>
            <span className="rounded-md bg-muted/65 px-2.5 py-1">
              Status: Funnel-Status
            </span>
            <span className="rounded-md bg-muted/65 px-2.5 py-1">
              Zeitraum: Erstellungsdatum
            </span>
          </div>
        </div>
      </div>

      <section className="agency-panel p-4" aria-labelledby="analytics-kpi-heading">
        <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
          <div>
            <p className="agency-kicker">Funnel Snapshot</p>
            <h2
              className="mt-1 font-heading text-xl font-semibold tracking-normal"
              id="analytics-kpi-heading"
            >
              Operative Kennzahlen
            </h2>
          </div>
          <p className="text-sm text-muted-foreground">
            Live aus Convex, Tracking bei Bedarf aus Rybbit.
          </p>
        </div>

        <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          {heroMetrics.map((metric) => {
            const Icon = metric.icon;

            return (
              <div
                className="rounded-md border border-border/75 bg-background/65 p-3"
                key={metric.key}
              >
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {metricLabels[metric.key]}
                    </p>
                    <p className="mt-2 text-3xl font-semibold">
                      {metricValue(metric.key)}
                    </p>
                  </div>
                  <span
                    className={cn(
                      "flex size-9 shrink-0 items-center justify-center rounded-md",
                      metric.surface,
                    )}
                  >
                    <Icon className="size-4" />
                  </span>
                </div>
                <p className="mt-2 text-xs text-muted-foreground">{metric.note}</p>
              </div>
            );
          })}
        </div>

        <div className="mt-3 grid gap-3 xl:grid-cols-3">
          {metricGroups.map((group) => {
            const Icon = group.icon;

            return (
              <section
                className="rounded-md border border-border/75 bg-card/45 p-3"
                key={group.title}
                aria-labelledby={`${group.title}-analytics-heading`}
              >
                <div className="flex items-start gap-3">
                  <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
                    <Icon className="size-4" />
                  </span>
                  <div>
                    <h3
                      className="text-sm font-semibold"
                      id={`${group.title}-analytics-heading`}
                    >
                      {group.title}
                    </h3>
                    <p className="mt-1 text-xs leading-5 text-muted-foreground">
                      {group.description}
                    </p>
                  </div>
                </div>
                <div className="mt-3 grid gap-2">
                  {group.keys.map((key) => (
                    <div
                      className="flex items-center justify-between gap-3 rounded-md bg-background/70 px-3 py-2 text-sm"
                      key={key}
                    >
                      <span className="text-muted-foreground">{metricLabels[key]}</span>
                      <span className="font-semibold">{metricValue(key)}</span>
                    </div>
                  ))}
                </div>
              </section>
            );
          })}
        </div>
      </section>

      <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,0.72fr)]">
        <Card className="agency-panel">
          <CardHeader>
            <CardTitle className="inline-flex items-center gap-2">
              <Activity className="size-5 text-primary" />
              Run-Details
            </CardTitle>
            <CardDescription>
              Neue Leads, übersprungene Duplikate, Sperrliste, Fehler und erzeugte Audits.
            </CardDescription>
          </CardHeader>
          <CardContent className="grid gap-2 text-sm">
            {dashboard.runs.length === 0 ? (
              <p className="rounded-md border border-dashed border-border/80 bg-background/60 p-4 text-muted-foreground">
                Noch keine Kampagnenläufe.
              </p>
            ) : (
              dashboard.runs.map((run) => (
                <div className="rounded-md border border-border/75 bg-background/65 p-3" key={run.id}>
                  <div className="flex flex-wrap justify-between gap-2">
                    <p className="font-medium">{run.status}</p>
                    <p className="text-muted-foreground">
                      Leads {run.newLeads} · Audits {run.auditsGenerated} · Fehler {run.errors}
                    </p>
                  </div>
                  {run.errorSummary ? (
                    <p className="mt-1 text-xs text-destructive">{run.errorSummary}</p>
                  ) : null}
                </div>
              ))
            )}
          </CardContent>
        </Card>

        <Card className="agency-panel">
          <CardHeader>
            <CardTitle className="inline-flex items-center gap-2">
              <MousePointerClick className="size-5 text-primary" />
              Rybbit
            </CardTitle>
            <CardDescription>
              Audit-Öffnungen und CTA-Aktivität werden bei Bedarf aus der Rybbit API geladen.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3 text-sm text-muted-foreground">
            {rybbitError ? (
              <p className="rounded-md bg-[var(--danger-soft)] p-3 text-destructive">
                {rybbitError}
              </p>
            ) : (
              <p className="rounded-md bg-muted/55 p-3">
                Rybbit-Daten konnten nicht geladen werden, wenn API-URL, Site-ID oder API-Key fehlen.
              </p>
            )}
            <div className="grid gap-2 sm:grid-cols-3 lg:grid-cols-1 2xl:grid-cols-3">
              <div className="rounded-md bg-background/70 p-3">
                <p className="text-xs">Audit-Öffnungen</p>
                <p className="mt-1 text-xl font-semibold text-foreground">
                  {rybbitData?.auditOpens ?? dashboard.metrics.rybbitAuditOpens}
                </p>
              </div>
              <div className="rounded-md bg-background/70 p-3">
                <p className="text-xs">CTA-Klicks</p>
                <p className="mt-1 text-xl font-semibold text-foreground">
                  {rybbitData?.ctaClicks ?? dashboard.metrics.rybbitCtaClicks}
                </p>
              </div>
              <div className="rounded-md bg-background/70 p-3">
                <p className="text-xs">Website-Link-Klicks</p>
                <p className="mt-1 text-xl font-semibold text-foreground">
                  {rybbitData?.outboundClicks ?? 0}
                </p>
              </div>
            </div>
            {rybbitGroups.length > 0 ? (
              <div className="space-y-1 pt-2">
                {rybbitGroups.map((group) => (
                  <p key={group.label}>
                    {group.label}: {group.auditOpens} Öffnungen · {group.ctaClicks} CTA
                  </p>
                ))}
              </div>
            ) : null}
            <p className="text-xs">
              Public-Audit Tracking läuft nur auf veröffentlichten Audit-Seiten.
            </p>
          </CardContent>
        </Card>
      </div>
    </section>
  );
}
