import { redirect } from "next/navigation";
import {
  createTeamMemberAction,
  deleteTeamMemberAction,
} 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 { listDashboardTeam } from "@/services/team-service";

export default async function DashboardTeamPage() {
  const ctx = await requireDashboardContext("settings:manage");
  const rows = await listDashboardTeam(ctx.tenant);

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

  return (
    <DashboardShell>
      <DashboardPageHeader
        eyebrow="Studio"
        title="Team"
        description="People shown on the public team pages."
      />
      <form action={createAction} className="archi-panel mt-10 grid gap-3 p-5 sm:grid-cols-2">
        <label className="block text-sm">
          Name
          <input name="name" required className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Role
          <input name="role" placeholder="Principal Architect" className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Slug (optional)
          <input name="slug" className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Email
          <input name="email" type="email" className="archi-input mt-2" />
        </label>
        <label className="block text-sm sm:col-span-2">
          Bio
          <textarea name="bio" rows={3} className="archi-input mt-2" />
        </label>
        <button type="submit" className="archi-btn-primary sm:col-span-2 sm:w-fit">
          Add member
        </button>
      </form>
      <ul className="archi-panel mt-8 divide-y divide-[var(--archi-line)]">
        {rows.length === 0 ? (
          <li className="px-4 py-8 text-sm text-[var(--archi-ink-muted)]">
            No team members yet.
          </li>
        ) : (
          rows.map((row) => (
            <li key={row.id} className="flex flex-wrap items-center justify-between gap-3 px-4 py-4">
              <div>
                <p className="font-medium">{row.name}</p>
                <p className="text-xs text-[var(--archi-ink-muted)]">
                  {[row.role, `/${row.slug}`].filter(Boolean).join(" · ")}
                </p>
              </div>
              <form action={deleteTeamMemberAction.bind(null, row.id)}>
                <button type="submit" className="text-xs text-red-800 underline">
                  Delete
                </button>
              </form>
            </li>
          ))
        )}
      </ul>
    </DashboardShell>
  );
}
