"use client";

import { useMemo, useRef, useState } from "react";
import Link from "next/link";
import { ChevronDown, ChevronUp } from "lucide-react";
import type { Program } from "@/types/yokatlas";
import { trBaslikDuzeni } from "@/lib/slug";
import { Sayfalama, SAYFA_BOYU } from "./sayfalama";
import {
  ProgramSiraGecmisi,
  ProgramTabanTrendi,
} from "@/components/program-liste-verileri";
import { ProgramEkleButonu } from "@/features/liste/components/program-ekle-butonu";
import { ProgramNetleriButonu } from "./program-netleri";
import { UniLogo } from "@/components/uni-logo";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

const sayi = (n: number) => n.toLocaleString("tr-TR");

type SiralamaAlani = "sira2025" | "puan2025" | "kontenjan2025";
type SiralamaYonu = "artan" | "azalan";
export type BolumProgrami = Program & { universiteSlug: string | null };

const ALAN_ETIKETLERI: Record<SiralamaAlani, string> = {
  sira2025: "Sıralama",
  puan2025: "Puan",
  kontenjan2025: "Kontenjan",
};

function SiralamaDugmesi({
  alan,
  aktifAlan,
  yon,
  onSirala,
}: {
  alan: SiralamaAlani;
  aktifAlan: SiralamaAlani | null;
  yon: SiralamaYonu;
  onSirala: (alan: SiralamaAlani) => void;
}) {
  const aktif = alan === aktifAlan;
  const etiket = ALAN_ETIKETLERI[alan];

  return (
    <button
      type="button"
      onClick={() => onSirala(alan)}
      aria-label={`${etiket}: ${
        aktif && yon === "artan" ? "azalan" : "artan"
      } sırala`}
      aria-pressed={aktif}
      className="inline-flex min-h-11 cursor-pointer items-center gap-1 rounded-full px-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
    >
      <span>{etiket}</span>
      <span className="flex flex-col -space-y-1" aria-hidden>
        <ChevronUp
          className={`size-3 ${
            aktif && yon === "artan"
              ? "text-primary"
              : "text-muted-foreground/40"
          }`}
          strokeWidth={aktif && yon === "artan" ? 3 : 2}
        />
        <ChevronDown
          className={`size-3 ${
            aktif && yon === "azalan"
              ? "text-primary"
              : "text-muted-foreground/40"
          }`}
          strokeWidth={aktif && yon === "azalan" ? 3 : 2}
        />
      </span>
    </button>
  );
}

export function BolumProgramListesi({
  programlar,
  bazAd,
  tabanYol,
  sayfa,
}: {
  /** Bölümün TÜM programları — sıralama liste geneline uygulanır. */
  programlar: BolumProgrami[];
  bazAd: string;
  tabanYol: string;
  sayfa: number;
}) {
  const [aktifAlan, setAktifAlan] = useState<SiralamaAlani | null>(null);
  const [yon, setYon] = useState<SiralamaYonu>("artan");
  // Sıralama aktifken URL değişmeden istemci tarafında gezilen sayfa
  const [istemciSayfa, setIstemciSayfa] = useState(1);
  const listeRef = useRef<HTMLDivElement>(null);

  const toplamSayfa = Math.max(1, Math.ceil(programlar.length / SAYFA_BOYU));

  const siraliProgramlar = useMemo(() => {
    if (!aktifAlan) return programlar;

    return programlar
      .map((program, index) => ({ program, index }))
      .sort((a, b) => {
        const aDeger = a.program[aktifAlan];
        const bDeger = b.program[aktifAlan];
        if (aDeger == null && bDeger == null) return a.index - b.index;
        if (aDeger == null) return 1;
        if (bDeger == null) return -1;

        const fark = aDeger - bDeger;
        return fark === 0 ? a.index - b.index : yon === "artan" ? fark : -fark;
      })
      .map(({ program }) => program);
  }, [aktifAlan, programlar, yon]);

  const gosterilenSayfa = aktifAlan ? istemciSayfa : sayfa;
  const gosterilenProgramlar = useMemo(
    () =>
      siraliProgramlar.slice(
        (gosterilenSayfa - 1) * SAYFA_BOYU,
        gosterilenSayfa * SAYFA_BOYU,
      ),
    [siraliProgramlar, gosterilenSayfa],
  );

  function sirala(alan: SiralamaAlani) {
    setIstemciSayfa(1);
    if (aktifAlan === alan) {
      setYon((mevcut) => (mevcut === "artan" ? "azalan" : "artan"));
      return;
    }
    setAktifAlan(alan);
    setYon("artan");
  }

  function istemciSayfaDegistir(n: number) {
    setIstemciSayfa(n);
    listeRef.current?.scrollIntoView({ block: "start" });
  }

  return (
    <>
      <div
        ref={listeRef}
        className="scroll-mt-24 overflow-hidden rounded-2xl border border-slate-200 bg-white"
      >
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Üniversite</TableHead>
              <TableHead className="hidden text-right md:table-cell">
                Son 5 yıl
              </TableHead>
              <TableHead className="hidden text-right lg:table-cell">
                <SiralamaDugmesi
                  alan="puan2025"
                  aktifAlan={aktifAlan}
                  yon={yon}
                  onSirala={sirala}
                />
              </TableHead>
              <TableHead className="hidden text-right sm:table-cell">
                <SiralamaDugmesi
                  alan="kontenjan2025"
                  aktifAlan={aktifAlan}
                  yon={yon}
                  onSirala={sirala}
                />
              </TableHead>
              <TableHead className="text-right">
                <SiralamaDugmesi
                  alan="sira2025"
                  aktifAlan={aktifAlan}
                  yon={yon}
                  onSirala={sirala}
                />
              </TableHead>
              <TableHead className="w-24 text-right">
                <span className="sr-only">Netler ve listeye ekle</span>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {gosterilenProgramlar.map((p) => {
              const uniAd = trBaslikDuzeni(p.universite);
              const varyant = p.isim.trim() !== bazAd ? p.isim.trim() : null;
              const devlet = p.unitur === "DEVLET";

              return (
                <TableRow key={p.id}>
                  <TableCell className="max-w-0 w-full">
                    <span className="flex min-w-0 items-center gap-2.5">
                      {p.universiteSlug ? (
                        <UniLogo slug={p.universiteSlug} ad={uniAd} boy="sm" />
                      ) : null}
                      <span className="min-w-0 flex-1">
                        {p.universiteSlug ? (
                          <Link
                            href={`/universite/${p.universiteSlug}`}
                            className="block truncate text-sm font-semibold hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                          >
                            {uniAd}
                          </Link>
                        ) : (
                          <span className="block truncate text-sm font-semibold">
                            {uniAd}
                          </span>
                        )}
                        <span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-slate-500">
                          {p.unitur ? (
                            <span
                              className={`shrink-0 rounded px-1 py-px text-[10px] font-medium leading-4 ${
                                devlet
                                  ? "bg-slate-100 text-slate-600"
                                  : "bg-violet-50 text-violet-600"
                              }`}
                            >
                              {devlet ? "Devlet" : trBaslikDuzeni(p.unitur)}
                            </span>
                          ) : null}
                          <span className="truncate">
                            {p.il ? trBaslikDuzeni(p.il) : null}
                            {varyant ? `${p.il ? " · " : ""}${varyant}` : ""}
                          </span>
                          {p.sure ? (
                            <span className="shrink-0 text-slate-400">
                              · {p.sure} yıl
                            </span>
                          ) : null}
                        </span>
                      </span>
                    </span>
                  </TableCell>
                  <TableCell className="hidden text-right text-xs md:table-cell">
                    <ProgramSiraGecmisi program={p} />
                  </TableCell>
                  <TableCell className="hidden text-right text-xs tabular-nums text-slate-500 lg:table-cell">
                    {p.puan2025 != null
                      ? p.puan2025.toFixed(2).replace(".", ",")
                      : "—"}
                  </TableCell>
                  <TableCell className="hidden text-right text-xs tabular-nums text-slate-500 sm:table-cell">
                    {p.kontenjan2025 != null ? `${sayi(p.kontenjan2025)} kişi` : "—"}
                  </TableCell>
                  <TableCell className="text-right text-xs tabular-nums text-slate-500">
                    <span className="inline-flex items-center gap-1">
                      <ProgramTabanTrendi program={p} />
                      {p.sira2025 != null ? `~${sayi(p.sira2025)}.` : "—"}
                    </span>
                  </TableCell>
                  <TableCell className="pr-3 text-right">
                    <span className="inline-flex items-center gap-1.5">
                      <ProgramNetleriButonu
                        programId={p.id}
                        isim={p.isim.trim()}
                        universite={uniAd}
                        className="size-8 min-h-8 min-w-8"
                      />
                      <ProgramEkleButonu
                        program={p}
                        kaynak="bolum"
                        className="size-8 min-h-8 min-w-8"
                      />
                    </span>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>
      <Sayfalama
        tabanYol={tabanYol}
        sayfa={gosterilenSayfa}
        toplamSayfa={toplamSayfa}
        onSayfa={aktifAlan ? istemciSayfaDegistir : undefined}
      />
    </>
  );
}
