"use client";

import { useState } from "react";
import { BarChart3, ExternalLink, RefreshCcw, TriangleAlert } from "lucide-react";
import { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { useT, useLocale } from "@/shared/i18n/client";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import { SearchableSelect } from "@/presentation/components/ui/searchable-select";
import type { Announcement } from "@/domain/entities/announcement";

// Validated categorical pair (light surface): seen = blue, not seen = orange (+ dashed line).
const SEEN = "#2563eb";
const NOT_SEEN = "#ea580c";

const pct = (part: number, whole: number) => (whole > 0 ? Math.round((part / whole) * 100) : 0);

/** Statistics of one announcement: funnel, per step, broken placements, adoption (spec §8.1). */
export function AnnouncementStats({ announcement }: { announcement: Announcement }) {
  const t = useT();
  const locale = useLocale();
  const s = t.announcements.stats;
  const { announcementRepository } = useRepositories();
  const [round, setRound] = useState<number | undefined>(undefined);
  const nf = (n: number) => n.toLocaleString(locale === "fr" ? "fr-FR" : "en-US", { maximumFractionDigits: 1 });

  const { data, loading } = useApiQuery(() => announcementRepository.stats(announcement.id, round), {
    deps: [announcement.id, round, announcement.updated_at],
  });

  if (!announcement.first_published_at) {
    return (
      <div className="flex flex-col items-center gap-2 rounded-xl border bg-card py-16 text-center text-sm text-muted-foreground">
        <BarChart3 className="h-8 w-8 opacity-40" />
        {s.notPublished}
      </div>
    );
  }
  if (loading && !data) return <Skeleton className="h-96 w-full rounded-xl" />;
  if (!data) return null;

  const c = data.counts;
  const funnel = [
    { label: s.eligible, value: c.eligible, of: null as number | null },
    { label: s.seen, value: c.seen, of: c.eligible },
    { label: s.clicked, value: c.clicked, of: c.seen },
    { label: s.completed, value: c.completed, of: c.seen },
  ];
  const max = Math.max(1, c.eligible);

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <SearchableSelect
          label={s.round}
          triggerClassName="w-48"
          value={String(round ?? data.round)}
          onValueChange={(v) => setRound(Number(v))}
          options={[
            ...data.rounds.map((r) => ({ value: String(r), label: t.announcements.list.round(r) })),
            ...(data.rounds.length > 1 ? [{ value: "0", label: s.allRounds }] : []),
          ]}
        />
        {data.posthog_url && (
          <a href={data.posthog_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1.5 text-sm font-medium text-blue-700 hover:underline">
            <ExternalLink className="h-4 w-4" />
            {s.posthog}
          </a>
        )}
      </div>

      <div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-5">
        {[
          { label: s.eligible, value: nf(c.eligible) },
          { label: s.seen, value: nf(c.seen), sub: `${pct(c.seen, c.eligible)} %` },
          { label: s.clicked, value: nf(c.clicked), sub: `${pct(c.clicked, c.seen)} %` },
          { label: s.completed, value: nf(c.completed), sub: `${pct(c.completed, c.seen)} %` },
          { label: s.dismissRate, value: `${nf(data.dismiss_rate)} %`, sub: `${nf(c.dismissed)} ${s.dismissed.toLowerCase()}` },
        ].map((tile) => (
          <div key={tile.label} className="rounded-xl border bg-card p-4">
            <div className="text-xs font-medium text-muted-foreground">{tile.label}</div>
            <div className="mt-1 text-2xl font-bold tabular-nums">{tile.value}</div>
            {tile.sub && <div className="text-xs tabular-nums text-muted-foreground">{tile.sub}</div>}
          </div>
        ))}
      </div>

      <div className={data.steps.length > 0 ? "grid gap-5 lg:grid-cols-2" : "grid gap-5"}>
        <section className="rounded-xl border bg-card p-5" aria-labelledby="stats-funnel">
          <h3 id="stats-funnel" className="mb-4 text-sm font-semibold">{s.funnel}</h3>
          <ul className="space-y-3">
            {funnel.map((row) => (
              <li key={row.label} title={`${row.label} : ${nf(row.value)}`}>
                <div className="mb-1 flex items-baseline justify-between text-xs">
                  <span className="font-medium">{row.label}</span>
                  <span className="tabular-nums text-muted-foreground">
                    <b className="text-foreground">{nf(row.value)}</b>
                    {row.of !== null && ` · ${pct(row.value, row.of)} %`}
                  </span>
                </div>
                <div className="h-2.5 rounded-full bg-muted">
                  <div className="h-2.5 rounded-full" style={{ width: `${(row.value / max) * 100}%`, background: SEEN }} />
                </div>
              </li>
            ))}
          </ul>
        </section>

        {data.steps.length > 0 && (
          <section className="rounded-xl border bg-card p-5" aria-labelledby="stats-steps">
            <h3 id="stats-steps" className="mb-4 text-sm font-semibold">{s.perStep}</h3>
            <table className="w-full text-xs">
              <thead className="text-muted-foreground">
                <tr>
                  <th className="pb-2 text-left font-medium">#</th>
                  <th className="pb-2 text-left font-medium" />
                  <th className="pb-2 text-right font-medium">{s.stepSeen}</th>
                  <th className="pb-2 text-right font-medium">{s.stepCompleted}</th>
                  <th className="pb-2 text-right font-medium">{s.anchorMissing}</th>
                </tr>
              </thead>
              <tbody>
                {data.steps.map((step, i) => (
                  <tr key={step.step_id} className="border-t">
                    <td className="py-2 pr-2 font-semibold">{i + 1}</td>
                    <td className="py-2 pr-2">
                      <div className="truncate font-medium">{step.title}</div>
                      <div className="mt-1 h-1.5 rounded-full bg-muted">
                        <div className="h-1.5 rounded-full" style={{ width: `${pct(step.seen, Math.max(1, data.steps[0].seen))}%`, background: SEEN }} />
                      </div>
                      {i > 0 && <div className="mt-0.5 text-[10px] text-muted-foreground">{s.ofPrevious(pct(step.seen, data.steps[i - 1].seen))}</div>}
                    </td>
                    <td className="py-2 text-right tabular-nums">{nf(step.seen)}</td>
                    <td className="py-2 text-right tabular-nums">{nf(step.completed)}</td>
                    <td className={step.anchor_missing ? "py-2 text-right font-semibold tabular-nums text-amber-700" : "py-2 text-right tabular-nums text-muted-foreground"}>
                      {nf(step.anchor_missing)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        )}
      </div>

      {data.anchor_missing > 0 && (
        <p className="flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900" role="status">
          <TriangleAlert className="h-4 w-4 shrink-0" />
          {s.anchorMissingWarn(data.anchor_missing)}
        </p>
      )}

      <section className="rounded-xl border bg-card p-5" aria-labelledby="stats-adoption">
        <h3 id="stats-adoption" className="text-sm font-semibold">{s.adoption}</h3>
        <p className="mb-4 text-xs text-muted-foreground">{s.adoptionHelp}</p>
        {!data.adoption.event ? (
          <p className="text-sm text-muted-foreground">{s.noEvent}</p>
        ) : (
          <div className="grid gap-5 lg:grid-cols-[220px_1fr]">
            <div className="space-y-3">
              <div className="rounded-lg border p-3">
                <div className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <span className="h-2 w-2 rounded-full" style={{ background: SEEN }} />
                  {s.adoptedSeen}
                </div>
                <div className="mt-1 text-2xl font-bold tabular-nums">{nf(data.adoption.rate_seen)} %</div>
                <div className="text-xs tabular-nums text-muted-foreground">{nf(data.adoption.adopted_after_seen)}</div>
              </div>
              <div className="rounded-lg border p-3">
                <div className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
                  <span className="h-2 w-2 rounded-full" style={{ background: NOT_SEEN }} />
                  {s.adoptedNotSeen}
                </div>
                <div className="mt-1 text-2xl font-bold tabular-nums">{nf(data.adoption.rate_not_seen)} %</div>
                <div className="text-xs tabular-nums text-muted-foreground">{nf(data.adoption.adopted_not_seen)}</div>
              </div>
              {data.reminder_targets > 0 && (
                <p className="flex items-start gap-1.5 text-xs text-muted-foreground">
                  <RefreshCcw className="mt-0.5 h-3.5 w-3.5 shrink-0" />
                  {s.reminderTargets(data.reminder_targets)}
                </p>
              )}
            </div>
            <div className="h-56">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={data.adoption.series} margin={{ top: 8, right: 16, bottom: 0, left: -12 }}>
                  <CartesianGrid stroke="#e5e7eb" strokeDasharray="0" vertical={false} />
                  <XAxis
                    dataKey="date"
                    tickFormatter={(d: string) => new Date(d).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-US", { day: "2-digit", month: "short" })}
                    tick={{ fontSize: 11, fill: "#6b7280" }}
                    axisLine={false}
                    tickLine={false}
                    minTickGap={24}
                  />
                  <YAxis tickFormatter={(v: number) => `${v} %`} tick={{ fontSize: 11, fill: "#6b7280" }} axisLine={false} tickLine={false} width={48} />
                  <Tooltip
                    formatter={(v, name) => [`${v} %`, name]}
                    labelFormatter={(d) => new Date(String(d)).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-US")}
                    contentStyle={{ fontSize: 12, borderRadius: 8 }}
                  />
                  <Legend wrapperStyle={{ fontSize: 12 }} iconType="plainline" />
                  <Line type="monotone" dataKey="rate_seen" name={s.adoptedSeen} stroke={SEEN} strokeWidth={2} dot={false} activeDot={{ r: 4 }} />
                  <Line type="monotone" dataKey="rate_not_seen" name={s.adoptedNotSeen} stroke={NOT_SEEN} strokeWidth={2} strokeDasharray="5 4" dot={false} activeDot={{ r: 4 }} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}
      </section>
    </div>
  );
}
