import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import lodash from 'lodash';
import { useEffect } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';
import { FG_FASILITAS_DN, FG_FASILITAS_OPTIONS, TARIF_0 } from '../../constant';

type PPHDipotongProps = {
  kodeObjectPajak: any[];
  fgFasilitasOptions: {
    value: string;
    label: string;
  }[];
};

function roundCustom(num: number) {
  const decimalPart = num - Math.floor(num);

  if (decimalPart <= 0.5) return Math.trunc(num); // Bulatkan ke bawah
  return Math.round(num); // Bulatkan ke bilangan bulat terdeka
}

const PphDipotong = ({ kodeObjectPajak, fgFasilitasOptions }: PPHDipotongProps) => {
  const { setValue, control } = useFormContext<Record<string, any>>();

  const perhitunganChanges = useWatch({
    control,
    name: ['penghasilanBruto', 'tarif', 'fgFasilitas', 'normaPenghasilanNeto'],
  });

  const fgFasilitas = perhitunganChanges[2].value;

  useEffect(() => {
    if (perhitunganChanges.filter((item) => lodash.isEmpty(item)).length === 0) {
      const dpp = Number(perhitunganChanges[0] || 0);
      const tarif = Number(perhitunganChanges[1] || 0);
      const fasilitas = perhitunganChanges[2].value;
      const normaPenghasilanNeto = Number(perhitunganChanges[3] || 0);

      const valPphDipotong = dpp * (normaPenghasilanNeto / 100) * (tarif / 100);
      const perhitungan = TARIF_0.includes(fasilitas) ? 0 : valPphDipotong;

      setValue('pphDipotong', `${roundCustom(perhitungan)}`, {
        shouldValidate: true,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [perhitunganChanges]);

  return (
    <Grid container rowSpacing={2} columnSpacing={2}>
      <Grid sx={{ mt: 3 }} size={{ md: 6 }}>
        <Field.Autocomplete
          name="kodeObjekPajak"
          label="Kode Objek Pajak"
          options={kodeObjectPajak}
        />
      </Grid>

      <Grid size={{ md: 12 }}>
        <Divider sx={{ fontWeight: 'bold' }} textAlign="left">
          Fasilitas Pajak Penghasilan
        </Divider>
      </Grid>

      <Grid size={{ md: 6 }}>
        <Field.Autocomplete
          name="fgFasilitas"
          label="Fasilitas"
          options={fgFasilitasOptions}
          onChange={(_, val) => {
            setValue('fgFasilitas', val);

            if (val.value !== FG_FASILITAS_OPTIONS.FASILITAS_LAINNYA)
              setValue('normaPenghasilanNeto', '100');

            if (val.value === FG_FASILITAS_OPTIONS.TANPA_FASILITAS) setValue('noDokLainnya', '');
          }}
        />
      </Grid>

      <Grid size={{ md: 6 }}>
        <Field.Text
          name="noDokLainnya"
          label="Nomor Dokumen Lainnya"
          disabled={['9', ''].includes(fgFasilitas)}
          sx={{ '& .MuiInputBase-root.Mui-disabled': { backgroundColor: '#f6f6f6' } }}
        />
      </Grid>

      <Grid size={{ md: 6 }}>
        <RHFNumeric
          name="penghasilanBruto"
          label="Jumlah Penghasilan Bruto (Rp)"
          allowNegativeValue={false}
          allowDecimalValue={false}
        />
      </Grid>

      <Grid size={{ md: 6 }}>
        <RHFNumeric
          name="normaPenghasilanNeto"
          label="Perkiraan Penghasilan Netto (%)"
          allowNegativeValue={false}
          allowDecimalValue={false}
          maxValue={100}
          readOnly={fgFasilitas !== FG_FASILITAS_OPTIONS.FASILITAS_LAINNYA}
        />
      </Grid>

      <Grid size={{ md: 6 }}>
        <RHFNumeric
          name="tarif"
          label="Tarif (%)"
          allowDecimalValue
          maxValue={100}
          readOnly={
            ![FG_FASILITAS_DN.FASILITAS_LAINNYA, FG_FASILITAS_DN.SKD_WPLN].includes(fgFasilitas)
          }
          disabled={
            ![FG_FASILITAS_DN.FASILITAS_LAINNYA, FG_FASILITAS_DN.SKD_WPLN].includes(fgFasilitas)
          }
        />
      </Grid>

      <Grid size={{ md: 6 }}>
        <RHFNumeric
          name="pphDipotong"
          label="PPh Yang Dipotong/Dipungut"
          allowNegativeValue={false}
          allowDecimalValue={false}
          readOnly
        />
      </Grid>
    </Grid>
  );
};

export default PphDipotong;
