import { resendVerificationCode } from "@/shared/services/authService";
import {
  assignOrganizationAdmin,
  assignUnitAdmin,
  fetchAllUnitAdminById,
  fetchUnitAdminById,
  getOrganizationAdminById,
  getOrganizationAdmins,
  OrgAdminQueryParams,
  OrganizationAdminPayload,
  UnitAdminPayload,
  updateOrganizationAdmin,
} from "@/super-admin/services/api/organizationAdminService";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

// Resend verification code API call
const resendVerificationCodeToAdmin = async ({
  organizationId,
  email,
  phoneNumber,
}: {
  organizationId: string;
  email: string;
  phoneNumber: string;
}) => {
  const response = await fetch("/api/resend-verification-code", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ organizationId, email, phoneNumber }),
  });

  if (!response.ok) {
    throw new Error("Failed to resend verification code");
  }

  return response.json();
};

export const useOrganizationAdmins = (params?: OrgAdminQueryParams) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // Get all admins
  const {
    data: adminsResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["organizationAdmins", params],
    queryFn: async () => {
      const { data } = await getOrganizationAdmins(params);
      return {
        count: data,
        items: data,
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
    enabled: false,
  });

  // Create admin
  const { mutate: createAdminMutation, isPending: isCreating } = useMutation({
    mutationFn: async ({
      payload,
      successCallback,
    }: {
      payload: OrganizationAdminPayload;
      successCallback: () => void;
    }) => assignOrganizationAdmin(payload),
    onSuccess: (_data, variables) => {
      toast.success("Admin assigned successfully");
      queryClient.invalidateQueries({ queryKey: ["organizationAdmins"] });
      variables.successCallback();
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const { mutate: createUnitAdminMutation, isPending: isUnitCreating } = useMutation({
    mutationFn: async ({
      payload,
      successCallback,
    }: {
      payload: UnitAdminPayload;
      successCallback: () => void;
    }) => assignUnitAdmin(payload),
    onSuccess: (_data, variables) => {
      toast.success("Admin assigned successfully");
      queryClient.invalidateQueries({ queryKey: ["organizationAdmins"] });
      variables.successCallback();
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Update admin
  const { mutate: updateAdminMutation, isPending: isUpdating } = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: string;
      data: OrganizationAdminPayload;
    }) => updateOrganizationAdmin(id, data),
    onSuccess: () => {
      toast.success("Admin updated successfully");
      queryClient.invalidateQueries({ queryKey: ["organizationAdmins"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // Get admin by ID
  const getAdminById = async (id: string) => {
    try {
      return await getOrganizationAdminById(id);
    } catch (error) {
      toast.error("Failed to fetch admin details");
      return undefined;
    }
  };
   const getUnitAdminById = async (id: string) => {
     try {
       return await fetchUnitAdminById(id);
     } catch (error) {
       toast.error("Failed to fetch unit admin details");
       return undefined;
     }
   };

   const getAllAdminById = async (id: string, params?: OrgAdminQueryParams) => {
     try {
       return await fetchAllUnitAdminById(id, params);
     } catch (error) {
       toast.error("Failed to fetch all admin details");
       return undefined;
     }
   };

  // Resend invitation (verification code)
  const resendInvitation = async ({
    email,
    phoneNumber,
  }: {
    email: string;
    phoneNumber: string;
  }) => {
    try {
      await resendVerificationCode({
        email,
        phoneNumber,
      });
    } catch (error) {
      console.error("Failed to resend verification code:", error);
      throw error;
    }
  };

  return {
    adminsResponse,
    createAdmin: createAdminMutation,
    createUnitAdmin:createUnitAdminMutation,
    updateAdmin: updateAdminMutation,
    getAdminById,
    getUnitAdminById,
    resendInvitation, 
    getAllAdminById,// 👈 important to expose this
    isCreating,
    isUpdating,
    isLoading,
    isError,
    refetch,
  };
};
