import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import Cookies from "js-cookie";
import { AxiosResponse } from "axios";
import {
  AdjustmentDto,
  SendBackDto,
} from "@/record-management/dto/userRecords/userRecordsDto";
import { withHeaders } from "./withHeaders";
import { ProcessedApprovalRecordsResponseDto } from "@/record-management/dto/approval/newApprovalRecordsDto";

export interface ApprovalRecordQueryParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  action?: string;
  isUrgent?: boolean;
  canApprove?: boolean;
  onReview?: boolean;
  receiverEmployee?: string;
  receiverPosition?: string;
  subject?: string;
  letterName?: string;
  sendingPosition?: string;
  fromUpdatedAt?: string;
  toUpdatedAt?: string;
  fromCreatedAt?: string;
  toCreatedAt?: string;
}

export const getApiErrorMessage = (
  error: any,
  fallback = "Something went wrong.",
) => {
  if (error.response) {
    const data = error.response.data;
    if (data.exception?.message) return data.exception.message;
    if (data.message) return data.message;
    return error.response.statusText;
  } else if (error.request) {
    return "No response received from server.";
  } else {
    return error.message || fallback;
  }
};

export const handleAxiosError = (
  error: any,
  defaultMessage = "An unknown error occurred.",
) => {
  if (error.response) {
    const contentType = error.response.headers["content-type"];
    const data = error.response.data;

    if (contentType?.includes("application/json")) {
      // Prefer the most specific error message if available
      if (data.exception?.message) return data.exception.message;
      if (data.message) return data.message;
      return error.response.statusText;
    } else if (contentType?.includes("text/plain")) {
      return data || error.response.statusText;
    } else {
      return error.response.statusText;
    }
  } else if (error.request) {
    return "No response received from server.";
  } else {
    return error.message || defaultMessage;
  }
};

export const fetchApprovalTasks = async (
  params?: ApprovalRecordQueryParams,
): Promise<any> => {
  try {
    const response = await recordAxiosInstance.get(
      `/outgoing-instances/my-workflows`,
      {
        params: {
          take: 10,
          ...params,
        },
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    console.error("Error fetching approval tasks:", error);
    throw error;
  }
};

export const sendBack = async (body: SendBackDto): Promise<AxiosResponse> => {
  try {
    const response = await recordAxiosInstance.post(
      `/outgoing-instances/go-to-next`,
      body, // this is the POST body
      {
        headers: withHeaders(), // this is the Axios config (3rd argument)
      },
    );
    return response;
  } catch (error) {
    console.error("Error sending back:", error);
    throw error;
  }
};

export const goToNext = async (body: AdjustmentDto): Promise<void> => {
  try {
    const response = await recordAxiosInstance.post(
      `/outgoing-instances/go-to-next`,
      body, // send body as payload
      {
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    console.error("[approvalService.goToNext]", error);
    throw error;
  }
};

export const sendToRO = async (
  recordId: string,
  stampId?: string,
  signatureId?: string,
  note?: string,
  recordPrefixId?: string,
  isWithTeamSignature?: boolean,
): Promise<void> => {
  try {
    const response = await recordAxiosInstance.patch(
      `/outgoing-instances/send-to-ro/${recordId}`,
      {
        stampId,
        signatureId,
        comment: note,
        recordPrefixId,
        ...(isWithTeamSignature !== undefined && { isWithTeamSignature }),
      },
      {
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error: any) {
    const errorMessage = handleAxiosError(error, "Error Approving record");
    console.error(errorMessage);
    throw new Error(errorMessage);
  }
};

export const submitRecord = async (
  recordId: string,
  delegatorId?: string,
): Promise<void> => {
  try {
    const response = await recordAxiosInstance.patch(
      `/records/submit/${recordId}`,
      {}, // no body
      {
        headers: withHeaders(),
      },
    );
    return response.data; // Axios automatically resolves to response.data
    // No need for response.ok — Axios throws automatically on non-2xx responses
  } catch (error: any) {
    const errorMessage = handleAxiosError(error, "Error submitting record");
    console.error(errorMessage);
    throw new Error(errorMessage);
  }
};

export const submitAndSendToRo = async (
  id: string,
  stampId?: string,
  signatureId?: string,
  note?: string,
  recordPrefixId?: string,
): Promise<any> => {
  const url = `/records/submit-and-send-to-ro/${id}`;
  const response = await recordAxiosInstance.patch(
    url,
    {
      stampId,
      signatureId,
      comment: note,
      recordPrefixId,
    },
    {
      headers: withHeaders(),
    },
  );
  return response.data;
};

export const makeUnderReview = async (id: string): Promise<any> => {
  const url = `/outgoing-instances/start-review/${id}`;
  const response = await recordAxiosInstance.post(
    url,
    {},
    {
      headers: withHeaders(),
    },
  );
  return response.data;
};

export const fetchMyRecordsApprovals = async (
  params?: ApprovalRecordQueryParams,
): Promise<any> => {
  try {
    const response = await recordAxiosInstance.get(
      `/outgoing-histories/my-record-approvals`,
      {
        params: {
          ...params,
          isUrgent: false,
          take: 10, // Set take to 10 records per page
        },
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    console.error("Error fetching approval actions:", error);
    throw error;
  }
};
export const fetchMyProcessedRecordsApprovals = async (
  params?: ApprovalRecordQueryParams,
): Promise<ProcessedApprovalRecordsResponseDto> => {
  try {
    const response = await recordAxiosInstance.get(
      `/outgoing-histories/my-record-approvals/v2`,
      {
        params: {
          ...params,
          isUrgent: false,
          take: 10, // Set take to 10 records per page
        },
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    console.error("Error fetching approval actions:", error);
    throw error;
  }
};
