import { CalculateRounded } from '@mui/icons-material';
import { LoadingButton } from '@mui/lab';
import { Grid } from '@mui/material';
import dayjs from 'dayjs';
import { 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 { getHitungBulananErrorMessage, useHitungBulanan } from 'src/sections/bupot-21-26/hitung';
import {
  FG_FASILITAS_PPH_21,
  FG_PERHITUNGAN,
  FG_PERHITUNGAN_TEXT,
  KODE_OBJEK_PAJAK,
  METODE_POTONG,
  PERHITUNGAN_BUPOT21,
  PTKP,
  PTKP_TEXT,
  PTKP_TITLE,
} from '../../constant';

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

function JumlahPerhitunganForm() {
  const { watch, getValues, setValue } = useFormContext();

  const ptkpOptions = useMemo(
    () =>
      Object.entries(PTKP)
        .map(([key, value]) => ({ value, label: PTKP_TEXT[value] }))
        .filter((option) => !option.value.includes(PTKP_TITLE.HB)),
    []
  );

  const { mutate, isPending } = useHitungBulanan({
    onSuccess: (data) => {
      console.log('✅ Berhasil hitung PPh21:', data);

      setValue(
        'pph21',
        [FG_FASILITAS_PPH_21.SKB_PPH_PASAL_21].includes(watch('fgFasilitas')) ? 0 : data.pphBulan
      );

      setValue('dpp', 100);
      setValue('tarif', data.tarif);
      setValue('tunjanganPPh', data.pph21ditanggungperusahaan ?? data.tunjanganPPh);
    },
    onError: (error) => {
      console.error('❌ Error:', getHitungBulananErrorMessage(error));
    },
  });

  const handleHitung = () => {
    const { phBruto: penghasilanBruto, ptkp, fgPerhitungan, tglPemotongan, kdObjPjk } = getValues();

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

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

    mutate(data as any);
  };
  return (
    <Grid container rowSpacing={2} columnSpacing={2} sx={{ my: 3 }}>
      <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: 6 }}>
        <RHFNumeric name="phBruto" label="Jumlah Penghasilan (Rp)" />
      </Grid>

      <Grid size={{ md: 6 }}>
        <RHFNumeric name="tunjanganPPh" label="Tunjangan PPh 21 (Rp)" 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;
