import { Loader } from "lucide-react";

import { Card, CardContent } from "@/components/ui/card";
import { useGetMembers } from "@/features/members/api/use-get-members";
import { useGetProjects } from "@/features/projects/api/use-get-projects";
import { useGetBoards } from "@/features/boards/api/use-get-boards";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { useProjectId } from "@/features/projects/hooks/use-project-id";
import { useCreateTaskModal } from "../hooks/use-create-task-modal";

import { CreateTaskForm } from "./create-task-form";

interface CreateTaskFormWrapperProps {
  onCancel: () => void;
}

export const CreateTaskFormWrapper = ({
  onCancel,
}: CreateTaskFormWrapperProps) => {
  const workspaceId = useWorkspaceId();
  const projectId = useProjectId();
  const { initialStatus } = useCreateTaskModal();

  const { data: projects, isLoading: isLoadingProjects } = useGetProjects({
    workspaceId,
  });

  const { data: members, isLoading: isLoadingMembers } = useGetMembers({
    workspaceId,
  });

  // Fetch boards for the current project if we have a projectId
  const { data: boards, isLoading: isLoadingBoards } = useGetBoards({
    projectId: projectId || "",
  });

  const projectOptions = projects?.documents.map((project) => ({
    id: project.id,
    name: project.name,
    imageUrl: project.imageUrl,
  }));

  const memberOptions = members?.documents.map((project) => ({
    id: project.id,
    name: project.name,
  }));

  const boardOptions = boards?.documents.map((board) => ({
    id: board.id,
    name: board.name,
  }));

  const isLoading = isLoadingProjects || isLoadingMembers || (projectId ? isLoadingBoards : false);

  if (isLoading) {
    return (
      <Card className="w-full h-[714px] border-none shadow-none">
        <CardContent className="flex items-center justify-center h-full">
          <Loader className="size-5 animate-spin text-muted-foreground" />
        </CardContent>
      </Card>
    );
  }

  return (
    <CreateTaskForm
      onCancel={onCancel}
      projectOptions={projectOptions ?? []}
      memberOptions={memberOptions ?? []}
      boardOptions={boardOptions ?? []}
      initialStatus={initialStatus}
    />
  );
};
