import { redirect } from "next/navigation";
import {
  createCategoryAction,
  deleteCategoryAction,
  updateCategoryAction,
} from "@/app/dashboard/actions";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import { listCategories } from "@/services/category-service";

export default async function DashboardCategoriesPage() {
  const ctx = await requireDashboardContext("projects:edit");
  const categories = await listCategories(ctx.tenant);

  async function createAction(formData: FormData) {
    "use server";
    const result = await createCategoryAction(formData);
    if (!result.ok) {
      redirect("/dashboard/categories?error=1");
    }
    redirect("/dashboard/categories");
  }

  return (
    <DashboardShell>
      <DashboardPageHeader
        eyebrow="Projects"
        title="Categories"
        description="Organize portfolio projects. Assign categories on project create and edit."
      />

      <form
        action={createAction}
        className="mt-10 grid max-w-3xl gap-3 rounded-2xl border border-[var(--archi-line)] bg-white/70 p-5 sm:grid-cols-[1fr_1fr_auto]"
      >
        <label className="block text-sm sm:col-span-1">
          Name
          <input
            name="name"
            required
            className="archi-input mt-2"
          />
        </label>
        <label className="block text-sm">
          Slug (optional)
          <input
            name="slug"
            className="archi-input mt-2"
          />
        </label>
        <div className="flex items-end">
          <button
            type="submit"
            className="w-full bg-[var(--archi-ink)] px-4 py-2 text-sm text-[var(--archi-bg)] sm:w-auto"
          >
            Add
          </button>
        </div>
        <label className="block text-sm sm:col-span-3">
          Description
          <input
            name="description"
            className="archi-input mt-2"
          />
        </label>
        <label className="block text-sm sm:col-span-1">
          Sort order
          <input
            name="sortOrder"
            type="number"
            defaultValue={0}
            className="archi-input mt-2"
          />
        </label>
      </form>

      <ul className="mt-10 max-w-3xl divide-y divide-[var(--archi-line)] border border-[var(--archi-line)]">
        {categories.length === 0 ? (
          <li className="px-4 py-8 text-sm text-[var(--archi-ink-muted)]">
            No categories yet.
          </li>
        ) : (
          categories.map((category) => (
            <CategoryRow key={category.id} category={category} />
          ))
        )}
      </ul>
    </DashboardShell>
  );
}

function CategoryRow({
  category,
}: {
  category: {
    id: string;
    name: string;
    slug: string;
    description: string | null;
    sortOrder: number;
  };
}) {
  async function saveAction(formData: FormData) {
    "use server";
    const result = await updateCategoryAction(category.id, formData);
    if (!result.ok) {
      redirect("/dashboard/categories?error=1");
    }
    redirect("/dashboard/categories");
  }

  async function removeAction() {
    "use server";
    await deleteCategoryAction(category.id);
    redirect("/dashboard/categories");
  }

  return (
    <li className="space-y-3 px-4 py-4">
      <form
        action={saveAction}
        className="grid gap-3 sm:grid-cols-[1fr_1fr_auto]"
      >
        <input
          name="name"
          defaultValue={category.name}
          required
          className="border border-[var(--archi-line)] bg-white px-3 py-2 text-sm"
        />
        <input
          name="slug"
          defaultValue={category.slug}
          className="border border-[var(--archi-line)] bg-white px-3 py-2 text-sm"
        />
        <button type="submit" className="text-sm underline">
          Save
        </button>
        <input
          name="description"
          defaultValue={category.description ?? ""}
          placeholder="Description"
          className="border border-[var(--archi-line)] bg-white px-3 py-2 text-sm sm:col-span-2"
        />
        <input
          name="sortOrder"
          type="number"
          defaultValue={category.sortOrder}
          className="border border-[var(--archi-line)] bg-white px-3 py-2 text-sm"
        />
      </form>
      <form action={removeAction}>
        <button type="submit" className="text-xs text-red-800 underline">
          Delete
        </button>
      </form>
    </li>
  );
}
