import { useMutation, type UseMutationOptions } from '@tanstack/react-query';
import dayjs from 'dayjs';
import queryKey from '../constant/queryKey';
import type { TPostBulananRequest } from '../types/types';
import bulananApi from '../utils/api';

const extractKapFromKodeObjekPajak = (kodeObjekPajak: string) =>
  `4111${kodeObjekPajak.split('-')[0]}`;

const transformParams = ({ isPengganti = false, ...Data }: any): TPostBulananRequest => {
  const {
    id,
    idBupot,
    noBupot,
    msPajak,
    thnPajak,
    idDipotong,
    nitku,
    namaDipotong,
    fgFasilitas,
    noDokLainnya,
    kdObjPjk,
    kdJnsPjk,
    jmlBruto,
    tarif,
    pphDipotong,
    revNo: initialRevNo,
    tglPemotongan,
    idTku,
    fgGrossUp,
    alamatDipotong,
    foreignEmployee,
    passportNo,
    countryCode,
    statusPtkp,
    posisiJabatan,
  } = Data;

  console.log('🚀 ~ transformParams ~ Data:', Data);

  const revNo = isPengganti ? parseInt(initialRevNo || 0, 10) + 1 : parseInt(initialRevNo || 0, 10);
  const [status, jmlPtkp] = statusPtkp.split('/');

  return {
    id: !isPengganti ? (id ?? null) : null,
    idBupot: isPengganti ? (idBupot ?? '') : undefined,
    noBupot: isPengganti ? (noBupot ?? '') : undefined,
    npwpPemotong: idTku,
    idTku: idTku ?? '',
    masaPajak: msPajak ? dayjs(msPajak).format('MM') : '',
    tahunPajak: thnPajak ? dayjs(thnPajak).format('YYYY') : '',
    npwp: idDipotong ?? '',
    nik: nitku ?? (idDipotong ? `${idDipotong}000000` : ''),
    nama: namaDipotong ?? '',
    revNo,
    fgNpwpNik: true,
    fgJnsBupot: 'A0',
    alamat: alamatDipotong ?? '',
    dataDetilA0: {
      foreignEmployee: foreignEmployee ?? false,
      passportNo: passportNo ?? '',
      countryCode: countryCode ?? null,
      statusPtkp: status ?? '',
      jmlPtkp: jmlPtkp ?? '0',
      posisiJabatan: posisiJabatan ?? '',
      kodeObjekPajak: kdObjPjk ?? '',
      pasalPPh: kdJnsPjk ?? '',
      penghasilanKotor: jmlBruto ?? 0,
      tarif: tarif ?? 0,
      pphDipotong: pphDipotong ?? 0,
      kap: extractKapFromKodeObjekPajak(kdObjPjk ?? ''),
      kjs: '100',
      sertifikatInsentifDipotong: fgFasilitas ?? '9',
      nomorSertifikatInsentif: noDokLainnya ?? '',
    },
    tglPemotongan: tglPemotongan ? dayjs(tglPemotongan).format('DDMMYYYY') : '',
    fgGrossUp: fgGrossUp ?? 1,
  };
};

const useSaveBulanan = (
  props?: Omit<UseMutationOptions<any, Error, any, unknown>, 'mutationKey' | 'mutationFn'>
) =>
  useMutation({
    mutationKey: queryKey.bulanan.draft,
    mutationFn: (params: any) => bulananApi.save(transformParams(params)),
    ...props,
  });

export default useSaveBulanan;
