import type { Metadata } from "next";
import Link from "next/link";
import { getAllHomeSectionsForAdmin, HOME_SECTION_LABELS } from "@/lib/home-sections/queries";
import { toggleHomeSectionActive, reorderHomeSections } from "@/lib/admin/home-section-actions";
import { SortableList } from "@/components/admin/SortableList";

export const metadata: Metadata = {
  title: "Ana Sayfa Düzeni",
};

export default async function AdminHomeSectionsPage() {
  const sections = await getAllHomeSectionsForAdmin();

  return (
    <div className="p-8">
      <div className="mb-6 border-b border-border pb-6">
        <h1 className="text-[22px]">Ana Sayfa Düzeni</h1>
        <p className="mt-0.5 text-[12.5px] text-text-muted">
          Ana sayfadaki bölümleri sürükleyerek sıralayın, göstermek istemediklerinizi gizleyin. Değişiklikler anında{" "}
          <Link href="/" target="_blank" className="font-semibold text-accent">
            ana sayfaya
          </Link>{" "}
          yansır.
        </p>
      </div>

      <div className="max-w-xl">
        <p className="mb-3 rounded-xl border border-dashed border-border bg-bg-alt p-3 text-[12.5px] text-text-muted">
          Üst bölüm (hero/başlık alanı) ve en alttaki üyelik çağrısı sabittir, bu listeye dahil değildir — aralarındaki
          içerik bölümlerini burada yönetebilirsiniz.
        </p>

        <SortableList
          key={sections.map((s) => s.id).join(",")}
          items={sections.map((section) => {
            const toggle = toggleHomeSectionActive.bind(null, section.id);
            return {
              id: section.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">{HOME_SECTION_LABELS[section.key]}</span>
                    <span
                      className={`rounded-full px-2 py-0.5 text-[10.5px] font-semibold ${
                        section.isActive ? "bg-green-100 text-green-700" : "bg-accent/10 text-accent"
                      }`}
                    >
                      {section.isActive ? "Aktif" : "Pasif"}
                    </span>
                  </div>
                  <form action={toggle}>
                    <button className="rounded-md px-2 py-1 text-[11px] font-semibold text-text-muted hover:bg-bg-alt">
                      {section.isActive ? "Gizle" : "Göster"}
                    </button>
                  </form>
                </div>
              ),
            };
          })}
          onReorder={reorderHomeSections}
        />
      </div>
    </div>
  );
}
