"use client";

import { useMemo, useState, useTransition } from "react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ResponsiveContainer,
  Scatter,
  ScatterChart,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

import { useToast } from "@/components/admin/common/ToastProvider";
import { SavedFiltersBar } from "@/components/admin/common/SavedFiltersBar";

import type {
  NotFoundRow,
  SeoOverview,
  SeoPeriod,
  StrikingDistanceQuery,
  TopQuery,
  GscTrendPoint,
  GscCoverageOverview,
  SeoPageOpportunity,
} from "@/lib/seo/intelligence";

type Props = {
  period: SeoPeriod;
  overview: SeoOverview;
  topQueries: TopQuery[];
  strikingDistance: StrikingDistanceQuery[];
  notFound: NotFoundRow[];
  trend: GscTrendPoint[];
  opportunities: SeoPageOpportunity[];
  coverage: GscCoverageOverview;
};

const PERIOD_LABELS: Record<SeoPeriod, string> = {
  "7d": "7 dana",
  "30d": "30 dana",
  "90d": "90 dana",
};

export function SeoIntelligenceDashboard({
  period,
  overview,
  topQueries,
  strikingDistance,
  notFound,
  trend,
  opportunities,
  coverage,
}: Props) {
  const [activePeriod, setActivePeriod] = useState<SeoPeriod>(period);
  const [search, setSearch] = useState("");
  const toast = useToast();
  const [pending, startTransition] = useTransition();

  const filteredQueries = useMemo(() => {
    if (!search.trim()) return topQueries;
    const q = search.toLowerCase();
    return topQueries.filter((r) => r.query.toLowerCase().includes(q));
  }, [topQueries, search]);

  function changePeriod(p: SeoPeriod) {
    setActivePeriod(p);
    const url = new URL(window.location.href);
    url.searchParams.set("period", p);
    window.location.assign(url.toString());
  }

  function setRedirect(id: string) {
    const target = window.prompt("Redirect na (npr. /kompanije ili /):");
    if (!target) return;
    startTransition(async () => {
      const res = await fetch("/api/admin/seo/not-found-resolve", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, redirectTo: target }),
      });
      if (res.ok) {
        toast.success("Redirect postavljen.");
        window.location.reload();
      } else {
        toast.error("Greška pri postavljanju redirect-a.");
      }
    });
  }

  function markResolved(id: string) {
    startTransition(async () => {
      const res = await fetch("/api/admin/seo/not-found-resolve", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, redirectTo: null }),
      });
      if (res.ok) {
        toast.success("Označeno kao rešeno.");
        window.location.reload();
      } else {
        toast.error("Greška.");
      }
    });
  }

  const topChartData = topQueries.slice(0, 10).map((q) => ({
    query: q.query.length > 24 ? q.query.slice(0, 24) + "…" : q.query,
    impressions: q.impressions,
  }));
  const scatterData = strikingDistance.map((q) => ({
    impressions: q.impressions,
    position: q.position,
    query: q.query,
  }));

  return (
    <div className="space-y-6">
      <SavedFiltersBar />

      {/* Period switcher */}
      <div className="flex flex-wrap items-center gap-2">
        <span className="text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
          Period
        </span>
        {(["7d", "30d", "90d"] as const).map((p) => (
          <button
            key={p}
            type="button"
            onClick={() => changePeriod(p)}
            className={`rounded-full border px-3 py-1 text-xs font-semibold transition ${
              activePeriod === p
                ? "border-primary bg-primary text-white"
                : "border-border bg-white text-foreground hover:border-primary/40"
            }`}
          >
            {PERIOD_LABELS[p]}
          </button>
        ))}
      </div>

      {/* Stats strip */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
        <Stat label="Upiti" value={overview.totalQueries.toLocaleString("sr-Latn")} />
        <Stat label="Prikazi" value={overview.totalImpressions.toLocaleString("sr-Latn")} />
        <Stat label="Klikovi" value={overview.totalClicks.toLocaleString("sr-Latn")} />
        <Stat label="Pros. pozicija" value={overview.avgPosition.toFixed(1)} />
        <Stat label="Nerešene 404" value={String(overview.unresolvedNotFound)} accent="warn" />
      </div>

      <Card title="Google indeksacija — URL Inspection uzorak">
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
          <MiniMetric label="Provereno" value={coverage.inspected} />
          <MiniMetric label="Indeksirano" value={coverage.indexed} />
          <MiniMetric label="Discovered, neindeksirano" value={coverage.discoveredNotIndexed} warn />
          <MiniMetric label="Crawled, neindeksirano" value={coverage.crawledNotIndexed} warn />
          <MiniMetric label="Canonical neslaganje" value={coverage.canonicalMismatch} warn />
          <MiniMetric label="Blokirano / fetch greška" value={coverage.blockedOrFailed} warn />
        </div>
        <p className="mt-3 text-xs text-muted-foreground">
          Dnevni uzorak prioritetnih URL-ova iz Search Console-a.
          {coverage.lastInspectedAt
            ? ` Poslednja provera: ${new Intl.DateTimeFormat("sr-Latn-RS", { dateStyle: "medium", timeStyle: "short" }).format(coverage.lastInspectedAt)}.`
            : " URL Inspection podaci još nisu sinhronizovani."}
        </p>
      </Card>

      <Card title="Automatski prioriteti za sledeću optimizaciju">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-2 py-2">Problem</th>
                <th className="px-2 py-2">Stranica</th>
                <th className="px-2 py-2">Prikazi</th>
                <th className="px-2 py-2">CTR</th>
                <th className="px-2 py-2">Pozicija</th>
                <th className="px-2 py-2">Prioritet</th>
              </tr>
            </thead>
            <tbody>
              {opportunities.map((row) => (
                <tr key={`${row.kind}:${row.page}`} className="border-t border-border/40">
                  <td className="px-2 py-2 font-semibold">
                    {row.kind === "DECLINING"
                      ? "Pad klikova"
                      : row.kind === "LOW_CTR"
                        ? "Nizak CTR"
                        : "Pozicija 11–20"}
                  </td>
                  <td className="max-w-[28rem] truncate px-2 py-2">
                    <a href={row.page} target="_blank" rel="noreferrer" className="text-primary hover:underline">
                      {row.page}
                    </a>
                  </td>
                  <td className="px-2 py-2">{row.impressions}</td>
                  <td className="px-2 py-2">{(row.ctr * 100).toFixed(2)}%</td>
                  <td className="px-2 py-2">{row.position.toFixed(1)}</td>
                  <td className="px-2 py-2 font-semibold">{row.priority}</td>
                </tr>
              ))}
              {opportunities.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-2 py-6 text-center text-muted-foreground">
                    Nema dovoljno uzastopnih GSC perioda za prioritizaciju.
                  </td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Trend chart */}
      <Card title="Trend prikazi i klikovi">
        <div className="h-72 w-full">
          {trend.length === 0 ? (
            <EmptyHint text="Nema podataka — uvezi GSC izveštaj." />
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={trend}>
                <CartesianGrid strokeDasharray="3 3" stroke="#eee" />
                <XAxis dataKey="date" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="impressions" stroke="#0c1828" name="Prikazi" />
                <Line type="monotone" dataKey="clicks" stroke="#c2410c" name="Klikovi" />
              </LineChart>
            </ResponsiveContainer>
          )}
        </div>
      </Card>

      {/* Top queries */}
      <Card title="Top 50 upita iz Google-a">
        <div className="mb-3 flex items-center gap-3">
          <input
            type="search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Filtriraj upite…"
            className="w-full rounded-full border border-border bg-white px-4 py-2 text-sm"
          />
        </div>
        <div className="h-56 w-full">
          {topChartData.length === 0 ? (
            <EmptyHint text="Nema podataka." />
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={topChartData} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" stroke="#eee" />
                <XAxis type="number" tick={{ fontSize: 11 }} />
                <YAxis dataKey="query" type="category" width={140} tick={{ fontSize: 11 }} />
                <Tooltip />
                <Bar dataKey="impressions" fill="#c2410c" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
        <div className="mt-4 overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-2 py-2">Upit</th>
                <th className="px-2 py-2">Prikazi</th>
                <th className="px-2 py-2">Klikovi</th>
                <th className="px-2 py-2">CTR</th>
                <th className="px-2 py-2">Pozicija</th>
              </tr>
            </thead>
            <tbody>
              {filteredQueries.slice(0, 50).map((row) => (
                <tr key={row.id} className="border-t border-border/40">
                  <td className="px-2 py-2 font-medium">{row.query}</td>
                  <td className="px-2 py-2">{row.impressions}</td>
                  <td className="px-2 py-2">{row.clicks}</td>
                  <td className="px-2 py-2">{(row.ctr * 100).toFixed(2)}%</td>
                  <td className="px-2 py-2">{row.position.toFixed(1)}</td>
                </tr>
              ))}
              {filteredQueries.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-2 py-6 text-center text-muted-foreground">
                    Nema upita za prikaz.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Striking distance */}
      <Card title="Prilike na dohvat ruke (pozicija 11-20)">
        <p className="mb-3 text-sm text-muted-foreground">
          Upiti na drugoj strani Google-a — uz malu intervenciju (interni link, dopuna sadržaja)
          mogu da se popnu u top 10 i donesu organski saobraćaj.
        </p>
        <div className="h-64 w-full">
          {scatterData.length === 0 ? (
            <EmptyHint text="Nema prilika u trenutnom periodu." />
          ) : (
            <ResponsiveContainer width="100%" height="100%">
              <ScatterChart>
                <CartesianGrid strokeDasharray="3 3" stroke="#eee" />
                <XAxis dataKey="impressions" name="Prikazi" tick={{ fontSize: 11 }} />
                <YAxis
                  dataKey="position"
                  name="Pozicija"
                  reversed
                  domain={[10, 21]}
                  tick={{ fontSize: 11 }}
                />
                <Tooltip cursor={{ strokeDasharray: "3 3" }} />
                <Scatter data={scatterData} fill="#c2410c" />
              </ScatterChart>
            </ResponsiveContainer>
          )}
        </div>
        <div className="mt-4 overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-2 py-2">Upit</th>
                <th className="px-2 py-2">Trenutna pozicija</th>
                <th className="px-2 py-2">Mesečni prikazi</th>
                <th className="px-2 py-2">Stranica</th>
              </tr>
            </thead>
            <tbody>
              {strikingDistance.map((row) => (
                <tr key={row.id} className="border-t border-border/40">
                  <td className="px-2 py-2 font-medium">{row.query}</td>
                  <td className="px-2 py-2">{row.position.toFixed(1)}</td>
                  <td className="px-2 py-2">{row.impressions}</td>
                  <td className="px-2 py-2 text-xs text-muted-foreground">
                    {row.page ? (
                      <a className="text-primary hover:underline" href={row.page} target="_blank" rel="noreferrer">
                        {row.page.slice(0, 60)}
                      </a>
                    ) : (
                      "—"
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 404 monitor */}
      <Card title="404 monitor">
        <p className="mb-3 text-sm text-muted-foreground">
          Stranice koje su posetioci tražili a portal ih nije pronašao. Postavi 301 redirect
          da bi sačuvao SEO težinu i konverziju.
        </p>
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-2 py-2">Putanja</th>
                <th className="px-2 py-2">Broj</th>
                <th className="px-2 py-2">Prvi put</th>
                <th className="px-2 py-2">Poslednji put</th>
                <th className="px-2 py-2">Akcija</th>
              </tr>
            </thead>
            <tbody>
              {notFound.map((row) => (
                <tr key={row.id} className="border-t border-border/40">
                  <td className="px-2 py-2 font-mono text-xs">{row.path}</td>
                  <td className="px-2 py-2">{row.count}</td>
                  <td className="px-2 py-2 text-xs text-muted-foreground">
                    {row.firstSeenAt.toLocaleDateString("sr-Latn")}
                  </td>
                  <td className="px-2 py-2 text-xs text-muted-foreground">
                    {row.lastSeenAt.toLocaleDateString("sr-Latn")}
                  </td>
                  <td className="px-2 py-2">
                    <div className="flex flex-wrap gap-2">
                      <button
                        type="button"
                        disabled={pending}
                        onClick={() => setRedirect(row.id)}
                        className="rounded-full border border-primary/40 px-3 py-1 text-xs font-semibold text-primary transition hover:bg-primary hover:text-white"
                      >
                        Postavi redirect
                      </button>
                      <button
                        type="button"
                        disabled={pending}
                        onClick={() => markResolved(row.id)}
                        className="rounded-full border border-border px-3 py-1 text-xs font-semibold text-muted-foreground transition hover:border-foreground hover:text-foreground"
                      >
                        Označi rešeno
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {notFound.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-2 py-6 text-center text-muted-foreground">
                    Nema nerešenih 404 grešaka. 🎉
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function Stat({
  label,
  value,
  accent,
}: {
  label: string;
  value: string;
  accent?: "warn";
}) {
  return (
    <div
      className={`surface rounded-2xl px-4 py-4 ${
        accent === "warn" ? "ring-1 ring-amber-300" : ""
      }`}
    >
      <p className="text-xs uppercase tracking-wider text-muted-foreground">{label}</p>
      <p className="mt-1 font-display text-2xl font-semibold">{value}</p>
    </div>
  );
}

function MiniMetric({
  label,
  value,
  warn = false,
}: {
  label: string;
  value: number;
  warn?: boolean;
}) {
  return (
    <div className={`rounded-xl border p-3 ${warn && value > 0 ? "border-amber-300 bg-amber-50" : "border-border bg-white"}`}>
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="mt-1 text-xl font-semibold text-foreground">{value.toLocaleString("sr-Latn")}</p>
    </div>
  );
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <details open className="surface rounded-2xl px-5 py-4">
      <summary className="cursor-pointer text-base font-semibold">{title}</summary>
      <div className="mt-4">{children}</div>
    </details>
  );
}

function EmptyHint({ text }: { text: string }) {
  return (
    <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
      {text}
    </div>
  );
}
