import Divider from '@mui/material/Divider';
import React, { useEffect } 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 {
  dlkData?: any;
  isLoading?: boolean;
  isRetur?: boolean;
}

const InformasiPembeli: React.FC<InformasiPembeliProps> = ({ dlkData, 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 isEdit = type === 'ubah';
  const canModify = !dlkData || isEdit;

  const canEditNamaPembeli = isRetur || canModify;

  useEffect(() => {
    // 🔒 tunggu kdTransaksi ada
    if (!kdTransaksi) return;

    // ✅ EXPORT → NPWP WAJIB 0000000000000000 (SEMUA MODE)
    if (kdTransaksi === 'EXPORT') {
      setValue('npwpPembeli', '0000000000000000', {
        shouldDirty: false,
        shouldValidate: true,
      });
    }
  }, [kdTransaksi, setValue]);

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

    // NPWP dikunci & diambil dari dokumen asal
    setValue('npwpPembeli', dlkData.npwppembeli ?? '', {
      shouldDirty: false,
      shouldValidate: false,
    });

    // Nama pembeli default dari dokumen asal (masih boleh diedit)
    setValue('namaPembeli', dlkData.namapembeli ?? '', {
      shouldDirty: false,
      shouldValidate: false,
    });
  }, [isRetur, dlkData, 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 Pembeli
        </Divider>
      </Grid>

      {/* IDENTITAS */}

      {/* NPWP*/}
      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text
          name="npwpPembeli"
          label="NPWP Pembeli"
          disabled={!canModify || kdTransaksi === 'EXPORT' || 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('npwpPembeli', value, { shouldDirty: true });
          }}
          sx={{ '& .MuiInputBase-root.Mui-disabled': { backgroundColor: '#f6f6f6' } }}
        />
      </Grid>

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

      {!isRetur && (
        <Grid size={{ md: 12 }}>
          <Field.Text
            name="alamatPembeli"
            label="Alamat Pembeli"
            multiline
            minRows={1}
            disabled={!canModify || isPengganti}
            sx={{ '& .MuiInputBase-root.Mui-disabled': { backgroundColor: '#f6f6f6' } }}
          />
        </Grid>
      )}
    </Grid>
  );
};

export default InformasiPembeli;
