import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import MenuItem from '@mui/material/MenuItem';
import { useEffect, useMemo } from 'react';
import { Field } from 'src/components/hook-form';
import { useFormContext } from 'react-hook-form';
import FieldNumberText from 'src/shared/components/FieldNumberText ';
import usePphDipotong from 'src/sections/bupot-unifikasi/bupot-dn/hooks/usePphDipotong';
import {
  FG_FASILITAS_DN,
  FG_FASILITAS_MASTER_KEY,
  FG_FASILITAS_TEXT,
} from 'src/sections/bupot-unifikasi/bupot-dn/constant';
import { TGetListDataKOPDn } from 'src/sections/bupot-unifikasi/bupot-dn/types/types';

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

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

  const selectedKode = watch('kdObjPjk');
  const fgFasilitas = watch('fgFasilitas');

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

  // Hook otomatis hitung tarif & pphDipotong
  usePphDipotong(kodeObjekPajakSelected);

  // Fasilitas options
  const fgFasilitasOptions = useMemo(
    () =>
      Object.entries(FG_FASILITAS_DN).map(([_, value]) => ({
        value,
        label: FG_FASILITAS_TEXT[value],
      })),
    []
  );

  const fasilitasOptions = useMemo(
    () =>
      fgFasilitasOptions.filter(
        (opt) =>
          kodeObjekPajakSelected &&
          kodeObjekPajakSelected[FG_FASILITAS_MASTER_KEY[opt.value] as keyof TGetListDataKOPDn] ===
            1
      ),
    [fgFasilitasOptions, kodeObjekPajakSelected]
  );

  // Reset fasilitas jika kode objek pajak berubah
  useEffect(() => {
    setValue('fgFasilitas', '', { shouldValidate: true });
  }, [selectedKode, setValue]);

  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">
          {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>

      {/* Nomor 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: 6 }}>
        <FieldNumberText name="jmlBruto" label="Jumlah Penghasilan Bruto (Rp)" />
      </Grid>

      <Grid size={{ md: 6 }}>
        <Field.Text
          name="kiraNetto"
          label="Perkiraan Penghasilan Netto (%)"
          type="number"
          slotProps={{
            input: {
              readOnly: true,
              style: { backgroundColor: '#f6f6f6' },
            },
          }}
        />
      </Grid>

      {/* Tarif */}
      <Grid size={{ md: 6 }}>
        <Field.Text
          name="tarif"
          label="Tarif (%)"
          type="number"
          value={kodeObjekPajakSelected?.tarif || ''}
          slotProps={{
            input: {
              readOnly: ![FG_FASILITAS_DN.SKD_WPLN, FG_FASILITAS_DN.FASILITAS_LAINNYA].includes(
                fgFasilitas
              ),
              style: {
                backgroundColor: ![
                  FG_FASILITAS_DN.SKD_WPLN,
                  FG_FASILITAS_DN.FASILITAS_LAINNYA,
                ].includes(fgFasilitas)
                  ? '#f6f6f6'
                  : undefined,
              },
            },
          }}
        />
      </Grid>

      {/* PPh Dipotong */}
      <Grid size={{ md: 6 }}>
        <Field.Text
          name="pphDipotong"
          label="PPh Yang Dipotong/Dipungut"
          type="number"
          slotProps={{
            input: {
              readOnly: true,
              style: { backgroundColor: '#f6f6f6' },
            },
          }}
        />
      </Grid>
    </Grid>
  );
};

export default PphDipotong;
