"use client";

import { useMemo } from "react";
import { useQuery } from "convex/react";
import { Activity, BarChart3, Filter, MousePointerClick } 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";

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",
};

export function AnalyticsDashboard() {
  const dashboard = useQuery(api.campaignMetrics.getDashboard, { limit: 20 });
  const metricEntries = useMemo(() => {
    if (!dashboard) {
      return [];
    }

    return Object.entries(dashboard.metrics).filter(([key]) => key in metricLabels);
  }, [dashboard]);

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

  return (
    <section className="space-y-4">
      <header className="border-b pb-3">
        <p className="text-sm text-muted-foreground">Kampagnen-Reporting</p>
        <h1 className="mt-2 text-3xl font-semibold tracking-normal">Analytics</h1>
      </header>

      <Card>
        <CardHeader>
          <CardTitle className="inline-flex items-center gap-2">
            <Filter className="size-5" />
            Filter
          </CardTitle>
          <CardDescription>
            Kampagne, Nische, PLZ, Radius, Priorität, Status und Zeitraum.
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-2 text-sm text-muted-foreground sm:grid-cols-2 lg:grid-cols-4">
          <p>Kampagne: {dashboard.filters.campaigns.length}</p>
          <p>Nische: {dashboard.filters.niches.length}</p>
          <p>PLZ: {dashboard.filters.postalCodes.length}</p>
          <p>Radius: Kampagnenradius</p>
          <p>Priorität: Hoch/Mittel/Niedrig</p>
          <p>Status: Funnel-Status</p>
          <p>Zeitraum: Erstellungsdatum</p>
        </CardContent>
      </Card>

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        {metricEntries.map(([key, value]) => (
          <Card key={key}>
            <CardContent className="p-4">
              <p className="text-sm text-muted-foreground">{metricLabels[key]}</p>
              <p className="mt-2 text-2xl font-semibold">{value}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,0.7fr)]">
        <Card>
          <CardHeader>
            <CardTitle className="inline-flex items-center gap-2">
              <Activity className="size-5" />
              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="text-muted-foreground">Noch keine Kampagnenläufe.</p>
            ) : (
              dashboard.runs.map((run) => (
                <div className="rounded-md border 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>
          <CardHeader>
            <CardTitle className="inline-flex items-center gap-2">
              <MousePointerClick className="size-5" />
              Rybbit
            </CardTitle>
            <CardDescription>
              Audit-Öffnungen und CTA-Aktivität werden bei Bedarf aus der Rybbit API geladen.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-2 text-sm text-muted-foreground">
            <p>Rybbit-Daten konnten nicht geladen werden, wenn API-URL, Site-ID oder API-Key fehlen.</p>
            <p>Public-Audit Tracking läuft nur auf veröffentlichten Audit-Seiten.</p>
          </CardContent>
        </Card>
      </div>
    </section>
  );
}
