import { useMutation, useQuery } from "@tanstack/react-query";
import {
  getOrganizationReport,
  OrganizationReport,
  getOrganizationEmployees,
  getOrganizationDepartments,
  getOrganizationUnits,
} from "@/super-admin/services/api/dashboardApi";
import { useAuth } from "@/shared/context/AuthContext";
import { useState } from "react";
import { FilterEnum, getDocumentRequirements, getDocumentRequirementsByFilter, giveResponse, postDocumentRequirements } from "../services/organizationsService";
import { toast } from "sonner";
import { DocumentRequirementDto, ResponseActionDto } from "../dto/External-Portal/External-PortalDto";
import { AxiosResponse } from "axios";

type GiveResponseVariables = {
  id: string;
  data: ResponseActionDto;
};

export type RequirementDoc = {
  items: any[]; // replace `any` with your Document type
  count: number;
};


export const useOrganizationReport = (
  organizationId?: string,
  options?: { enabled?: boolean },
) => {
  const { user } = useAuth();
  const [fallbackMode, setFallbackMode] = useState(false);
  const enabled = options?.enabled ?? true;

  // Use the first employee's organizationId as the organization ID if not provided
  const orgId = organizationId || user?.employee?.[0]?.organizationId;

  // Main query to get the complete organization report
  const {
    data,
    isLoading: isMainLoading,
    isError: isMainError,
    error: mainError,
    refetch,
  } = useQuery<OrganizationReport>({
    queryKey: ["organizationReport", orgId],
    queryFn: async () => {
      if (!orgId) {
        throw new Error("Organization ID is required");
      }
      try {
        const response = await getOrganizationReport(orgId);
        return response.data;
      } catch (error) {
        // If the main endpoint fails, switch to fallback mode
        setFallbackMode(true);
        throw error;
      }
    },
    enabled: enabled && !!orgId && !fallbackMode, // Only run if we have an organization ID and not in fallback mode
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  // Fallback queries for individual data points
  const { data: employeesData, isLoading: isEmployeesLoading } = useQuery({
    queryKey: ["organizationEmployees", orgId],
    queryFn: async () => {
      if (!orgId) throw new Error("Organization ID is required");
      const { data } = await getOrganizationEmployees(orgId);
      return data.total;
    },
    enabled: enabled && !!orgId && fallbackMode,
    staleTime: 5 * 60 * 1000,
  });

  const { data: departmentsData, isLoading: isDepartmentsLoading } = useQuery({
    queryKey: ["organizationDepartments", orgId],
    queryFn: async () => {
      if (!orgId) throw new Error("Organization ID is required");
      const { data } = await getOrganizationDepartments(orgId);
      return data.total;
    },
    enabled: enabled && !!orgId && fallbackMode,
    staleTime: 5 * 60 * 1000,
  });

const {
  data: documentRequirementData,
  isLoading: isDocumentRequirementLoading,
} = useQuery({
  queryKey: ["documentRequirement"],
  queryFn: async () => {
    const response = await getDocumentRequirements();
    return {
      count: response.data.count,
      items: response.data.items,
    };
  },
  staleTime: 5 * 60 * 1000,
});



  const { data: unitsData, isLoading: isUnitsLoading } = useQuery({
    queryKey: ["organizationUnits", orgId],
    queryFn: async () => {
      if (!orgId) throw new Error("Organization ID is required");
      const { data } = await getOrganizationUnits(orgId);
      return data.total;
    },
    enabled: enabled && !!orgId && fallbackMode,
    staleTime: 5 * 60 * 1000,
  });

  // Combine data from individual queries if in fallback mode
  const fallbackData: OrganizationReport | undefined = fallbackMode
    ? {
        employeesCount: employeesData || 0,
        positionsCount: 0, // Default value since we don't have a separate endpoint
        unitsCount: unitsData || 0,
        totalDocuments: 0, // Default value since we don't have a separate endpoint
        recentActivities: [], // Default empty array since we don't have a separate endpoint
      }
    : undefined;

  // Determine if we're still loading data
  const isLoading = fallbackMode
    ? isEmployeesLoading || isDepartmentsLoading || isUnitsLoading
    : isMainLoading;

  // Use fallback data if in fallback mode, otherwise use main data
  const reportData = fallbackMode ? fallbackData : data;


  const createDocumentRequirements = async(values:DocumentRequirementDto)=>{
    try{
      const response = await postDocumentRequirements(values);
      return response.data;
      }catch(error){
        console.error(error);
        toast.error("Error in Creating Document Requirements")
    }
  }

  return {
    report: reportData,
    isLoading,
    isError: isMainError && fallbackMode,
    error: mainError,
    refetch,
    isDocumentRequirementLoading,
    documentRequirementData,
    createDocumentRequirements
  };
};


export const useGiveResponse = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<any>(null);


  const mutate = async ({ id, data }: GiveResponseVariables) => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await giveResponse(id, data);
      setData(response.data);
      return response;
    } catch (err: any) {
      const errorMessage =
        err.response?.data?.message || "An unexpected error occurred";
      setError(errorMessage);
      throw err;
    } finally {
      setIsLoading(false);
    }
  };
    const mutateDocumetary = async (values: DocumentRequirementDto) => {
      setIsLoading(true);
      setError(null);

      try {
        const response = await postDocumentRequirements(values);
        setData(response.data);
        return response;
      } catch (err: any) {
        const errorMessage =
          err.response?.data?.message || "An unexpected error occurred";
        setError(errorMessage);
        throw err;
      } finally {
        setIsLoading(false);
      }
    };

  return {
    mutate,
    isLoading,
    error,
    data,
    mutateDocumetary,
    
  };
};



export const useDocumentRequirement = (filterData?: FilterEnum) => {
  const { data, isLoading: isRequirementLoading } = useQuery<RequirementDoc>({
    queryKey: ["organizationUnits", filterData],
    queryFn: async () => {
      if (!filterData) throw new Error("User Type is required");
      const { data } = await getDocumentRequirementsByFilter(filterData);
      return {
        items: data.items as DocumentRequirementDto[],
        count: data.count,
      };
    },
    enabled: !!filterData,
    staleTime: 5 * 60 * 1000,
  });

  // always return a defined shape
  const requirementDoc: RequirementDoc = data ?? { items: [], count: 0 };
  return { requirementDoc, isRequirementLoading };
};
