import {
  IProject,
  Participants,
  Project,
  collaborator,
} from "@/contexts/types/Project";
import axios, {
  axiosInstance1,
  endpoints,
  fetcher1,
  fetcher2,
  axiosInstance,
} from "@/utils/axios";
import { useMemo } from "react";
import useSWR, { mutate } from "swr";
import { _Participants } from "../_mock";

const options = {
  revalidateIfStale: false,
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
};

export async function createProject(projectData: IProject) {
  const URL = endpoints.project.add;
  try {
    const createdProject = await axiosInstance1.post(URL, projectData);
    mutate(
      [endpoints.project.list],
      (projects: Project[] = []) => [...projects, createdProject.data],
      true
    );
    return createdProject.data;
  } catch (error) {
    console.error("Update project error:", error);
    throw error;
  }
}

export function useGetProjects() {
  const URL = [endpoints.project.list];

  const { data, isLoading, error, isValidating } = useSWR<Project[]>(
    URL,
    fetcher1,
    options
  );

  const memoizedValue = useMemo(
    () => ({
      projects: data || [],
      projectsLoading: isLoading,
      projectsError: error,
      projectValidating: isValidating,
      projectsEmpty: !isLoading && !data?.length,
    }),
    [data, error, isLoading, isValidating, mutate]
  );

  return memoizedValue;
}
export async function archiveProject(projectId: number) {
  try {
    const response = await axiosInstance1.post(
      `${endpoints.project.archive}/${projectId}`
    );
    const Data = await response.data;
    mutate([endpoints.project.list]);
    return Data;
  } catch (error) {
    console.error("Error archiving project:", error);
    throw error;
  }
}

export async function deleteProject(projectId: number) {
  try {
    const response = await axiosInstance1.delete(
      `${endpoints.project.delete}/${projectId}`
    );
    const newData = await response.data;
    mutate(endpoints.project.list);
    return newData;
  } catch (error) {
    console.error(" delete project Error:", error);
    throw error;
  }
}
export async function favoriteProject(projectId: number) {
  try {
    const response = await axiosInstance1.put(
      `${endpoints.project.favorit}/${projectId}`
    );
    const newData = await response.data;
    mutate(endpoints.project.list);
    return newData;
  } catch (error) {
    console.error("Favorite project error:", error);
    throw error;
  }
}
export async function recoverProject(projectId: number) {
  try {
    const response = await axiosInstance1.put(
      `${endpoints.project.recover}/${projectId}`
    );
    const newData = await response.data;
    mutate(endpoints.project.list);
    return newData;
  } catch (error) {
    console.error("Recorve project error:", error);
    throw error;
  }
}
export async function unfavoriteProject(projectId: number) {
  try {
    const response = await axiosInstance1.put(
      `${endpoints.project.unfavorit}/${projectId}`
    );
    const newData = await response.data;
    mutate(
      endpoints.project.list
      // Mise à jour optimiste sans refetch
    );
    return newData;
  } catch (error) {
    console.error("Unfavorite project error:", error);
    throw error;
  }
}
export function useGetProject(projectId: number) {
  const URL = `${endpoints.project.get}/${projectId}`;
  const { data, isLoading, error } = useSWR<Project>(URL, fetcher1);

  return {
    ProjectData: data as Project,
    projectIsLoading: isLoading,
    projectError: error,
  };
}
export async function updateProject(projectId: number, project: IProject) {
  try {
    const updatedProject = await axiosInstance1.put(
      `${endpoints.project.update}/${projectId}`,
      project
    );
    mutate(
      [endpoints.project.list],
      (projects: Project[] = []) => {
        const index = projects.findIndex((project) => project.id === projectId);
        if (index > -1) {
          projects[index] = updatedProject.data;
        }
        return [...projects];
      },
      true
    );
    return updatedProject.data;
  } catch (error) {
    console.error("Update project error:", error);
    throw error;
  }
}
export async function deleteListProject(projectIds: number[]) {
  try {
    const deletePromises = projectIds.map(async (projectId) => {
      await deleteProject(projectId);
    });

    await Promise.all(deletePromises);

    // Mettre à jour la liste des projets après suppression
    mutate(endpoints.project.list);

    return deletePromises;
  } catch (error) {
    console.error("Erreur lors de la suppression des projets:", error);
    throw error;
  }
}
export async function archiveListProject(projectIds: number[]) {
  try {
    const archivePromises = projectIds.map(async (projectId) => {
      await archiveProject(projectId);
    });

    await Promise.all(archivePromises);

    // Mettre à jour la liste des projets après suppression
    mutate(endpoints.project.list);
    return archivePromises;
  } catch (error) {
    console.error("Erreur lors archivage des projets:", error);
    throw error;
  }
}
export async function recoverListProject(projectIds: number[]) {
  try {
    const recoverPromises = projectIds.map(async (projectId) => {
      await recoverProject(projectId);
    });
    await Promise.all(recoverPromises);
    // Mettre à jour la liste des projets après suppression
    mutate(endpoints.project.list);
    return recoverPromises;
  } catch (error) {
    console.error("Erreur lors du désarchivage des projets ", error);
    throw error;
  }
}
export async function unfavoritListProject(projectIds: number[]) {
  try {
    const unfavoritPromises = projectIds.map(async (projectId) => {
      await unfavoriteProject(projectId);
    });
    await Promise.all(unfavoritPromises);
    // Mettre à jour la liste des projets après suppression
    mutate(endpoints.project.list);
    return unfavoritPromises;
  } catch (error) {
    console.error("Erreur lors du défavorisage des projets :", error);
    throw error;
  }
}
export function useGetCollaborators() {
  // Will be extracted from the token later
  const agencyId = 1;
  const URL = `${endpoints.collaborator.list}/${agencyId}`;

  const { data, isLoading, error, isValidating } = useSWR<collaborator[]>(
    [URL],
    fetcher2
  );

  const memoizedValue = useMemo(
    () => ({
      collaborators: (data as collaborator[]) || [],
      collaboratorsLoading: isLoading,
      collaboratorsError: error,
      collaboratorsValidating: isValidating,
      collaboratorsEmpty: !isLoading && !data?.length,
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}
export async function addcollaborator(
  projectId: number,
  collaboratorId: number
) {
  try {
    const agencyId = 1;
    const response = await axiosInstance.post(
      `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/collaborators/${projectId}/${collaboratorId}`
    );

    return response;
  } catch (error) {
    console.error("Add collaborator error:", error);
    throw error;
  }
}
export function useGetTasksOfProject(projectId: number) {
  const URL = `${endpoints.project.tasks}/${projectId}`;

  const { data, isLoading, error, isValidating } = useSWR(URL, fetcher1);

  const memoizedValue = useMemo(
    () => ({
      tasks: data || [],
      tasksLoading: isLoading,
      tasksError: error,
      tasksValidating: isValidating,
      tasksEmpty: !isLoading && !data?.length,
    }),
    [data, error, isLoading, isValidating]
  );
  console.log("data: ", data);
  return memoizedValue;
}



export async function getProjectOverviewStats(projectId: number) {
  const response = await axiosInstance.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/statistics/overview`, {
    params: { projectId },
  });
  return response.data;
}

export async function getTaskDistributionStats(projectId: number) {
  const response = await axiosInstance.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/statistics/task-distribution`, {
    params: { projectId }
  });
  console.log('API Response:', response.data);
  return response.data;
}

export async function getTeamWorkloadStats(projectId: number) {
  const response = await axiosInstance.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/team-workload/${projectId}`);
  return response.data;
}
export async function getTaskStatusDistribution(projectId: number) {
  const response = await axiosInstance.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/tasks/status-distribution`, {
    params: { projectId }
  });
  return response.data;
}

export async function getTaskProgressStats(
  projectId: number, 
  taskType?: string | null
) {
  const response = await axiosInstance.get(`${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/statistics/task-progress`, {
    params: { 
      projectId,
      taskType
    }
  });
  return response.data;
}