import Link from "next/link";

import { PlaceholderActions, ShellPage } from "@/components/page-templates";
import { TablePlaceholder, TeamSummaryCards } from "@/components/placeholders";
import { getTeamData } from "@/lib/platform-data";
import { deleteTeamUser } from "@/lib/admin-crud";

export default async function TeamPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const users = await getTeamData();
  const error = params.error;
  const infoMessage = error === "user_not_found"
    ? "User tidak ditemukan."
    : error === "user_has_campaigns"
      ? "User tidak bisa dihapus karena pernah membuat campaign."
    : error === "self_delete_not_allowed"
      ? "Tidak bisa menghapus akun sendiri."
      : error === "invalid_role"
        ? "Role tidak valid."
        : error === "missing_fields"
          ? "Pastikan semua kolom wajib terisi."
          : null;

  return (
    <ShellPage
      shell="admin"
      title="Team / Users"
      description="Kelola admin client dan agent di tenant."
      actions={<PlaceholderActions primaryHref="/team/new" primaryLabel="Create user" secondaryHref="/team/performance" secondaryLabel="Team performance" />}
    >
      <TeamSummaryCards users={users} />
      {infoMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{infoMessage}</p> : null}
      <TablePlaceholder
        title="Users list"
        columns={["Name", "Email", "Role", "Status", "Last login", "Actions"]}
        rows={users.map((user) => [
          user.fullName,
          user.email,
          user.role,
          user.status,
          user.lastLogin,
          <div key={user.id} className="flex gap-2">
            <Link href={`/team/${user.id}`} className="text-brand hover:underline">
              Detail
            </Link>
            <Link href={`/team/${user.id}/edit`} className="text-brand hover:underline">
              Edit
            </Link>
            <form action={deleteTeamUser} className="inline">
              <input type="hidden" name="userId" value={user.id} />
              <button type="submit" className="text-danger hover:underline">
                Delete
              </button>
            </form>
          </div>
        ])}
      />
    </ShellPage>
  );
}
