import { useEffect, useState } from "react";
import { TasksRepository } from "../repositories/TaskRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import { MasterRespository } from "../repositories/MastersRepository";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import { useSelector } from "react-redux";

// ---------Query---------------------------------

export const useTaskList = (projectId, dateFrom, toDate) => {
  const enabled = !!projectId && !!dateFrom && !!toDate;

  const {
    data: TaskList = [],
    isLoading: loading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["taskList", projectId, dateFrom, toDate],
    queryFn: async () => {
      const response = await TasksRepository.getTaskList(
        projectId,
        dateFrom,
        toDate
      );
      return response.data;
    },
    enabled,
  });

  return { TaskList, loading, error, refetch };
};

export const useTaskById = (TaskId) => {
  const {
    data: Task = null,
    isLoading: loading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["taskDetails", TaskId],
    queryFn: async () => {
      const res = await TasksRepository.getTaskById(TaskId);
      return res.data;
    },
    enabled: !!TaskId,
  });

  return { Task, loading, error, refetch };
};

// export const useActivities = () => {
//   return useQuery({
//     queryKey: ["activitiesMaster"],
//     queryFn: async () => {
//       const response = await ActivityRepository.getActivities();
//       return response.data;
//     },

//   });
// };

export const useAuditStatus = () => {
  const {
    data: status = [],
    isLoading: loading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["AuditStatus"],
    queryFn: async () => {
      const res = await MasterRespository.getAuditStatus();
      return res.data;
    },
  });

  return { status, loading, error, refetch };
};

// -----------------------Mutation------------------------
const toDate = new Date().toISOString().split("T")[0];
const dateFrom = new Date(Date.now() - 6 * 24 * 60 * 60 * 1000)
  .toISOString()
  .split("T")[0];

export const useReportTask = ({ onSuccessCallback, onErrorCallback } = {}) => {
  const queryClient = useQueryClient();
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const { mutate, isPending, isSuccess, isError, error } = useMutation({
    mutationFn: async ({ reportData, workAreaId }) => {
      return await TasksRepository.reportTask(reportData);
    },
    onSuccess: (data, variables) => {
      const { workAreaId, buildingId, floorId } = variables;
      queryClient.invalidateQueries({ queryKey: ["taskList"] });
      queryClient.invalidateQueries({ queryKey: ["WorkItems", workAreaId] });
      queryClient.setQueryData(["ProjectInfra", selectedProject], (oldData) => {
        if (!oldData) return oldData;
        const { workAreaId, floorId, buildingId } = variables;
        const updatedData = JSON.parse(JSON.stringify(oldData));

        return updatedData.map((building) => {
          if (building.id !== buildingId) return building;
          return {
            ...building,
            floors: building.floors.map((floor) => {
              if (floor.id !== floorId) return floor;

              return {
                ...floor,
                workAreas: floor.workAreas.map((area) => {
                  if (area.id !== workAreaId) return area;
                  return {
                    ...area,
                    completedWork:
                      (area.completedWork ?? 0) +
                      (data?.data?.completedTask ?? 0),
                  };
                }),
              };
            }),
          };
        });
      });
      queryClient.setQueryData(["ProjectsList"], (projects) => {
        if (!projects) return projects;
        const updatedProject = JSON.parse(JSON.stringify(projects));
        return updatedProject.map((project) => {
          if (project.id !== selectedProject) return project;

          return {
            ...project,
            completedWork:
              (project.completedWork ?? 0) + (data?.data?.completedTask ?? 0),
          };
        });
      });
      showToast("Task Reported Successfully.", "success");
      if (onSuccessCallback) onSuccessCallback(data);
    },
    onError: (error) => {
      const msg =
        error?.response?.data?.message ||
        error.message ||
        "Error occurred during API call";
      showToast(msg, "error");
    },
  });

  return {
    mutate,
    isPending,
    isSuccess,
    isError,
    error,
  };
};

export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
  const queryClient = useQueryClient();
  const { mutate, isPending } = useMutation({
    mutationFn: async ({ data, commentsData }) => {
      const payload = {
        ...data,
        [actionAllow ? "id" : "taskAllocationId"]: commentsData?.id,
        ...(actionAllow ? {} : { commentDate: new Date().toISOString() }),
      };

      const response = actionAllow
        ? await TasksRepository.auditTask(payload)
        : await TasksRepository.taskComments(payload);

      return response.data;
    },

    onSuccess: (data, variables) => {
      const workAreaId = variables?.commentsData?.workItem?.workArea?.id;
      queryClient.invalidateQueries({ queryKey: ["taskList"] });
      if (actionAllow) {
        showToast("Review submitted successfully.", "success");
      } else {
        showToast("Comment sent successfully.", "success");
      }

      onSuccessCallback?.(data);
    },

    onError: (error) => {
      const msg =
        error?.response?.data?.message ||
        error.message ||
        "Error during API call";
      showToast(msg, "error");
    },
  });

  return { submitComment: mutate, isPending };
};

export const useCreateTask = ({ onSuccessCallback, onErrorCallback } = {}) => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ payload, workAreaId }) => {
      return await TasksRepository.assignTask(payload);
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ["taskList"] });
      queryClient.invalidateQueries({
        queryKey: ["WorkItems", variables?.workAreaId],
      });
      showToast("Task Assigned Successfully.", "success");
      if (onSuccessCallback) onSuccessCallback(variables);
    },
    onError: (error) => {
      showToast("Something went wrong. Please try again.", "error");
      if (onErrorCallback) onErrorCallback(error);
    },
  });
};
