/* eslint-disable react/jsx-no-useless-fragment */
import { CalculateRounded, CheckCircleRounded } from '@mui/icons-material';
import { LoadingButton } from '@mui/lab';
import { Alert, Grid } from '@mui/material';
import dayjs from 'dayjs';
import { useEffect, useMemo } from 'react';
import { useFormContext } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';
import {
  FG_FASILITAS_PPH_21,
  FG_PERHITUNGAN,
  FG_PERHITUNGAN_TEXT,
  KODE_OBJEK_PAJAK,
  METODE_POTONG,
} from 'src/sections/bupot-21-26/constant';
import {
  getHitungBulananErrorMessage,
  useHitungBupotFinalTidakFinal,
} from 'src/sections/bupot-21-26/hitung';

const fgPerhitunganOptions = Object.values(FG_PERHITUNGAN).map((value) => ({
  value,
  label: FG_PERHITUNGAN_TEXT[value],
}));

function JumlahPerhitunganForm({
  ptkpOptions,
}: {
  ptkpOptions: {
    value: string;
    label: string;
  }[];
}) {
  const { watch, getValues, setValue, trigger } = useFormContext();

  const kdObjPjk = watch('kdObjPjk');

  const { mutate, isPending } = useHitungBupotFinalTidakFinal({
    onSuccess: (data) => {
      console.log('✅ Berhasil hitung PPh21:', data);
      const tunjanganPPh = data.pph21ditanggungperusahaan ?? data.tunjanganPPh;
      setValue(
        'pph21',
        [FG_FASILITAS_PPH_21.SKB_PPH_PASAL_21].includes(watch('fgFasilitas')) ? 0 : data.pphDipotong
      );

      setValue('tarif', data.tarif || kdObjPjk.dpp);
      setValue('tunjanganPPh', tunjanganPPh || 0);
    },
    onError: (error) => {
      console.error('❌ Error:', getHitungBulananErrorMessage(error));
    },
  });

  const handleHitung = async () => {
    const validasi = await trigger(['phBruto', 'ptkp', 'fgPerhitungan']);
    if (!validasi) return;

    const {
      phBruto: penghasilanBruto,
      ptkp,
      fgPerhitungan,
      tglPemotongan,
      dppPersen,
      jenisHitung,
      akumulasiJmlBruto,
    } = getValues();

    console.log('🚀 ~ handleHitung ~ fgPerhitungan:', { fgPerhitungan });

    const tglBupot = dayjs(tglPemotongan).format('DDMMYYYY');

    const data = {
      tglBupot,
      dppPersen,
      jenisHitung,
      status: ptkp.value,
      kodeObjekPajak: kdObjPjk.value,
      penghasilanKotor: penghasilanBruto,
      akumulasiJmlBruto: akumulasiJmlBruto || '0',
      metode: fgPerhitungan !== '0' ? METODE_POTONG.GROSS_UP : METODE_POTONG.GROSS, // Simplify conditional assignment
    };

    mutate(data as any);
  };

  const isOpenAkumulasiPerhitunganForm = useMemo(() => {
    if ([KODE_OBJEK_PAJAK.FINAL_01, KODE_OBJEK_PAJAK.FINAL_02].includes(kdObjPjk.value))
      return true;
    return false;
  }, [kdObjPjk.value]);

  useEffect(() => {
    if (!isOpenAkumulasiPerhitunganForm) {
      setValue('akumulasiJmlBruto', 0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpenAkumulasiPerhitunganForm]);

  return (
    <Grid container rowSpacing={2} columnSpacing={2} sx={{ my: 3 }}>
      {isOpenAkumulasiPerhitunganForm ? (
        <>
          <Grid size={{ md: 5 }}>
            <Alert variant="outlined" icon={<CheckCircleRounded />} severity="warning">
              Transaksi dilakukan dalam kurun waktu 2 tahun
            </Alert>
          </Grid>
          <Grid size={{ md: 7 }}>
            <RHFNumeric name="akumulasiJmlBruto" label="Jumlah Akumulasi (Rp)" />
          </Grid>
        </>
      ) : (
        <></>
      )}
      <Grid size={{ md: 3 }}>
        <Field.RadioGroup
          row
          name="fgPerhitungan"
          label="Metode Pemotongan"
          options={fgPerhitunganOptions.filter((a) => a.value !== FG_PERHITUNGAN.MIXED)}
        />
      </Grid>

      <Grid size={{ md: 9 }}>
        <Field.Autocomplete name="ptkp" label="Status PTKP" options={ptkpOptions} />
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric name="phBruto" label="Jumlah Penghasilan (Rp)" />
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric name="tunjanganPPh" label="Tunjangan PPh 21 (Rp)" readOnly />
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric name="dppPersen" label="Dpp (%)" allowDecimalValue maxValue={100} readOnly />
      </Grid>

      <Grid size={{ md: 5 }}>
        <RHFNumeric name="tarif" label="Tarif (%)" allowDecimalValue maxValue={100} readOnly />
      </Grid>

      <Grid size={{ md: 5 }}>
        <RHFNumeric name="pph21" label="PPh Pasal 21" readOnly />
      </Grid>

      <Grid size={{ md: 2 }} alignSelf="center">
        <LoadingButton
          variant="contained"
          fullWidth
          size="large"
          color="primary"
          onClick={handleHitung}
          loading={isPending}
          startIcon={<CalculateRounded />}
        >
          Hitung
        </LoadingButton>
      </Grid>
    </Grid>
  );
}

export default JumlahPerhitunganForm;
