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,
    masaPajak,
    tahunPajak,
    npwp,
    nitku,
    namaDipotong,
    fgFasilitas,
    noDokLainnya,
    kdObjPjk,
    kdJnsPjk,
    jmlBruto,
    tarif,
    pphDipotong,
    revNo: initialRevNo,
    tglPemotongan,
    idTku,
    fgGrossUp,
    alamatDipotong,
    foreignEmployee,
    passportNo,
    countryCode,
    statusPtkp,
    posisiJabatan,
  } = Data;

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

  const npwpLog = localStorage.getItem('npwp_log') ?? '';

  return {
    id: !isPengganti ? (id ?? null) : null,
    idBupot,
    noBupot,
    npwpPemotong: npwpLog,
    idTku: idTku ?? '',
    masaPajak,
    tahunPajak,
    npwp: npwp ?? '',
    nik: nitku ?? (npwp ? `${npwp}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;
