import { RecordPayload } from "@/record-management/dto/userRecords/userRecordsDto";
import {
  fetchMyRecords,
  createRecord,
  updateRecord,
  deleteRecord,
  softDeleteRecord,
  getAttachmentsById,
  getSealedAttachmentsById,
  deleteAttachmentsById,
  makeSecureRecord,
  unMakeSecureRecord,
  makeUrgentRecord,
  unMakeUrgentRecord,
  fetchMyRecordsParent,
  directSubmitRecord,
  directDispatchRecord,
  forceDispatchCollaboratorRecord,
  forceDispatchCollaboratorInternalMemoRecord,
  canSkipLevelUp,
} from "@/record-management/services/api/userRecordService";

import {
  InitiationType,
  KeyValue,
} from "@/record-management/types/recordSelectTypes";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useEffect, useRef } from "react";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

interface RecordQueryParams {
  skip?: number;
  take?: number;
  status?: string;
  subject?: string;
  to?: string;
  receiverPosition?: string;
  referenceNumber?: string;
  fromCreatedAt?: string;
  toCreatedAt?: string;
  fetchParent?: boolean;
}

// ✅ Translated initiation type options
export const useInitiationTypeOptions = (): KeyValue[] => {
  const { t } = useTranslation();

  return [
    {
      label: t("initiationType.self", "Self (በራስ)"),
      value: InitiationType.Self,
      employeePositionId: "",
    },
    {
      label: t("initiationType.team", "Team (በቡድን)"),
      value: InitiationType.Team,
      employeePositionId: "",
    },
  ];
};

export const useCanJumpOnStepUp = () =>
  useQuery({
    queryKey: ["canJumpOnStepUp"],
    queryFn: async () => {
      const data = await canSkipLevelUp();
      return data.canSkipLevel === true;
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

export const useUserRecords = (params?: RecordQueryParams) => {
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  // -------------------- Fetch Records --------------------
  const {
    data: recordsResponse,
    isLoading,
    isError,
    error: recordsError,
    refetch,
  } = useQuery({
    queryKey: ["userRecords", params],
    queryFn: async () => {
      const data = await fetchMyRecords(params);
      return {
        count: data.count,
        items: data.items,
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });
  const {
    data: dataParent,
    isLoading: isLoadingParent,
    isError: isErrorParent,
    error: parentError,
    refetch: refetchParent,
  } = useQuery({
    queryKey: ["userRecords-parent", params],
    queryFn: () => fetchMyRecordsParent(params?.fetchParent ? params : {}),
    staleTime: 5 * 60 * 1000,
    enabled: Boolean(params?.fetchParent),
    retry: false,
  });

  // Surface list-fetch failures via the centralized error handler.
  // Inline `isError` UI is preserved by callers; this just adds a toast.
  const listFetchError = recordsError || parentError;
  const prevListErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (listFetchError && listFetchError !== prevListErrorRef.current) {
      prevListErrorRef.current = listFetchError;
      handleError(listFetchError);
    }
  }, [listFetchError, handleError]);
  // -------------------- Create Record --------------------
  const addMutation = useMutation({
    mutationFn: (payload: RecordPayload) => createRecord(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // -------------------- Edit Record --------------------
  const editMutation = useMutation({
    mutationFn: ({
      id,
      updatedRecord,
    }: {
      id: string;
      updatedRecord: RecordPayload;
    }) => updateRecord(id, updatedRecord),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  // -------------------- Delete Record --------------------
  const deleteMutation = useMutation({
    mutationFn: (id: string) => deleteRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  //-------------------------direct submit record -----------
  const directSubmitMutation = useMutation({
    mutationFn: ({
      recordId,
      signatureId,
    }: {
      recordId: string;
      signatureId: string;
    }) => directSubmitRecord({ recordId, signatureId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const directDispatchMutation = useMutation({
    mutationFn: ({
      recordId,
      signatureId,
    }: {
      recordId: string;
      signatureId: string;
    }) => directDispatchRecord({ recordId, signatureId }),
    onSuccess: () => {
      toast.success(t("userRecord.directDispatchSuccess"));
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const forceDispatchCollaboratorMutation = useMutation({
    mutationFn: ({ recordId, type }: { recordId: string; type?: string }) =>
      type === "other"
        ? forceDispatchCollaboratorInternalMemoRecord(recordId)
        : forceDispatchCollaboratorRecord(recordId),
    onSuccess: () => {
      toast.success(
        t("userRecord.forceDispatchSuccess", "Record dispatched successfully"),
      );
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const useAttachmentById = (selectedId: string | null) =>
    useQuery({
      queryKey: ["record-attachment", selectedId],
      queryFn: async () => {
        try {
          return await getAttachmentsById(selectedId ?? "");
        } catch {
          return await getSealedAttachmentsById(selectedId ?? "");
        }
      },
      enabled: !!selectedId,
      staleTime: 1000 * 60 * 5,
    });
  //-------------------Soft Delete --------------------------
  const softDeleteMutation = useMutation({
    mutationFn: (id: string) => softDeleteRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  // -------------------- Delete Attachment --------------------
  const deleteAttachmentMutation = useMutation({
    mutationFn: (recordId: string) => deleteAttachmentsById(recordId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  //---------------- Make Secure Record ----------------
  const makeSecureMutation = useMutation({
    mutationFn: ({ id }: { id: string }) => makeSecureRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const unMakeSecureMutation = useMutation({
    mutationFn: ({ id }: { id: string }) => unMakeSecureRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  const markUrgentRecordMutation = useMutation({
    mutationFn: ({ id }: { id: string }) => makeUrgentRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });

  const unMarkUrgentRecordMutation = useMutation({
    mutationFn: ({ id }: { id: string }) => unMakeUrgentRecord(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["userRecords"] });
      queryClient.invalidateQueries({ queryKey: ["record"] });
    },
    onError: (error) => {
      handleError(error);
    },
  });
  return {
    useAttachmentById,
    recordsResponse,
    isLoading,
    isError,
    refetch,
    ...(params?.fetchParent
      ? {
          recordParent: dataParent?.items ?? [],
          recordParentCount: dataParent?.count ?? 0,
          refetchParent,
          isErrorParent,
          isLoadingParent,
        }
      : {}),

    // CRUD
    addRecord: addMutation.mutateAsync,
    editRecord: editMutation.mutateAsync,
    deleteRecord: deleteMutation.mutate,
    deleteRecordAsync: deleteMutation.mutateAsync,
    softDeleteRecord: softDeleteMutation.mutate,
    makeSecureRecord: makeSecureMutation.mutate,
    unMakeSecureRecord: unMakeSecureMutation.mutate,
    markUrgentRecord: markUrgentRecordMutation.mutate,
    unMarkUrgentRecord: unMarkUrgentRecordMutation.mutate,
    directlySubmit: directSubmitMutation.mutateAsync,
    // Mutation States
    isAdding: addMutation.isPending,
    isEditing: editMutation.isPending,
    isDeleting: deleteMutation.isPending,

    addStatus: addMutation.status,
    editStatus: editMutation.status,
    deleteStatus: deleteMutation.status,

    addRecordData: addMutation.data,
    addRecordSuccess: addMutation.isSuccess,
    deleteAttachment: deleteAttachmentMutation.mutateAsync,
    isDeleteingAttachment: deleteAttachmentMutation.isPending,
    directDispatch: directDispatchMutation.mutateAsync,
    isDirectDispatching: directDispatchMutation.isPending,
    forceDispatchCollaborator: forceDispatchCollaboratorMutation.mutateAsync,
    isForceDispatchingCollaborator: forceDispatchCollaboratorMutation.isPending,
  };
};
