import Divider from '@mui/material/Divider';
import React, { useEffect, useRef } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import { useParams } from 'react-router';
import Grid from '@mui/material/Grid';

interface InformasiPembeliProps {
  dlmData?: any;
  isLoading?: boolean;
  isRetur?: boolean;
}

const InformasiPembeli: React.FC<InformasiPembeliProps> = ({ dlmData, isRetur }) => {
  const { type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();
  const { control, setValue } = useFormContext();

  const isPengganti = type === 'pengganti';

  const kdTransaksi = useWatch({
    control,
    name: 'kdTransaksi',
  });

  const prevKdTransaksi = useRef<string | undefined>(undefined);

  const isEdit = type === 'ubah';
  const canModify = !dlmData || isEdit;

  const canEditnamaPenjual = isRetur || canModify;

  useEffect(() => {
    if (!kdTransaksi) return;

    // 🔁 BERUBAH DARI IMPORT → SELAIN IMPORT
    if (prevKdTransaksi.current === 'IMPORT' && kdTransaksi !== 'IMPORT') {
      setValue('npwpPenjual', '', {
        shouldDirty: true,
        shouldValidate: true,
      });
    }

    // ✅ MASUK KE IMPORT
    if (kdTransaksi === 'IMPORT') {
      setValue('npwpPenjual', '0000000000000000', {
        shouldDirty: false,
        shouldValidate: true,
      });
    }

    // simpan nilai terakhir
    prevKdTransaksi.current = kdTransaksi;
  }, [kdTransaksi, setValue]);

  useEffect(() => {
    if (!isRetur) return;
    if (!dlmData) return;

    // NPWP dikunci & diambil dari dokumen asal
    setValue('npwpPenjual', dlmData.npwppenjual ?? '', {
      shouldDirty: false,
      shouldValidate: false,
    });

    // Nama pembeli default dari dokumen asal (masih boleh diedit)
    setValue('namaPenjual', dlmData.namapenjual ?? '', {
      shouldDirty: false,
      shouldValidate: false,
    });
  }, [isRetur, dlmData, setValue]);

  return (
    <Grid container spacing={2} sx={{ mb: 3 }}>
      <Grid size={{ xs: 12 }} sx={{ mt: 3 }}>
        <Divider sx={{ fontWeight: 'bold', fontSize: '1rem' }} textAlign="left">
          Informasi Penjual
        </Divider>
      </Grid>

      {/* IDENTITAS */}

      {/* NPWP*/}
      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text
          name="npwpPenjual"
          label="NPWP Penjual"
          disabled={!canModify || kdTransaksi === 'IMPORT' || isPengganti || isRetur}
          inputProps={{
            inputMode: 'numeric',
            pattern: '[0-9]*',
            maxLength: 16,
          }}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
            const value = e.target.value.replace(/\D/g, '').slice(0, 16);
            setValue('npwpPenjual', value, { shouldDirty: true });
          }}
          sx={{ '& .MuiInputBase-root.Mui-disabled': { backgroundColor: '#f6f6f6' } }}
        />
      </Grid>

      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text
          name="namaPenjual"
          label="Nama Penjual"
          // disabled={!canModify || isPengganti}
          disabled={!canEditnamaPenjual || isPengganti || isRetur}
          sx={{ '& .MuiInputBase-root.Mui-disabled': { backgroundColor: '#f6f6f6' } }}
        />
      </Grid>
    </Grid>
  );
};

export default InformasiPembeli;
