import {
  ANALYTICS_ENTITY_LABELS,
  type AnalyticsEntityType,
} from "@/lib/entity-analytics";
import type { EntityAnalyticsSummary } from "@/lib/data/entity-analytics";

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

function formatShortDate(value: string) {
  const [year, month, day] = value.split("-");
  if (!year || !month || !day) {
    return value;
  }

  return `${day}.${month}.`;
}

function getBelgradeTodayIso() {
  const formatter = new Intl.DateTimeFormat("sv-SE", {
    timeZone: "Europe/Belgrade",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formatter.format(new Date());
}

function AnalyticsMiniCard({
  label,
  value,
  accent,
}: {
  label: string;
  value: number;
  accent: string;
}) {
  return (
    <div className="rounded-[1.6rem] border border-border bg-white/86 px-5 py-5 shadow-[0_18px_45px_rgba(15,23,42,0.06)]">
      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
        {label}
      </p>
      <p className={`mt-4 text-[2rem] font-semibold leading-none tracking-[-0.03em] ${accent}`}>
        {formatNumber(value)}
      </p>
    </div>
  );
}

function formatChange(changePercent: number | null, current: number, previous: number) {
  if (changePercent === null) {
    return current > 0 && previous === 0 ? "Novi rast" : "Bez osnove";
  }

  if (changePercent === 0) {
    return "0%";
  }

  const sign = changePercent > 0 ? "+" : "";
  return `${sign}${Math.round(changePercent)}%`;
}

function TrendPill({
  changePercent,
  direction,
  current,
  previous,
}: {
  changePercent: number | null;
  direction: "up" | "down" | "flat";
  current: number;
  previous: number;
}) {
  const className =
    direction === "up"
      ? "border-success/18 bg-success/10 text-success"
      : direction === "down"
        ? "border-danger/18 bg-danger/10 text-danger"
        : "border-border bg-muted/60 text-muted-foreground";

  return (
    <div className={`inline-flex rounded-full border px-3 py-1 text-xs font-semibold ${className}`}>
      {formatChange(changePercent, current, previous)}
    </div>
  );
}

function ComparisonCard({
  label,
  metric,
}: {
  label: string;
  metric: {
    current: number;
    previous: number;
    changePercent: number | null;
    direction: "up" | "down" | "flat";
  };
}) {
  return (
    <div className="rounded-[1.35rem] border border-border bg-background/75 px-4 py-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-sm font-semibold text-foreground">{label}</p>
          <p className="mt-1 text-xs uppercase tracking-[0.14em] text-muted-foreground">
            Tekući period
          </p>
        </div>
        <TrendPill
          changePercent={metric.changePercent}
          direction={metric.direction}
          current={metric.current}
          previous={metric.previous}
        />
      </div>
      <div className="mt-4 flex items-end justify-between gap-4">
        <div>
          <p className="text-[1.45rem] font-semibold tracking-[-0.03em] text-foreground">
            {formatNumber(metric.current)}
          </p>
          <p className="text-sm text-muted-foreground">
            Prethodni period: {formatNumber(metric.previous)}
          </p>
        </div>
      </div>
    </div>
  );
}

export function EntityAnalyticsPanel({
  entityType,
  title,
  summary,
  reportHref,
}: {
  entityType: AnalyticsEntityType;
  title?: string;
  summary: EntityAnalyticsSummary;
  reportHref?: string;
}) {
  const timeline = summary.timeline.slice(-14);
  const maxTimelineValue = Math.max(...timeline.map((point) => point.count), 1);
  const todayIso = getBelgradeTodayIso();
  const todayPoint = timeline.find((point) => point.date === todayIso) ?? {
    date: todayIso,
    count: 0,
  };
  const viewsTimeline = summary.viewTimeline.slice(-14);
  const maxViewTimelineValue = Math.max(...viewsTimeline.map((point) => point.count), 1);

  return (
    <section>
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <p className="eyebrow">Statistika</p>
          <h2 className="mt-3 text-[clamp(2rem,2.8vw,2.7rem)] font-semibold tracking-[-0.04em] text-foreground">
            {title || `Performanse za ${ANALYTICS_ENTITY_LABELS[entityType].toLowerCase()}`}
          </h2>
          <p className="mt-3 max-w-4xl text-sm leading-7 text-muted-foreground">
            Ovaj pregled pokazuje koliko je puta sadržaj otvoren, kliknut i koliko je puta pokrenut direktan kontakt. To je osnov za jasno pravdanje premium paketa, isticanja i dodatnih modula prema klijentima.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <div className="admin-chip !rounded-full !px-4 !py-2 !text-sm !normal-case !tracking-normal">
            Poslednjih 30 dana: {formatNumber(summary.last30DaysTotal)} interakcija
          </div>
          {reportHref ? (
            <a href={reportHref} className="ghost-button px-4 py-2 text-sm">
              Preuzmi PDF izveštaj
            </a>
          ) : null}
        </div>
      </div>

      <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <AnalyticsMiniCard label="Ukupne interakcije" value={summary.totalInteractions} accent="text-foreground" />
        <AnalyticsMiniCard label="Jedinstveni posetioci" value={summary.totalUniqueVisitors} accent="text-primary" />
        <AnalyticsMiniCard label="Pregledi" value={summary.totals.VIEW} accent="text-secondary" />
        <AnalyticsMiniCard label="Pozivi" value={summary.totals.CALL} accent="text-success" />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        <section>
          <div className="flex items-center justify-between gap-3">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                Uporedni period
              </p>
              <h3 className="mt-2 text-[1.35rem] font-semibold tracking-[-0.03em] text-foreground">
                Poslednjih 7 dana vs prethodnih 7
              </h3>
            </div>
          </div>
          <div className="mt-5 grid gap-3 md:grid-cols-2">
            <ComparisonCard label="Pregledi" metric={summary.comparisons.last7Days.views} />
            <ComparisonCard label="Pozivi" metric={summary.comparisons.last7Days.calls} />
            <ComparisonCard
              label="Jedinstveni posetioci"
              metric={summary.comparisons.last7Days.uniqueVisitors}
            />
            <ComparisonCard
              label="Ukupne interakcije"
              metric={summary.comparisons.last7Days.totalInteractions}
            />
          </div>
        </section>

        <section>
          <div className="flex items-center justify-between gap-3">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                Uporedni period
              </p>
              <h3 className="mt-2 text-[1.35rem] font-semibold tracking-[-0.03em] text-foreground">
                Poslednjih 30 dana vs prethodnih 30
              </h3>
            </div>
          </div>
          <div className="mt-5 grid gap-3 md:grid-cols-2">
            <ComparisonCard label="Pregledi" metric={summary.comparisons.last30Days.views} />
            <ComparisonCard label="Pozivi" metric={summary.comparisons.last30Days.calls} />
            <ComparisonCard
              label="Jedinstveni posetioci"
              metric={summary.comparisons.last30Days.uniqueVisitors}
            />
            <ComparisonCard
              label="Ukupne interakcije"
              metric={summary.comparisons.last30Days.totalInteractions}
            />
          </div>
        </section>
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]">
        <section>
          <div className="flex items-center justify-between gap-3">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                Trend interakcija
              </p>
              <h3 className="mt-2 text-[1.35rem] font-semibold tracking-[-0.03em] text-foreground">
                Poslednjih 14 dana
              </h3>
            </div>
            <div className="text-sm text-muted-foreground">
              Ukupno: {formatNumber(timeline.reduce((sum, point) => sum + point.count, 0))}
            </div>
          </div>

          {todayPoint ? (
            <div className="mt-6 rounded-[1.6rem] border border-border bg-white/88 px-5 py-5 shadow-[0_18px_45px_rgba(15,23,42,0.05)]">
              <div className="flex flex-wrap items-start justify-between gap-4">
                <div>
                  <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                    Današnji dan
                  </p>
                  <h4 className="mt-2 text-[1.9rem] font-semibold tracking-[-0.04em] text-foreground">
                    {formatShortDate(todayPoint.date)}
                  </h4>
                </div>
                <div className="text-right">
                  <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
                    Interakcije
                  </p>
                  <p className="mt-2 text-[2.2rem] font-semibold leading-none tracking-[-0.05em] text-secondary">
                    {formatNumber(todayPoint.count)}
                  </p>
                </div>
              </div>
              <div className="mt-5 h-4 overflow-hidden rounded-full bg-muted/80">
                <div
                  className="h-full rounded-full bg-[linear-gradient(90deg,rgba(194,65,12,0.98),rgba(22,22,22,0.82))]"
                  style={{
                    width: `${Math.max(8, Math.round((todayPoint.count / maxTimelineValue) * 100))}%`,
                  }}
                />
              </div>
            </div>
          ) : null}

          {viewsTimeline.length ? (
            <div className="mt-5 rounded-[1.6rem] border border-border bg-white/72 px-4 py-4 shadow-[0_18px_45px_rgba(15,23,42,0.04)]">
              <div className="mb-4 flex items-center justify-between gap-3">
                <p className="text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
                  14 dana pregleda
                </p>
                <p className="text-sm text-muted-foreground">
                  {viewsTimeline.length} dana pregleda
                </p>
              </div>
              <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-7">
                {viewsTimeline.map((point) => {
                  const height = Math.max(10, Math.round((point.count / maxViewTimelineValue) * 72));
                  const hasActivity = point.count > 0;

                  return (
                    <div
                      key={point.date}
                      className="rounded-[1.25rem] border border-border bg-white/88 px-4 py-4 shadow-[0_10px_28px_rgba(15,23,42,0.035)]"
                    >
                      <div className="text-center text-[0.78rem] font-semibold leading-4 text-muted-foreground">
                        {formatShortDate(point.date)}
                      </div>
                      <div className="mt-4 flex h-16 items-end justify-center">
                        <div className="flex h-full w-8 items-end rounded-full bg-muted/70 p-1.5">
                          <div
                            className={`w-full rounded-full ${
                              hasActivity
                                ? "bg-[linear-gradient(180deg,rgba(194,65,12,0.95),rgba(22,22,22,0.85))]"
                                : "bg-muted-foreground/20"
                            }`}
                            style={{ height: `${height}%`, minHeight: hasActivity ? "10px" : "6px" }}
                          />
                        </div>
                      </div>
                      <div className="mt-4 text-center text-[1rem] font-semibold leading-none text-foreground">
                        {formatNumber(point.count)}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ) : null}
        </section>

        <section>
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
            Razrada po akcijama
          </p>
          <h3 className="mt-2 text-[1.35rem] font-semibold tracking-[-0.03em] text-foreground">
            Kanal po kanal
          </h3>
          <div className="mt-4 rounded-[1.35rem] border border-border bg-background/75 px-4 py-4">
            <div className="flex items-center justify-between gap-3">
              <div>
                <p className="font-semibold text-foreground">Različiti posetioci</p>
                <p className="text-sm text-muted-foreground">
                  Procena različitih browser poseta bez ličnih podataka.
                </p>
              </div>
              <div className="text-right">
                <p className="text-[1.2rem] font-semibold tracking-[-0.03em] text-foreground">
                  {formatNumber(summary.totalUniqueVisitors)}
                </p>
                <p className="text-xs uppercase tracking-[0.14em] text-muted-foreground">
                  Ukupno • 30d {formatNumber(summary.last30DaysUniqueVisitors)}
                </p>
              </div>
            </div>
          </div>
          <div className="mt-5 space-y-3">
            {summary.actionRows.map((row) => (
              <div
                key={row.action}
                className="flex items-center justify-between gap-3 rounded-[1.35rem] border border-border bg-background/75 px-4 py-3"
              >
                <div className="min-w-0">
                  <p className="font-semibold text-foreground">{row.label}</p>
                  <p className="text-sm text-muted-foreground">
                    Poslednjih 30 dana: {formatNumber(row.recent)}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-[1.2rem] font-semibold tracking-[-0.03em] text-foreground">
                    {formatNumber(row.total)}
                  </p>
                  <p className="text-xs uppercase tracking-[0.14em] text-muted-foreground">
                    Ukupno
                  </p>
                </div>
              </div>
            ))}
          </div>

          {!summary.hasData ? (
            <div className="mt-5 rounded-[1.35rem] border border-dashed border-border bg-background/55 px-4 py-4 text-sm leading-6 text-muted-foreground">
              Još nema zabeleženih interakcija. Čim profil ili oglas počnu da dobijaju preglede, klikove i pozive, statistika će se automatski popunjavati ovde.
            </div>
          ) : null}
        </section>
      </div>
    </section>
  );
}
