import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError, AxiosResponse } from "axios";
import {
  getPlanYears,
  getPlanYear,
  createPlanYear,
  updatePlanYear,
  deletePlanYear,
  PlanYearParams,
} from "../services/api/planYearService";
import { CreatePlanYearDto, PlanYear } from "../types/planYearTypes";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

// Query keys
const PLAN_YEAR_KEYS = {
  all: ["planYears"] as const,
  lists: () => [...PLAN_YEAR_KEYS.all, "list"] as const,
  list: (unitId: string, params?: PlanYearParams) =>
    [...PLAN_YEAR_KEYS.lists(), unitId, params] as const,
  details: () => [...PLAN_YEAR_KEYS.all, "detail"] as const,
  detail: (id: string) => [...PLAN_YEAR_KEYS.details(), id] as const,
  active: (unitId: string) =>
    [...PLAN_YEAR_KEYS.all, "active", unitId] as const,
};

// Fetch all plan years
export const usePlanYears = (unitId: string, params?: PlanYearParams) => {
  return useQuery({
    queryKey: PLAN_YEAR_KEYS.list(unitId, params),
    queryFn: () => getPlanYears(unitId, params),
    enabled: !!unitId,
    staleTime: 300_000,
    refetchOnWindowFocus: false,
  });
};
// Fetch plan year by ID or year number
export const usePlanYearById = (id: string) => {
  return useQuery({
    queryKey: PLAN_YEAR_KEYS.list(id),
    queryFn: () => getPlanYear(id),
    enabled: !!id,
    staleTime: 300_000,
    refetchOnWindowFocus: false,
  });
};

// Fetch plan year by year number (e.g., "2024")
export const usePlanYearByNumber = (unitId: string, year: string) => {
  return useQuery({
    queryKey: [...PLAN_YEAR_KEYS.all, "byYear", unitId, year],
    queryFn: async () => {
      const response = await getPlanYears(unitId, { take: 100 });
      const planYear = response.data?.items?.find(
        (py: any) => py.year.toString() === year
      );
      if (!planYear) {
        throw new Error(`Plan year ${year} not found`);
      }
      return { data: planYear };
    },
    enabled: !!unitId && !!year && /^\d{4}$/.test(year),
    staleTime: 300_000,
    refetchOnWindowFocus: false,
  });
};
// Fetch single plan year
export const usePlanYear = (id: string) => {
  return useQuery({
    queryKey: PLAN_YEAR_KEYS.detail(id),
    queryFn: () => getPlanYear(id),
    enabled: !!id,
    staleTime: 300_000,
    refetchOnWindowFocus: false,
  });
};

// Hook to resolve year parameter (supports both year number and UUID)
export const useResolvedPlanYear = (
  yearParam: string,
  unitId: string
): {
  data: any;
  isLoading: boolean;
  error: any;
  yearId: string | null;
} => {
  const isYearNumber = /^\d{4}$/.test(yearParam);

  const byNumber = usePlanYearByNumber(
    unitId,
    isYearNumber ? yearParam : ""
  );
  const byId = usePlanYearById(!isYearNumber ? yearParam : "");

  if (isYearNumber) {
    return {
      data: byNumber.data,
      isLoading: byNumber.isLoading,
      error: byNumber.error,
      yearId: byNumber.data?.data?.id || null,
    };
  }

  return {
    data: byId.data,
    isLoading: byId.isLoading,
    error: byId.error,
    yearId: yearParam,
  };
};

// Mutations
export const usePlanYearMutations = () => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  const create = useMutation<
    AxiosResponse,
    AxiosError,
    CreatePlanYearDto,
    unknown
  >({
    mutationFn: createPlanYear,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: PLAN_YEAR_KEYS.all });
      toast.success(
        t("planYear.createdSuccessfully", "Plan year created successfully")
      );
    },
    onError: (error: AxiosError) => {
      handleError(error);
    },
  });

  const update = useMutation<
    AxiosResponse,
    AxiosError,
    CreatePlanYearDto,
    unknown
  >({
    mutationFn: updatePlanYear,
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: PLAN_YEAR_KEYS.all });
      if (variables.id) {
        queryClient.invalidateQueries({
          queryKey: PLAN_YEAR_KEYS.detail(variables.id),
        });
      }
      toast.success(
        t("planYear.updatedSuccessfully", "Plan year updated successfully")
      );
    },
    onError: (error: AxiosError) => {
      handleError(error);
    },
  });

  const deleteMutation = useMutation<
    AxiosResponse,
    AxiosError,
    string,
    unknown
  >({
    mutationFn: deletePlanYear,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: PLAN_YEAR_KEYS.all });
      toast.success(
        t("planYear.deletedSuccessfully", "Plan year deleted successfully")
      );
    },
    onError: (error: AxiosError) => {
      handleError(error);
    },
  });

  return {
    create,
    update,
    delete: deleteMutation,
  };
};
