import { useEffect } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import type { TGetListDataKOPDn } from '../types/types';

const usePphDipotong = (kodeObjekPajakSelected?: TGetListDataKOPDn) => {
  const { watch, setValue, control } = useFormContext();

  // ambil value dari form
  const fgFasilitas = watch('fgFasilitas');
  const fgIdDipotong = watch('fgIdDipotong');

  // mapping statusPPh ke isFinal
  const isFinal = kodeObjekPajakSelected?.statuspph?.toLowerCase() === 'final' ? 1 : 0;

  const updateTarifValues = () => {
    if (kodeObjekPajakSelected) {
      let valueTarif = Number(kodeObjekPajakSelected.tarif) || 0;

      if (fgFasilitas === '6') {
        valueTarif = 0.5;
      } else if (fgFasilitas === '8') {
        valueTarif = 0;
      }

      setValue('tarif', valueTarif, { shouldValidate: true });
      setValue('tarifLt', fgIdDipotong === '1' && isFinal === 0 ? '100' : '0', {
        shouldValidate: true,
      });
    }
  };

  // watch field yang mempengaruhi perhitungan
  const handlerSetPphDipotong = useWatch({
    control,
    name: ['thnPajak', 'fgFasilitas', 'fgIdDipotong', 'jmlBruto', 'tarif'],
  });

   
  const calculateAndSetPphDipotong = (
    thnPajak: number,
    fgFasilitas: string,
    fgIdDipotong: string,
    jmlBruto: number,
    tarif: number
  ) => {
    if (kodeObjekPajakSelected) {
      const valTarif = thnPajak < 2024 && fgIdDipotong === '1' && isFinal === 0 ? tarif * 2 : tarif;

      const valPphDipotong =
        fgFasilitas === '8' // contoh: fasilitas tertentu PPh 0
          ? 0
          : (jmlBruto * valTarif) / 100;

      setValue('pphDipotong', Math.round(valPphDipotong || 0), {
        shouldValidate: true,
      });
    }
  };

  useEffect(() => {
    if (handlerSetPphDipotong.filter((item) => !item).length < 2) {
      calculateAndSetPphDipotong(
        Number(handlerSetPphDipotong[0]),
        handlerSetPphDipotong[1] as string,
        handlerSetPphDipotong[2] as string,
        Number(handlerSetPphDipotong[3]),
        Number(handlerSetPphDipotong[4])
      );
    }
  }, [handlerSetPphDipotong]);

  return {
    updateTarifValues,
  };
};

export default usePphDipotong;
