"use client";

import { useCallback, useState, useTransition } from "react";

import type { OptimizerReport, OptimizerSuggestion } from "@/lib/ai/profile-optimizer";
import { Spinner } from "@/components/common/Spinner";

/**
 * Client wrapper za AI Profile Optimizer.
 * Pokreće analizu na klik + prikazuje rezultat sa quick-win dugmadima.
 */
export function PortalOptimizerClient() {
  const [isPending, startTransition] = useTransition();
  const [report, setReport] = useState<OptimizerReport | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [applyingKey, setApplyingKey] = useState<string | null>(null);
  const [appliedKeys, setAppliedKeys] = useState<string[]>([]);

  const runAnalysis = useCallback(() => {
    setError(null);
    startTransition(async () => {
      try {
        const res = await fetch("/api/portal/optimizer/analyze", { method: "POST" });
        if (!res.ok) {
          const body = await res.json().catch(() => ({}));
          throw new Error(body.error || `HTTP ${res.status}`);
        }
        const data = (await res.json()) as { ok: boolean; report: OptimizerReport };
        setReport(data.report);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Greška pri analizi.");
      }
    });
  }, []);

  const applyQuickWin = useCallback(
    async (suggestion: OptimizerSuggestion) => {
      if (!suggestion.quickWin) return;
      const action = suggestion.actionUrl.split("action=")[1];
      if (!action) return;
      setApplyingKey(suggestion.key);
      try {
        const res = await fetch("/api/portal/optimizer/apply", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ action }),
        });
        if (!res.ok) {
          const body = await res.json().catch(() => ({}));
          throw new Error(body.error || `HTTP ${res.status}`);
        }
        setAppliedKeys((prev) => [...prev, suggestion.key]);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Greška pri primeni.");
      } finally {
        setApplyingKey(null);
      }
    },
    [],
  );

  if (!report) {
    return (
      <section className="rounded-3xl border border-border bg-gradient-to-br from-[#fff4f0] via-white to-[#fff4f0] p-8 text-center shadow-sm">
        <div className="mx-auto max-w-md">
          <div className="mx-auto mb-4 inline-flex h-14 w-14 items-center justify-center rounded-full bg-[#c2410c] text-2xl text-white shadow-lg">
            ✨
          </div>
          <h2 className="font-display text-[1.4rem] font-semibold text-foreground">
            Pokreni AI analizu profila
          </h2>
          <p className="mt-2 text-sm text-muted-foreground">
            AI će pregledati sve sekcije tvog profila i predložiti top 8 akcija
            koje daju najveći skok Health Score-a.
          </p>
          <button
            type="button"
            onClick={runAnalysis}
            disabled={isPending}
            className="mt-6 inline-flex items-center justify-center gap-2 rounded-xl bg-[#c2410c] px-6 py-3 text-sm font-bold text-white shadow-md transition hover:bg-[#c8421f] disabled:opacity-60"
          >
            {isPending ? <Spinner className="h-4 w-4" /> : null}
            {isPending ? "AI analizira profil…" : "Pokreni analizu sada"}
          </button>
          {error ? (
            <p className="mt-4 text-xs text-rose-700">{error}</p>
          ) : null}
          <p className="mt-4 text-[0.68rem] text-muted-foreground">
            Analiza traje 5-10 sekundi · Besplatno · Bez ograničenja
          </p>
        </div>
      </section>
    );
  }

  const potentialGain = report.potentialScore - report.currentScore;

  return (
    <div className="space-y-6">
      {/* Score progress card */}
      <section className="rounded-3xl border border-border bg-white p-6 shadow-sm">
        <div className="flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-[0.62rem] font-extrabold uppercase tracking-[0.18em] text-[#c2410c]">
              Dijagnostika
            </p>
            <p className="mt-2 max-w-2xl text-sm leading-relaxed text-foreground">
              {report.diagnosticSummary}
            </p>
            {report.aiAssisted ? (
              <p className="mt-2 text-[0.62rem] uppercase tracking-wider text-muted-foreground">
                ✨ AI-generisana analiza
              </p>
            ) : null}
          </div>
          <div className="rounded-2xl bg-gradient-to-br from-[#fff4f0] to-white p-4 text-right">
            <div className="text-[0.62rem] font-bold uppercase tracking-wider text-muted-foreground">
              Sada
            </div>
            <div className="text-2xl font-bold tabular-nums text-foreground">
              {report.currentScore}
            </div>
            <div className="mt-1 text-[0.62rem] uppercase tracking-wider text-emerald-700">
              Potencijal: <strong>{report.potentialScore}</strong> (+{potentialGain})
            </div>
          </div>
        </div>
      </section>

      {/* Suggestions list */}
      <section>
        <h2 className="mb-3 font-display text-[1.3rem] font-semibold text-foreground">
          Top {report.suggestions.length} preporuka
        </h2>
        <ul className="space-y-3">
          {report.suggestions.map((s, i) => {
            const applied = appliedKeys.includes(s.key);
            const applying = applyingKey === s.key;
            return (
              <li
                key={s.key}
                className={`rounded-2xl border p-5 transition ${
                  applied
                    ? "border-emerald-300 bg-emerald-50"
                    : "border-border bg-white hover:border-[#c2410c]/40"
                }`}
              >
                <div className="flex items-start gap-4">
                  <span
                    className={`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold ${
                      applied
                        ? "bg-emerald-500 text-white"
                        : "bg-[#c2410c] text-white"
                    }`}
                  >
                    {applied ? "✓" : i + 1}
                  </span>
                  <div className="flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <h3 className="text-sm font-bold text-foreground">{s.title}</h3>
                      {s.quickWin ? (
                        <span className="rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-bold text-violet-800">
                          Quick Win
                        </span>
                      ) : null}
                      <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-bold text-emerald-800">
                        +{s.estimatedHealthGain} score
                      </span>
                    </div>
                    <p className="mt-1.5 text-[0.82rem] leading-snug text-muted-foreground">
                      {s.rationale}
                    </p>
                  </div>
                  <div className="shrink-0 self-center">
                    {applied ? (
                      <span className="rounded-lg bg-emerald-500 px-3 py-1.5 text-[0.72rem] font-bold text-white">
                        Primenjeno
                      </span>
                    ) : s.quickWin ? (
                      <button
                        type="button"
                        onClick={() => applyQuickWin(s)}
                        disabled={applying}
                        className="rounded-lg bg-[#c2410c] px-3 py-1.5 text-[0.72rem] font-bold text-white hover:bg-[#c8421f] disabled:opacity-50"
                      >
                        {applying ? "Primenjujem…" : s.ctaLabel}
                      </button>
                    ) : (
                      <a
                        href={s.actionUrl}
                        className="inline-block rounded-lg border border-border bg-[#faf9f7] px-3 py-1.5 text-[0.72rem] font-semibold text-foreground hover:border-[#c2410c] hover:text-[#c2410c]"
                      >
                        {s.ctaLabel} →
                      </a>
                    )}
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </section>

      {error ? (
        <p className="text-xs text-rose-700">{error}</p>
      ) : null}

      <button
        type="button"
        onClick={runAnalysis}
        disabled={isPending}
        className="mt-2 inline-flex items-center gap-2 text-xs font-semibold text-[#c2410c] hover:underline"
      >
        {isPending ? <Spinner className="h-4 w-4" /> : null}
        {isPending ? "AI analizira profil…" : "↻ Ponovi analizu"}
      </button>
    </div>
  );
}
