import type { Metadata } from "next";
import Link from "next/link";
import { listAllCategoriesForAdmin, listAllQuotesForAdmin } from "@/lib/quotes/queries";
import {
  createQuoteCategory,
  toggleCategoryActive,
  deleteQuoteCategory,
  reorderQuoteCategories,
  createQuote,
  toggleQuoteActive,
  deleteQuote,
  reorderQuotes,
} from "@/lib/admin/quotes-actions";
import { SortableList } from "@/components/admin/SortableList";

export const metadata: Metadata = {
  title: "Güzel Sözler",
};

const FILTERS = [
  { key: "tumu", label: "Tümü" },
  { key: "bekleyen", label: "Bekleyen Sözler" },
  { key: "yayinda", label: "Yayında" },
] as const;

type FilterKey = (typeof FILTERS)[number]["key"];
const PENDING_PREVIEW = 5;

export default async function AdminQuotesPage({
  searchParams,
}: {
  searchParams: Promise<{ durum?: string; kategori?: string }>;
}) {
  const { durum, kategori } = await searchParams;
  const activeFilter: FilterKey = FILTERS.some((f) => f.key === durum) ? (durum as FilterKey) : "tumu";

  const [categories, quotes] = await Promise.all([listAllCategoriesForAdmin(), listAllQuotesForAdmin()]);

  const totalPending = quotes.filter((q) => !q.isActive).length;
  const totalActive = quotes.length - totalPending;

  const focusedCategory = kategori ? categories.find((c) => c.id === kategori) ?? null : null;

  const visibleQuotes = quotes.filter((quote) => {
    if (activeFilter === "bekleyen" && quote.isActive) return false;
    if (activeFilter === "yayinda" && !quote.isActive) return false;
    if (focusedCategory && quote.categoryId !== focusedCategory.id) return false;
    return true;
  });

  const categoriesToRender = focusedCategory ? [focusedCategory] : categories;

  function filterHref(filterKey: FilterKey) {
    const params = new URLSearchParams();
    if (filterKey !== "tumu") params.set("durum", filterKey);
    if (focusedCategory) params.set("kategori", focusedCategory.id);
    const qs = params.toString();
    return qs ? `/admin/sozler?${qs}` : "/admin/sozler";
  }

  return (
    <div className="p-8">
      <div className="mb-6 border-b border-border pb-6">
        <h1 className="text-[22px]">Güzel Sözler</h1>
        <p className="mt-0.5 text-[12.5px] text-text-muted">
          {totalPending} bekleyen · {totalActive} yayında söz — kategoriler ve sözler sürükleyerek sıralanabilir
        </p>
      </div>

      <div className="mb-8">
        <h2 className="mb-3 text-[13px] font-bold text-text-muted">Kategori Başına Bekleyen Söz Havuzu</h2>
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
          {categories.map((category) => {
            const pending = quotes.filter((q) => q.categoryId === category.id && !q.isActive).length;
            return (
              <Link
                key={category.id}
                href={`/admin/sozler?durum=bekleyen&kategori=${category.id}`}
                className="rounded-xl border border-border bg-surface p-3 hover:border-accent"
              >
                <div className="truncate text-[12px] font-semibold text-text-muted">{category.name}</div>
                <div className={`font-heading text-[20px] ${pending === 0 ? "text-accent" : ""}`}>{pending}</div>
              </Link>
            );
          })}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-8 lg:grid-cols-[320px_minmax(0,1fr)]">
        <section>
          <h2 className="mb-3 text-[15px] font-bold">Kategoriler</h2>
          <form action={createQuoteCategory} className="mb-4 flex gap-2">
            <input
              name="name"
              placeholder="Yeni kategori (örn. Aşk Sözleri)"
              required
              className="flex-1 rounded-lg border border-border px-3 py-2 text-[13px]"
            />
            <button className="rounded-lg bg-accent px-3.5 py-2 text-[12.5px] font-semibold text-white">Ekle</button>
          </form>

          <SortableList
            key={categories.map((c) => c.id).join(",")}
            items={categories.map((category) => {
              const toggle = toggleCategoryActive.bind(null, category.id);
              const remove = deleteQuoteCategory.bind(null, category.id);
              return {
                id: category.id,
                content: (
                  <div className="flex items-center justify-between rounded-xl border border-border bg-surface px-3 py-2.5">
                    <div className="flex items-center gap-2">
                      <span className="text-[13.5px] font-semibold">{category.name}</span>
                      <span
                        className={`rounded-full px-2 py-0.5 text-[10.5px] font-semibold ${
                          category.isActive ? "bg-green-100 text-green-700" : "bg-accent/10 text-accent"
                        }`}
                      >
                        {category.isActive ? "Aktif" : "Pasif"}
                      </span>
                    </div>
                    <div className="flex gap-1.5">
                      <form action={toggle}>
                        <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-text-muted hover:bg-bg-alt">
                          {category.isActive ? "Gizle" : "Göster"}
                        </button>
                      </form>
                      <form action={remove}>
                        <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-accent hover:bg-accent/10">
                          Sil
                        </button>
                      </form>
                    </div>
                  </div>
                ),
              };
            })}
            onReorder={reorderQuoteCategories}
          />
        </section>

        <section>
          <h2 className="mb-3 text-[15px] font-bold">Sözler</h2>
          <form action={createQuote} className="mb-4 flex flex-wrap gap-2 rounded-2xl border border-border bg-surface p-4">
            <select name="categoryId" required className="rounded-lg border border-border px-3 py-2 text-[13px]">
              <option value="">Kategori seç</option>
              {categories.map((category) => (
                <option key={category.id} value={category.id}>
                  {category.name}
                </option>
              ))}
            </select>
            <input name="author" placeholder="Yazar (opsiyonel)" className="rounded-lg border border-border px-3 py-2 text-[13px]" />
            <textarea
              name="text"
              placeholder="Söz metni"
              required
              rows={2}
              className="w-full resize-none rounded-lg border border-border px-3 py-2 text-[13px]"
            />
            <button className="rounded-lg bg-accent px-4 py-2 text-[12.5px] font-semibold text-white">Söz Ekle</button>
          </form>

          <div className="mb-4 flex flex-wrap items-center gap-2">
            {FILTERS.map((filter) => {
              const count = filter.key === "bekleyen" ? totalPending : filter.key === "yayinda" ? totalActive : quotes.length;
              const isActive = filter.key === activeFilter;
              return (
                <Link
                  key={filter.key}
                  href={filterHref(filter.key)}
                  className={`flex items-center gap-1.5 rounded-full border px-4 py-1.5 text-[12.5px] font-semibold transition-colors ${
                    isActive ? "border-accent bg-accent text-white" : "border-border bg-surface text-text-muted hover:border-accent"
                  }`}
                >
                  {filter.label}
                  <span
                    className={`rounded-full px-1.5 py-0.5 text-[10.5px] font-bold ${
                      isActive ? "bg-white/20 text-white" : "bg-bg-alt text-text-muted"
                    }`}
                  >
                    {count}
                  </span>
                </Link>
              );
            })}
            {focusedCategory && (
              <Link
                href={activeFilter === "tumu" ? "/admin/sozler" : `/admin/sozler?durum=${activeFilter}`}
                className="flex items-center gap-1 text-[12.5px] font-semibold text-text-muted hover:text-accent"
              >
                ✕ {focusedCategory.name} filtresini kaldır
              </Link>
            )}
          </div>

          <div className="flex flex-col gap-6">
            {categoriesToRender.map((category) => {
              const categoryQuotes = visibleQuotes.filter((quote) => quote.categoryId === category.id);
              if (categoryQuotes.length === 0) return null;

              const activeOnes = categoryQuotes.filter((q) => q.isActive);
              const pendingOnes = categoryQuotes.filter((q) => !q.isActive);
              const previewLimit = focusedCategory ? pendingOnes.length : PENDING_PREVIEW;
              const pendingPreview = pendingOnes.slice(0, previewLimit);
              const pendingRestCount = pendingOnes.length - pendingPreview.length;

              function pendingRow(quote: (typeof pendingOnes)[number]) {
                const toggle = toggleQuoteActive.bind(null, quote.id);
                const remove = deleteQuote.bind(null, quote.id);
                return (
                  <div key={quote.id} className="flex flex-wrap items-center justify-between gap-y-1.5 rounded-xl border border-border bg-surface px-3 py-2.5">
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-[13.5px]">{quote.text}</p>
                      <span className="text-[11.5px] text-text-muted">— {quote.author ?? "Anonim"}</span>
                    </div>
                    <div className="ml-3 flex shrink-0 items-center gap-1.5">
                      {quote.source === "BOT" && (
                        <span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10.5px] font-semibold text-blue-700">Bot</span>
                      )}
                      <span className="rounded-full bg-accent/10 px-2 py-0.5 text-[10.5px] font-semibold text-accent">Bekliyor</span>
                      <form action={toggle}>
                        <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-text-muted hover:bg-bg-alt">Göster</button>
                      </form>
                      <form action={remove}>
                        <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-accent hover:bg-accent/10">Sil</button>
                      </form>
                    </div>
                  </div>
                );
              }

              return (
                <div key={category.id}>
                  <h3 className="mb-2 text-[13px] font-semibold text-text-muted">
                    {category.name}
                    {pendingOnes.length > 0 && (
                      <span className="ml-2 font-normal text-text-muted">({pendingOnes.length} bekliyor)</span>
                    )}
                  </h3>

                  {activeOnes.length > 0 && (
                    <SortableList
                      key={activeOnes.map((q) => q.id).join(",")}
                      items={activeOnes.map((quote) => {
                        const toggle = toggleQuoteActive.bind(null, quote.id);
                        const remove = deleteQuote.bind(null, quote.id);
                        return {
                          id: quote.id,
                          content: (
                            <div className="flex flex-wrap items-center justify-between gap-y-1.5 rounded-xl border border-border bg-surface px-3 py-2.5">
                              <div className="min-w-0 flex-1">
                                <p className="truncate text-[13.5px]">{quote.text}</p>
                                <span className="text-[11.5px] text-text-muted">— {quote.author ?? "Anonim"}</span>
                              </div>
                              <div className="ml-3 flex shrink-0 items-center gap-1.5">
                                {quote.source === "BOT" && (
                                  <span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10.5px] font-semibold text-blue-700">
                                    Bot
                                  </span>
                                )}
                                <span className="rounded-full bg-green-100 px-2 py-0.5 text-[10.5px] font-semibold text-green-700">
                                  Yayında
                                </span>
                                <form action={toggle}>
                                  <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-text-muted hover:bg-bg-alt">
                                    Gizle
                                  </button>
                                </form>
                                <form action={remove}>
                                  <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-accent hover:bg-accent/10">
                                    Sil
                                  </button>
                                </form>
                              </div>
                            </div>
                          ),
                        };
                      })}
                      onReorder={reorderQuotes}
                    />
                  )}

                  {pendingOnes.length > 0 && (
                    <div className={`flex flex-col gap-1.5 ${activeOnes.length > 0 ? "mt-1.5" : ""}`}>
                      {pendingPreview.map(pendingRow)}
                      {pendingRestCount > 0 && (
                        <Link
                          href={`/admin/sozler?durum=bekleyen&kategori=${category.id}`}
                          className="py-1 text-[11.5px] font-semibold text-accent hover:underline"
                        >
                          {pendingRestCount} bekleyen söz daha — tümünü gör
                        </Link>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </section>
      </div>
    </div>
  );
}
