"use client";

import { useEffect } from "react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

import { useGetCurrentMember } from "@/features/members/api/use-get-current-member";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { MembersList } from "@/features/members/components/members-list";
import { MemberRole } from "@/features/members/types";
import { PageLoader } from "@/components/page-loader";

export const MembersPageClient = () => {
  const workspaceId = useWorkspaceId();
  const router = useRouter();
  const { data: currentMember, isLoading } = useGetCurrentMember({ workspaceId });

  useEffect(() => {
    if (!isLoading && currentMember && currentMember.role !== MemberRole.ADMIN) {
      toast.error("Not authorized", {
        description: "You don't have permission to access the members page. Only administrators can manage members.",
      });
      router.push(`/workspaces/${workspaceId}`);
    }
  }, [currentMember, isLoading, router, workspaceId]);

  if (isLoading) {
    return <PageLoader />;
  }

  if (!currentMember || currentMember.role !== MemberRole.ADMIN) {
    return null; // Will redirect via useEffect
  }

  return <MembersList />;
}; 