import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import MenuItem from '@mui/material/MenuItem';
import React, { useEffect, useMemo } from 'react';
import { Field } from 'src/components/hook-form';
import { TGetListDataKOPDn } from '../../types/types';
import { useFormContext } from 'react-hook-form';
import {
  FG_FASILITAS_DN,
  FG_FASILITAS_MASTER_KEY,
  FG_FASILITAS_TEXT,
  TARIF_0,
} from '../../constant';
import { NumericFormat } from 'react-number-format';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';

type PPHDipotongProps = {
  kodeObjectPajak: TGetListDataKOPDn[];
};

const PphDipotong = ({ kodeObjectPajak }: PPHDipotongProps) => {
  const { watch, setValue } = useFormContext();

  const selectedKode = watch('kdObjPjk');
  const fgFasilitas = watch('fgFasilitas');
  const jmlBruto = Number(watch('jmlBruto') || 0);
  const tarif = Number(watch('tarif') || 0);

  const kodeObjekPajakSelected = useMemo(
    () => kodeObjectPajak.find((item) => item.kode === selectedKode),
    [kodeObjectPajak, selectedKode]
  );

  // Hitung PPh dipotong
  const pphDipotong = useMemo(() => {
    if (!fgFasilitas) return 0;
    if (TARIF_0.includes(fgFasilitas)) return 0;
    return (jmlBruto * tarif) / 100;
  }, [fgFasilitas, jmlBruto, tarif]);

  // Reset tarif saat kode objek pajak berubah
  useEffect(() => {
    if (!selectedKode || !kodeObjekPajakSelected) return;
    if (fgFasilitas !== FG_FASILITAS_DN.FASILITAS_LAINNYA) {
      setValue('tarif', Number(kodeObjekPajakSelected.tarif) || 0);
    }
  }, [selectedKode, kodeObjekPajakSelected, fgFasilitas, setValue]);

  // Reset tarif saat fasilitas berubah
  useEffect(() => {
    if (!fgFasilitas) return;
    if (fgFasilitas === FG_FASILITAS_DN.FASILITAS_LAINNYA) {
      setValue('tarif', 0);
      setValue('noDokLainnya', '');
    } else if (kodeObjekPajakSelected) {
      setValue('tarif', Number(kodeObjekPajakSelected.tarif) || 0);
      setValue('noDokLainnya', '');
    }
  }, [fgFasilitas, kodeObjekPajakSelected, setValue]);

  // Opsi fasilitas
  const fasilitasOptions = useMemo(() => {
    if (!kodeObjekPajakSelected) return [];
    return Object.values(FG_FASILITAS_DN)
      .map((v) => ({ value: v, label: FG_FASILITAS_TEXT[v] }))
      .filter(
        (opt) =>
          kodeObjekPajakSelected[FG_FASILITAS_MASTER_KEY[opt.value] as keyof TGetListDataKOPDn] ===
          1
      );
  }, [kodeObjekPajakSelected]);

  return (
    <Grid container rowSpacing={2} columnSpacing={2}>
      {/* Kode objek pajak */}
      <Grid sx={{ mt: 3 }} size={{ md: 6 }}>
        <Field.Select name="kdObjPjk" label="Kode Objek Pajak">
          {kodeObjectPajak.map((item) => (
            <MenuItem key={item.kode} value={item.kode}>
              {`(${item.kode}) ${item.nama}`}
            </MenuItem>
          ))}
        </Field.Select>
      </Grid>

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

      {/* Fasilitas */}
      <Grid size={{ md: 6 }}>
        <Field.Select
          name="fgFasilitas"
          label="Fasilitas"
          //   onChange={() => {
          //     setValue('noDokLainnya', '');
          //   }}
        >
          {fasilitasOptions.length === 0 ? (
            <MenuItem disabled value="">
              No options
            </MenuItem>
          ) : (
            fasilitasOptions.map((opt) => (
              <MenuItem key={opt.value} value={opt.value}>
                {opt.label}
              </MenuItem>
            ))
          )}
        </Field.Select>
      </Grid>

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

      {/* Jumlah bruto */}
      <Grid size={{ md: 4 }}>
        <RHFNumeric
          name="jmlBruto"
          label="Jumlah Penghasilan Bruto (Rp)"
          allowNegativeValue={false}
          allowDecimalValue={false}
        />
      </Grid>

      {/* Tarif */}
      <Grid size={{ md: 4 }}>
        <RHFNumeric
          name="tarif"
          label="Tarif (%)"
          allowDecimalValue
          maxValue={100}
          readOnly={fgFasilitas !== FG_FASILITAS_DN.FASILITAS_LAINNYA}
          disabled={fgFasilitas !== FG_FASILITAS_DN.FASILITAS_LAINNYA}
        />
      </Grid>

      {/* PPh dipotong */}
      <Grid size={{ md: 4 }}>
        <Field.Text
          name="pphDipotong"
          label="PPh Yang Dipotong/Dipungut"
          value={pphDipotong}
          InputLabelProps={{ shrink: true }}
          slotProps={{
            input: {
              inputComponent: NumericFormat as any,
              inputProps: {
                thousandSeparator: '.',
                decimalSeparator: ',',
                allowNegative: false,
                valueIsNumericString: true,
              },
              readOnly: true,
              style: { backgroundColor: '#f6f6f6' },
            },
          }}
        />
      </Grid>
    </Grid>
  );
};

export default PphDipotong;
