import Divider from '@mui/material/Divider';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import MenuItem from '@mui/material/MenuItem';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import React, { useEffect, useRef } from 'react';
import { Controller, useFormContext, useWatch } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import useGetNegara from '../../hooks/useGetNegara';
import { useParams } from 'react-router';
import Grid from '@mui/material/Grid';

interface InformasiPembeliProps {
  fakturData?: any;
  isLoading?: boolean;
}

const InformasiPembeli: React.FC<InformasiPembeliProps> = ({ fakturData, isLoading }) => {
  const { type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();
  const { control, setValue, resetField, getValues, trigger } = useFormContext();
  const { data: country = [] } = useGetNegara();

  const initialIdentitasRef = useRef<string | null>(null);

  const isEdit = type === 'ubah';
  // const isPengganti = type === 'pengganti';

  // const canModify = isEdit || isPengganti;
  const canModify = !fakturData || isEdit;

  // watch fields
  const identitas = useWatch({ control, name: 'idLainPembeli' });
  const npwpPembeli = useWatch({ control, name: 'npwpPembeli' });
  const detailTransaksi = useWatch({ control, name: 'detailTransaksi' });

  const forceNpwpMode = detailTransaksi === 'TD.00302' || detailTransaksi === 'TD.00303';

  useEffect(() => {
    if (forceNpwpMode) {
      const currentIdentitas = getValues('idLainPembeli');
      if (currentIdentitas !== '0') {
        setValue('idLainPembeli', '0', { shouldDirty: true, shouldValidate: true });
      }
      // pastikan negara IDN
      setValue('kdNegaraPembeli', 'IDN', { shouldDirty: true, shouldValidate: true });
      // trigger validation bila perlu
      trigger('kdNegaraPembeli');
    }
  }, [forceNpwpMode, setValue, getValues, trigger]);

  // flag to mark autofill
  const hasFilledRef = useRef(false);

  // AUTOFILL SAAT fakturData MUNCUL
  useEffect(() => {
    if (!fakturData) return;

    // mark filled (do it before/after setValue — both ok)
    hasFilledRef.current = true;

    initialIdentitasRef.current = fakturData.idlainpembeli ?? '0';

    const useNik = fakturData.idlainpembeli === '2' || fakturData.idlainpembeli === '3';

    const mapped = {
      idLainPembeli: fakturData.idlainpembeli ?? '0',
      // npwpPembeli: fakturData.npwppembeli ?? '',
      npwpPembeli: useNik ? (fakturData.nikpasppembeli ?? '') : (fakturData.npwppembeli ?? ''),
      kdNegaraPembeli: fakturData.kdnegarapembeli ?? 'IDN',
      namaPembeli: fakturData.namapembeli ?? '',
      tkuPembeli: fakturData.tkupembeli ?? '',
      emailPembeli: fakturData.emailpembeli ?? '',
      alamatPembeli: fakturData.alamatpembeli ?? '',
    };

    // apply per-field to avoid clobbering entire form
    // Object.entries(mapped).forEach(([key, val]) => {
    //   // don't overwrite if user already edited this field
    //   // NOTE: using setValue with shouldDirty: false to treat this as autofill
    //   setValue(key, val as any, { shouldDirty: false, shouldValidate: false });
    // });

    Object.entries(mapped).forEach(([key, val]) => {
      const shouldValidate = key === 'npwpPembeli';
      setValue(key, val as any, {
        shouldDirty: false,
        shouldValidate,
      });
    });
  }, [fakturData, setValue]);

  useEffect(() => {
    // HANYA mode new yang boleh reset default
    if (type !== 'new') return;

    // masih loading → jangan reset
    if (isLoading) return;

    // sudah autofill (edit/pengganti) → jangan reset
    // if (hasFilledRef.current) return;
    if (hasFilledRef.current && fakturData) {
      // kalau user ganti identitas → tetap reset
      if (identitas === (fakturData?.idlainpembeli ?? '0')) return;
    }

    // kalau form sudah punya value (termasuk dari async source) → jangan reset
    const current = getValues('idLainPembeli');
    if (current !== undefined && current !== null && current !== '') return;

    // apply default
    const defaults = {
      idLainPembeli: '0',
      npwpPembeli: '',
      namaPembeli: '',
      tkuPembeli: '',
      kdNegaraPembeli: 'IDN',
      emailPembeli: '',
      alamatPembeli: '',
    };

    Object.entries(defaults).forEach(([k, v]) =>
      setValue(k, v as any, { shouldDirty: false, shouldValidate: false })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [type, fakturData, isLoading, setValue]);

  useEffect(() => {
    // if (hasFilledRef.current) return;
    if (hasFilledRef.current && identitas === initialIdentitasRef.current) {
      return;
    }
    if (!identitas) return;

    const fields = [
      'npwpPembeli',
      'namaPembeli',
      'kdNegaraPembeli',
      'emailPembeli',
      'alamatPembeli',
      'tkuPembeli',
    ];
    fields.forEach((f) => resetField(f));

    if (identitas === '0' || identitas === '1') {
      // NPWP & NIK → otomatis IDN
      setValue('kdNegaraPembeli', 'IDN', { shouldDirty: true, shouldValidate: true });
      trigger('kdNegaraPembeli'); // 🔥 baru
    } else {
      // Passport / ID Lain → kosong dan wajib diisi user
      setValue('kdNegaraPembeli', '', { shouldDirty: true, shouldValidate: true });
      trigger('kdNegaraPembeli'); // 🔥 baru
    }
  }, [identitas, resetField, setValue, trigger, hasFilledRef]);

  // AUTO GENERATE TKU (ONLY WHEN MANUAL INPUT)
  useEffect(() => {
    if (hasFilledRef.current) return;

    if (!npwpPembeli) {
      setValue('tkuPembeli', '');
      return;
    }

    if (identitas === '0' || identitas === '1') {
      const base = npwpPembeli.replace(/\D/g, '').slice(0, 16);
      setValue('tkuPembeli', `${base.padEnd(16, '0')}000000`.slice(0, 22));
    } else {
      setValue('tkuPembeli', '0'.repeat(22));
    }
  }, [npwpPembeli, identitas, setValue]);

  const labelMap: Record<string, string> = {
    '0': 'NPWP',
    '1': 'NIK',
    '2': 'Passport',
    '3': 'ID Lain',
  };

  const labelPembeli = `${labelMap[identitas as keyof typeof labelMap] ?? 'NIK'} Pembeli`;
  const disabledNegara = identitas === '0' || identitas === '1';

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

      {/* IDENTITAS */}
      <Grid sx={{ mt: 3 }} size={{ md: 6 }}>
        <Controller
          name="idLainPembeli"
          control={control}
          render={({ field }) => (
            <>
              <FormLabel component="legend" sx={{ mb: 1, fontWeight: 600 }}>
                Identitas
              </FormLabel>
              <RadioGroup row {...field}>
                <FormControlLabel
                  value="0"
                  control={<Radio />}
                  label="NPWP"
                  disabled={!canModify}
                />
                <FormControlLabel
                  value="1"
                  control={<Radio />}
                  label="NIK"
                  disabled={!canModify || forceNpwpMode}
                />
                <FormControlLabel
                  value="2"
                  control={<Radio />}
                  label="Passport"
                  disabled={!canModify || forceNpwpMode}
                />
                <FormControlLabel
                  value="3"
                  control={<Radio />}
                  label="ID Lain"
                  disabled={!canModify || forceNpwpMode}
                />
              </RadioGroup>
            </>
          )}
        />
      </Grid>

      {/* NPWP / NIK / ID */}
      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text name="npwpPembeli" label={labelPembeli} disabled={!canModify} />
      </Grid>

      {/* NEGARA */}
      <Grid size={{ md: 6 }}>
        <Field.Select
          name="kdNegaraPembeli"
          label="Kode Negara Pembeli"
          disabled={disabledNegara || !canModify || forceNpwpMode}
        >
          {(country ?? []).map((item) => (
            <MenuItem key={item.kode} value={item.kode}>
              {item.nama}
            </MenuItem>
          ))}
        </Field.Select>
      </Grid>

      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text name="namaPembeli" label="Nama Pembeli" disabled={!canModify} />
      </Grid>

      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text name="tkuPembeli" label="NITKU Pembeli" disabled={!canModify} />
      </Grid>

      <Grid size={{ md: 6 }} sx={{ display: 'flex', alignItems: 'end' }}>
        <Field.Text name="emailPembeli" label="Email" disabled={!canModify} />
      </Grid>

      <Grid size={{ md: 12 }}>
        <Field.Text
          name="alamatPembeli"
          label="Alamat"
          multiline
          minRows={3}
          disabled={!canModify}
        />
      </Grid>
    </Grid>
  );
};

export default InformasiPembeli;
