import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import MenuItem from '@mui/material/MenuItem';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import { useFormContext } from 'react-hook-form';
import { useSelector } from 'react-redux';
import { Field } from 'src/components/hook-form';
import type { RootState } from 'src/store';

export const METODE_PEMBAYARAN = [
  {
    value: 'DIRECT',
    label: 'Pembayaran Langsung',
  },
  {
    value: 'IMPREST',
    label: 'Uang Persediaan',
  },
];

const DokumenReferensi = ({
  namaDokOptions,
}: {
  namaDokOptions: {
    value: string;
    label: string;
  }[];
}) => {
  const { watch, setValue } = useFormContext<Record<string, any>>();
  const nitku = useSelector((state: RootState) => state.user.data.nitku_trial);
  const nitkuValue = watch('idTku');
  const isNmrSP2D = watch('metodePembayaranBendahara') === 'IMPREST';

  const npwpLog = localStorage.getItem('npwp_log') || '';
  const isSp2d = npwpLog.slice(0, 4) === '0001';

  useEffect(() => {
    if (!nitkuValue && nitku) {
      setValue('idTku', nitku);
    }
  }, [nitku, nitkuValue, setValue]);

  return (
    <Grid sx={{ mb: 3 }} container rowSpacing={2} columnSpacing={2}>
      <Grid sx={{ mt: 3 }} size={{ md: 12 }}>
        <Divider sx={{ fontWeight: 'bold' }} textAlign="left">
          Daftar Dokumen
        </Divider>
      </Grid>
      <Grid size={{ md: 6 }}>
        <Field.Autocomplete name="namaDok" label="Nama Dokumen" options={namaDokOptions} />
      </Grid>
      <Grid size={{ md: 6 }}>
        <Field.Text name="nomorDok" label="Nomor Dokumen" />
      </Grid>
      {isSp2d && (
        <>
          <Grid size={{ md: 6 }}>
            <Field.Autocomplete
              name="metodePembayaranBendahara"
              label="Metode Pembayaran SP2D"
              options={METODE_PEMBAYARAN}
              disableClearable={false}
              onChange={(_, val) => {
                setValue('metodePembayaranBendahara', val);
                setValue('nomorSP2D', '');
              }}
            />
          </Grid>
          <Grid size={{ md: 6 }}>
            <Field.Text name="nomorSP2D" label="Nomor SP2D" disabled={isNmrSP2D} />
          </Grid>
        </>
      )}
      <Grid size={{ md: 6 }}>
        <Field.DatePicker
          name="tglDok"
          label="Tanggal Dokumen"
          format="DD/MM/YYYY"
          maxDate={dayjs()}
          minDate={dayjs('2025-01-01')}
        />
      </Grid>
      <Grid size={{ md: 6 }}>
        <Field.Select name="idTku" label="NITKU Pemotong">
          <MenuItem value={nitku}>{nitku}</MenuItem>
        </Field.Select>
      </Grid>
    </Grid>
  );
};

export default DokumenReferensi;
