import { isEmpty } from 'lodash';
import { useQuery } from '@tanstack/react-query';
import queryKey from '../constant/queryKey';
import type { TableReturFakturPKResult } from '../types/types';
import fakturApi from '../utils/api';

export type TGetFakturPMApiWrapped = {
  data: TableReturFakturPKResult[];
  total: number;
  pageSize: number;
  page: number; // 1-based
};

/**
 * Format tanggal ke format dd/mm/yyyy
 */
export const formatDateToDDMMYYYY = (dateString: string | null | undefined) => {
  if (!dateString) return '';
  const [year, month, day] = dateString.split('T')[0].split('-');
  return `${day}/${month}/${year}`;
};

/**
 * Normalisasi params API — otomatis bedakan antara "list mode" dan "search mode"
 */
const normalizeParams = (params: any) => {
  if (!params) return {};

  const {
    page,
    pageSize,
    sort,
    filter,
    advanced,
    sortingMode: sortingModeParam,
    sortingMethod: sortingMethodParam,
    ...rest
  } = params;

  // Deteksi apakah user sedang minta list (ada pagination/sorting/filter)
  const isListRequest =
    page !== undefined ||
    pageSize !== undefined ||
    sort !== undefined ||
    filter !== undefined ||
    advanced !== undefined;

  // 🔸 Kalau bukan list (misal hanya nomorFaktur), langsung kembalikan tanpa modifikasi
  if (!isListRequest) {
    return rest;
  }

  // 🔹 Kalau list, pakai logika sorting & pagination seperti sebelumnya
  let sortPayload: any;
  let sortingMode = sortingModeParam || '';
  let sortingMethod = sortingMethodParam || '';

  if (sort) {
    try {
      const parsed = JSON.parse(sort);
      if (Array.isArray(parsed) && parsed.length > 0) {
        sortPayload = parsed;
        sortingMode = parsed[0]?.field ?? sortingMode;
        sortingMethod = parsed[0]?.sort ?? sortingMethod;
      }
    } catch {
      sortPayload = [];
    }
  }

  return {
    page: (page ?? 0) + 1,
    limit: pageSize ?? 10,
    advanced:
      typeof advanced === 'string' && advanced.trim() !== ''
        ? advanced
        : filter && !isEmpty(JSON.parse(filter))
          ? filter
          : undefined,
    ...(sortPayload ? { sort: sortPayload } : {}),
    sortingMode,
    sortingMethod,
    ...rest,
  };
};

/**
 * Hook utama untuk GET faktur PK
 * Bisa digunakan untuk:
 * - List data (dengan pagination, sorting, dsb.)
 * - Search by nomorFaktur (atau param lain tanpa pagination)
 */
export const useGetReturFakturPK = ({ params }: { params: any }) => {
  const normalized = normalizeParams(params);
  const { page, limit, advanced, sortingMode, sortingMethod, ...rest } = normalized;

  const restKey = JSON.stringify(rest ?? {});

  const isListRequest =
    page !== undefined ||
    limit !== undefined ||
    advanced !== undefined ||
    sortingMode ||
    sortingMethod;

  return useQuery<TGetFakturPMApiWrapped>({
    queryKey: isListRequest
      ? ['faktur-pk', page, limit, advanced, sortingMode, sortingMethod, restKey]
      : ['faktur-pk', restKey], // supaya cache beda antara list dan search tunggal
    queryFn: async () => {
      const res: any = await fakturApi.getReturPK({ params: normalized });

      const rawData: any[] = Array.isArray(res?.data) ? res.data : res?.data ? [res.data] : [];
      const total = Number(res?.total ?? res?.totalRow ?? 0);

      return {
        data: rawData as TableReturFakturPKResult[],
        total,
        pageSize: normalized.limit ?? 0,
        page: normalized.page ?? 1,
      };
    },
    placeholderData: (prev: any) => prev,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    staleTime: 0,
    gcTime: 0,
    retry: false,
  });
};

/**
 * Hook untuk get detail faktur PK by ID
 */
export const useGetReturFakturPKById = (id: string, options = {}) =>
  useQuery({
    queryKey: queryKey.fakturReturPK.detail(id),
    queryFn: async () => {
      const res = await fakturApi.getReturPKById(id);
      if (!res) throw new Error('Data tidak ditemukan');
      return res;
    },
    enabled: !!id,
    refetchOnWindowFocus: false,
    ...options,
  });

export default useGetReturFakturPK;
