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

export type TGetFakturPMApiWrapped = {
  data: TGetListDataTableFakturPMResult[];
  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 useGetFakturPM = ({ params }: { params: any }) => {
  const normalized = normalizeParams(params);
  const { page, limit, advanced, sortingMode, sortingMethod, ...rest } = normalized;

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

  return useQuery<TGetFakturPMApiWrapped>({
    queryKey: isListRequest
      ? ['faktur-pk', page, limit, advanced, sortingMode, sortingMethod]
      : ['faktur-pk', rest], // supaya cache beda antara list dan search tunggal
    queryFn: async () => {
      const res: any = await fakturApi.getFakturPM({ 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 TGetListDataTableFakturPMResult[],
        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 useGetFakturPKById = (id: string, options = {}) =>
  useQuery({
    queryKey: queryKey.faktuPK.detail(id),
    queryFn: async () => {
      const res = await fakturApi.getFakturPMById(id);
      if (!res) throw new Error('Data tidak ditemukan');
      return res;
    },
    enabled: !!id,
    refetchOnWindowFocus: false,
    ...options,
  });

export default useGetFakturPM;
