"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { UniLogo } from "@/components/uni-logo";
import {
  AlertTriangle,
  CheckCircle2,
  ListChecks,
  PencilLine,
  Sparkles,
  X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { RISK_ETIKET, type RiskSeviyesi } from "@/lib/risk";
import { sonucHref } from "@/features/sihirbaz/sihirbaz-sabitler";
import {
  tercihDegerlendir,
  tercihListesiOzeti,
} from "@/lib/tercih-degerlendirme";
import {
  cikar,
  MANUEL_LISTE_MAX,
  useManuelListe,
  type ManuelTercih,
} from "../liste-store";
import {
  profilDuzenlemeyiAc,
  sonucaGitIste,
  useTercihProfili,
} from "../hooks/use-tercih-profili";

const RISK_STIL: Record<RiskSeviyesi, { nokta: string; kenar: string }> = {
  guvenli: { nokta: "bg-emerald-500", kenar: "border-l-emerald-500" },
  "az-riskli": { nokta: "bg-amber-500", kenar: "border-l-amber-500" },
  riskli: { nokta: "bg-red-500", kenar: "border-l-red-500" },
};

export function SecimlerimPaneli() {
  const router = useRouter();
  const liste = useManuelListe();
  const profil = useTercihProfili();

  const ozet = profil
    ? tercihListesiOzeti(
        liste.map((t) => ({
          isim: t.isim,
          il: t.il,
          unitur: t.unitur,
          efektifSira: t.efektifSira,
        })),
        profil,
      )
    : null;

  function sonucaGit() {
    const { href } = sonucaGitIste();
    if (href) router.push(href);
  }

  if (liste.length === 0) {
    return (
      <section className="rounded-2xl border border-slate-200 bg-white p-8 text-center">
        <ListChecks className="mx-auto size-10 text-slate-300" aria-hidden />
        <h2 className="mt-4 font-heading text-xl font-bold">
          Henüz program seçmedin
        </h2>
        <p className="mx-auto mt-2 max-w-md text-sm text-slate-600">
          Bölüm, üniversite veya sonuç sayfalarındaki tablolardan{" "}
          <span aria-hidden>＋</span> ile program ekle. Tercihlerine göre
          risk ve uyum notlarını burada göreceksin.
        </p>
        <div className="mt-6 flex flex-wrap justify-center gap-3">
          <Button asChild variant="outline" className="cursor-pointer">
            <Link href="/bolumler">Bölümlere göz at</Link>
          </Button>
          {profil ? (
            <Button
              asChild
              className="cursor-pointer bg-orange-500 text-white hover:bg-orange-600"
            >
              <Link href={sonucHref(profil)}>Sonuçlara git</Link>
            </Button>
          ) : (
            <Button
              type="button"
              onClick={sonucaGit}
              className="cursor-pointer bg-orange-500 text-white hover:bg-orange-600"
            >
              Sıralamanı gir
            </Button>
          )}
        </div>
      </section>
    );
  }

  return (
    <section className="flex flex-col gap-6">
      <div className="rounded-2xl border border-slate-200 bg-white p-5">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <h2 className="flex items-center gap-2 font-heading text-xl font-bold">
              <ListChecks className="size-5 text-primary" aria-hidden />
              Kendi Listem
              <span className="text-sm font-bold tabular-nums text-slate-400">
                {liste.length}/{MANUEL_LISTE_MAX}
              </span>
            </h2>
            <p className="mt-1 text-sm text-slate-600">
              {profil
                ? `${profil.sira.toLocaleString("tr-TR")}. sıra · tercihlerine göre değerlendirme`
                : "Tercih profilin oluşunca uyum notları görünür."}
            </p>
          </div>
          {profil ? (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={profilDuzenlemeyiAc}
              className="cursor-pointer"
            >
              <PencilLine className="size-4" aria-hidden />
              Tercihlerimi düzenle
            </Button>
          ) : (
            <Button
              type="button"
              size="sm"
              onClick={sonucaGit}
              className="cursor-pointer bg-orange-500 text-white hover:bg-orange-600"
            >
              Sıralamanı gir
            </Button>
          )}
        </div>

        <div
          className="mt-4 h-1.5 overflow-hidden rounded-full bg-slate-100"
          role="progressbar"
          aria-valuenow={liste.length}
          aria-valuemin={0}
          aria-valuemax={MANUEL_LISTE_MAX}
          aria-label="Liste doluluğu"
        >
          <div
            className="h-full rounded-full bg-primary transition-[width] duration-300"
            style={{
              width: `${Math.round((liste.length / MANUEL_LISTE_MAX) * 100)}%`,
            }}
          />
        </div>

        {ozet ? (
          <dl className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <Istatistik etiket="Hayal" deger={ozet.hayal} />
            <Istatistik etiket="Dengeli" deger={ozet.dengeli} />
            <Istatistik etiket="Daha güvenli" deger={ozet.dahaGuvenli} />
            <Istatistik etiket="Dikkat" deger={ozet.dikkat} />
          </dl>
        ) : null}

        {ozet ? (
          <p className="mt-4 flex items-start gap-2 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 text-sm text-slate-700">
            <Sparkles className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden />
            {ozet.oneri}
            {ozet.gucluUyum > 0 ? (
              <span className="sr-only">
                {ozet.gucluUyum} program güçlü uyum gösteriyor.
              </span>
            ) : null}
          </p>
        ) : null}
      </div>

      <ol className="flex flex-col gap-3">
        {liste.map((t, i) => (
          <SecimSatiri key={t.id} tercih={t} sira={i + 1} />
        ))}
      </ol>
    </section>
  );
}

function Istatistik({ etiket, deger }: { etiket: string; deger: number }) {
  return (
    <div className="rounded-xl border border-slate-100 bg-slate-50 px-3 py-2">
      <dt className="text-[11px] font-medium uppercase tracking-wide text-slate-500">
        {etiket}
      </dt>
      <dd className="mt-0.5 font-heading text-xl font-bold tabular-nums text-slate-900">
        {deger}
      </dd>
    </div>
  );
}

function SecimSatiri({
  tercih,
  sira,
}: {
  tercih: ManuelTercih;
  sira: number;
}) {
  const profil = useTercihProfili();
  const degerlendirme = profil
    ? tercihDegerlendir(
        {
          isim: tercih.isim,
          il: tercih.il,
          unitur: tercih.unitur,
          efektifSira: tercih.efektifSira,
        },
        profil,
      )
    : null;
  const risk = degerlendirme?.risk ?? tercih.risk;
  const stil = risk ? RISK_STIL[risk] : null;

  return (
    <li
      className={`rounded-2xl border border-l-4 border-slate-200 bg-white p-4 ${
        stil?.kenar ?? "border-l-slate-300"
      }`}
    >
      <div className="flex items-start gap-3">
        <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-slate-100 font-heading text-xs font-bold tabular-nums">
          {sira}
        </span>
        <div className="min-w-0 flex-1">
          <div className="flex items-start justify-between gap-2">
            <div className="flex min-w-0 items-center gap-2.5">
              <UniLogo ad={tercih.universite} boy="sm" />
              <div className="min-w-0">
                <p className="truncate font-semibold text-slate-900">
                  {tercih.isim}
                </p>
                <p className="truncate text-xs text-slate-500">
                  {tercih.universite}
                  {tercih.il
                    ? ` · ${tercih.il.toLocaleLowerCase("tr-TR")}`
                    : ""}
                  {tercih.efektifSira != null
                    ? ` · ~${tercih.efektifSira.toLocaleString("tr-TR")}.`
                    : ""}
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={() => cikar(tercih.id)}
              className="shrink-0 cursor-pointer rounded-full p-2 text-slate-300 transition-colors hover:bg-slate-100 hover:text-red-500"
            >
              <X className="size-4" aria-hidden />
              <span className="sr-only">{tercih.isim} listeden çıkar</span>
            </button>
          </div>

          {degerlendirme ? (
            <div className="mt-3 flex flex-col gap-2">
              <p className="flex items-center gap-2 text-xs font-medium text-slate-700">
                {risk ? (
                  <span
                    className={`size-2 rounded-full ${RISK_STIL[risk].nokta}`}
                    aria-hidden
                  />
                ) : null}
                {degerlendirme.riskEtiketi}
                {risk ? (
                  <span className="font-normal text-slate-500">
                    ({RISK_ETIKET[risk]})
                  </span>
                ) : null}
              </p>
              <p className="text-sm text-slate-600">{degerlendirme.riskMetni}</p>
              {degerlendirme.olumlu.slice(0, 2).map((m) => (
                <p
                  key={m}
                  className="flex items-start gap-1.5 text-sm text-emerald-800"
                >
                  <CheckCircle2 className="mt-0.5 size-3.5 shrink-0" aria-hidden />
                  {m}
                </p>
              ))}
              {degerlendirme.celiskiler.slice(0, 2).map((m) => (
                <p
                  key={m}
                  className="flex items-start gap-1.5 text-sm text-amber-900"
                >
                  <AlertTriangle className="mt-0.5 size-3.5 shrink-0" aria-hidden />
                  {m}
                </p>
              ))}
            </div>
          ) : (
            <p className="mt-2 text-sm text-slate-500">
              Tercih profilin tamamlanınca bu programı değerlendireceğiz.
            </p>
          )}
        </div>
      </div>
    </li>
  );
}
