import {
  AcceptIncomingRecordPayload,
  AssignIncomingRecordPayload,
  ReAssignRecordPayload,
  AssignCCPayload,
} from "@/record-management/dto/userRecords/usersDto";
import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import qs from "qs";
import { withHeaders } from "./withHeaders";
import { OutgoingRecordQueryParams } from "./recordOfficerService";
import { AssignIncomingRecordResponse } from "@/record-management/components/hooks/useCreateIncomingRecord";
import IncomingRecordsResponse from "@/record-management/dto/IncomingRecords/incomingTasksDto";
import { IncomingRemarkResponseDto } from "@/record-management/components/hooks/useGetRemarks";

export interface PaginationParams {
  recordType?: string | string[];
  status?: string;
  skip?: number;
  take?: number;
  orderBy?: string | string[];
  hasSeen?: boolean;
  fetchParent?: boolean;
  isForYourReference?: boolean;
}

export interface AddRemarkPayload {
  incomingInstanceId: string;
  comment: string;
}

interface UseInternalIncomingRecordsParams {
  pageIndex?: number;
  pageSize?: number;
  status?: string;
  filterType?: string; // "Department" | "Subject" | "Date" | "Reference Number"
  searchQuery?: string;
  order?: string;
  letterNumber?: string;
  referenceNumber?: string;
  subject?: string;
  recordTypeKey?: string;
  fromCreatedAt?: string;
  toCreatedAt?: string;
  fromSubmittedAt?: string;
  toSubmittedAt?: string;
  fromDispatchedDate?: string;
  toDispatchedDate?: string;
  receiverPosition?: string;
  receiverEmployee?: string;
  sendingPosition?: string;
  sendingEmployee?: string;
  receiverUnit?: string;
  dispatchedBy?: string;
  from?: string; // Sender information filter
}

export interface PaginatedResponse {
  items: any[];
  count: number;
}

export const getIncoming = async (
  params?: UseInternalIncomingRecordsParams,
): Promise<PaginatedResponse> => {
  const { data } = await recordAxiosInstance.get<PaginatedResponse>(
    "incoming-instances/get-my",
    {
      params,
      paramsSerializer: (params) =>
        qs.stringify(params, { arrayFormat: "repeat" }),
      headers: withHeaders(),
    },
  );

  return {
    items: data.items || [],
    count: data.count || 0,
  };
};

export const getIncomingV2 = async (
  params?: UseInternalIncomingRecordsParams,
): Promise<IncomingRecordsResponse> => {
  const { data } = await recordAxiosInstance.get<IncomingRecordsResponse>(
    "incoming-instances/get-my/v2",
    {
      params,
      paramsSerializer: (params) =>
        qs.stringify(params, { arrayFormat: "repeat" }),
      headers: withHeaders(),
    },
  );

  return {
    items: data.items || [],
    count: data.count || 0,
  };
};

export const getIncomingParent = async (
  params?: UseInternalIncomingRecordsParams,
): Promise<PaginatedResponse> => {
  const { data } = await recordAxiosInstance.get<PaginatedResponse>(
    "incoming-instances/get-my-parent",
    {
      params,
      paramsSerializer: (params) =>
        qs.stringify(params, { arrayFormat: "repeat" }),
      headers: withHeaders(),
    },
  );

  return {
    items: data.items || [],
    count: data.count || 0,
  };
};

export const assignIncomingRecordApi = async (
  body: AssignIncomingRecordPayload,
): Promise<any> => {
  const { data } = await recordAxiosInstance.post(
    "record-boxes/assign",
    body,
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const assignDraftIncomingRecordApi = async (
  id: string,
): Promise<AssignIncomingRecordResponse> => {
  const { data } = await recordAxiosInstance.patch(
    `records/start-assignment/${id}`,
    {},
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const getRecordIncoming = async (
  params?: OutgoingRecordQueryParams,
): Promise<any> => {
  const { data } = await recordAxiosInstance.get("record-boxes/my-unit-box", {
    params: params,
    headers: withHeaders(),
  });

  return data;
};

export const getExternalRecordIncoming = async (
  params?: OutgoingRecordQueryParams,
): Promise<any> => {
  const { data } = await recordAxiosInstance.get(
    "records/non-smart-records",
    {
      params: params,
      headers: withHeaders(),
    },
  );

  return data;
};

export const getCCIncoming = async (
  params?: PaginationParams,
): Promise<PaginatedResponse> => {
  const { fetchParent, skip, take, orderBy, ...bodyParams } = params ?? {};
  const requestBody = {
    ...bodyParams,
  };

  const { data } = await recordAxiosInstance.post<PaginatedResponse>(
    "incoming-instances/get-my-cc",
    requestBody,
    {
      params: {
        isForYourReference: params?.isForYourReference,
        skip,
        take,
        orderBy: orderBy,
      },
      headers: withHeaders(),
    },
  );

  return data;
};

export const getCCIncomingParent = async (
  params?: PaginationParams,
): Promise<PaginatedResponse> => {
  const { fetchParent, skip, take, orderBy, ...bodyParams } = params ?? {};
  const requestBody = {
    ...bodyParams,
  };

  const { data } = await recordAxiosInstance.post<PaginatedResponse>(
    "incoming-instances/get-my-parent-cc",
    requestBody,
    {
      params: {
        isForYourReference: params?.isForYourReference,
        skip,
        take,
        orderBy: orderBy || "record.createdAt:DESC",
      },
      headers: withHeaders(),
    },
  );

  return data;
};

export const reassignRecord = async (
  body: ReAssignRecordPayload,
): Promise<any> => {
  const { data } = await recordAxiosInstance.post(
    "incoming-instances/re-assign",
    body,
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const addRemarkService = async (
  body: AddRemarkPayload,
): Promise<any> => {
  const { data } = await recordAxiosInstance.post(
    "incoming-instance-comments",
    body,
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const getRemarksByIncomingInstanceId = async (
  incomingInstanceId: string,
): Promise<IncomingRemarkResponseDto> => {
  const { data } = await recordAxiosInstance.get(
    `incoming-instance-comments/list/${incomingInstanceId}`,
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const acceptRecord = async (
  body: AcceptIncomingRecordPayload,
): Promise<any> => {
  const { data } = await recordAxiosInstance.patch(
    "incoming-instances/respond",
    body,
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const hasSeen = async (
  id: string,
  isForYourReference: boolean,
): Promise<any> => {
  const { data } = await recordAxiosInstance.patch(
    `records/has-seen/${id}/${isForYourReference}`,
    {},
    {
      headers: withHeaders(),
    },
  );

  return data;
};

export const assignCCRecord = async (body: AssignCCPayload): Promise<any> => {
  const { data } = await recordAxiosInstance.post(
    "incoming-instances/assign-cc",
    body,
    {
      headers: withHeaders(),
    },
  );

  return data;
};
