import React, { useEffect, useRef } from 'react';
import Grid from '@mui/material/Grid';
import Divider from '@mui/material/Divider';
import { useFormContext, useWatch } from 'react-hook-form';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';
import { KD_TRANSAKSI, DETAIL_TRANSAKSI } from '../../constant';
import { useParams } from 'react-router';

interface TotalTransaksiProps {
  dlkData?: any; // data dari API
  isRetur?: boolean;
}

const TotalTransaksi: React.FC<TotalTransaksiProps> = ({ dlkData, isRetur }) => {
  const { control, setValue } = useFormContext<any>();
  const { type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();
  const isEditMode = type === 'ubah' || type === 'pengganti';

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

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

  const maxDpp = Number(dlkData?.returMaxDpp ?? 0);
  const maxPpn = Number(dlkData?.returMaxPpn ?? 0);
  const maxPpnbm = Number(dlkData?.returMaxPpnbm ?? 0);

  const isExport = kdTransaksi === KD_TRANSAKSI.EXPORT;

  const isExportBkpBerwujud = isExport && detailTransaksi === DETAIL_TRANSAKSI.EKSPOR_BERWUJUD;

  const isExportNonBerwujudOrJasa =
    isExport &&
    (detailTransaksi === DETAIL_TRANSAKSI.EKSPOR_TIDAK_BERWUJUD ||
      detailTransaksi === DETAIL_TRANSAKSI.EKSPOR_JASA);

  // Set 0 hanya saat PPN & PPnBM wajib read-only
  useEffect(() => {
    if (isExportBkpBerwujud) {
      setValue('jumlahPpn', 0, { shouldDirty: false });
      setValue('jumlahPpnbm', 0, { shouldDirty: false });
    }
  }, [isExportBkpBerwujud, setValue]);

  useEffect(() => {
    // 🔒 EDIT / PENGGANTI → JANGAN SENTUH NILAI API
    if (isEditMode) return;

    // EXPORT → PPN WAJIB 0
    if (isExport) {
      setValue('jumlahPpn', 0, {
        shouldDirty: false,
        shouldTouch: false,
      });
      return;
    }

    // CREATE → AUTO HITUNG
    const dpp = Number(jumlahDpp || 0);
    const calculatedPpn = +(dpp * 0.12).toFixed(2);

    setValue('jumlahPpn', calculatedPpn, {
      shouldDirty: false,
      shouldTouch: false,
    });
  }, [isEditMode, isExport, jumlahDpp, setValue]);

  console.log('[TotalTransaksi]', {
    type,
    isEditMode,
    jumlahDpp,
  });

  const prevDppRef = useRef<number | null>(null);

  useEffect(() => {
    // log perubahan DPP
    console.log('[dbg] jumlahDpp changed ->', jumlahDpp, 'prev:', prevDppRef.current);
    // show stack trace to see which component triggered re-render (helpful)
    console.trace('[dbg] trace when jumlahDpp changed');
    prevDppRef.current = Number(jumlahDpp || 0);
  }, [jumlahDpp]);

  const dpp = Number(jumlahDpp || 0);
  const ppn = Number(useWatch({ control, name: 'jumlahPpn' }) || 0);
  const ppnbm = Number(useWatch({ control, name: 'jumlahPpnbm' }) || 0);

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

    if (maxDpp && dpp > maxDpp) {
      setValue('jumlahDpp', maxDpp, { shouldDirty: true });
    }

    if (maxPpn && ppn > maxPpn) {
      setValue('jumlahPpn', maxPpn, { shouldDirty: true });
    }

    if (maxPpnbm && ppnbm > maxPpnbm) {
      setValue('jumlahPpnbm', maxPpnbm, { shouldDirty: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isRetur, jumlahDpp, maxDpp, maxPpn, maxPpnbm]);

  const formatRupiah = (val: number) => val.toLocaleString('id-ID');

  if (!isExportNonBerwujudOrJasa) {
    return (
      <Grid container spacing={2} sx={{ mb: 3 }}>
        <Grid size={{ xs: 12 }} sx={{ mt: 3 }}>
          <Divider sx={{ fontWeight: 'bold', fontSize: '1rem', mb: 2 }} textAlign="left">
            Total Transaksi
          </Divider>
        </Grid>

        <Grid size={{ md: 4 }}>
          {/* <RHFNumeric
            name="jumlahDpp"
            label="Jumlah DPP (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={false}
          /> */}
          <RHFNumeric
            name="jumlahDpp"
            label="Jumlah DPP (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={false}
            helperText={isRetur && maxDpp ? `Max Jumlah DPP : ${formatRupiah(maxDpp)}` : ''}
          />
        </Grid>

        <Grid size={{ md: 4 }}>
          {/* <RHFNumeric
            name="jumlahPpn"
            label="Jumlah PPN (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={isExportBkpBerwujud}
            onValueChange={() => {
              setValue('isPpnManual', true, { shouldDirty: false });
            }}
          /> */}
          <RHFNumeric
            name="jumlahPpn"
            label="Jumlah PPN (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={isExportBkpBerwujud}
            helperText={isRetur && maxPpn ? `Max Jumlah PPN : ${formatRupiah(maxPpn)}` : ''}
            onValueChange={() => {
              setValue('isPpnManual', true, { shouldDirty: false });
            }}
          />
        </Grid>

        <Grid size={{ md: 4 }}>
          {/* <RHFNumeric
            name="jumlahPpnbm"
            label="Jumlah PPnBM (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={isExportBkpBerwujud}
          /> */}
          <RHFNumeric
            name="jumlahPpnbm"
            label="Jumlah PPnBM (Rp)"
            allowDecimalValue
            decimalScale={2}
            displayOnly={isExportBkpBerwujud}
            helperText={isRetur && maxPpnbm ? `Max Jumlah PPnBM : ${formatRupiah(maxPpnbm)}` : ''}
          />
        </Grid>
      </Grid>
    );
  }

  /* ======================================================
   * LAYOUT LENGKAP
   * EXPORT + (NON BERWUJUD | JASA)
   ====================================================== */
  return (
    <Grid container spacing={2} sx={{ mb: 3 }}>
      <Grid size={{ xs: 12 }} sx={{ mt: 3 }}>
        <Divider sx={{ fontWeight: 'bold', fontSize: '1rem', mb: 2 }} textAlign="left">
          Total Transaksi
        </Divider>
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric
          name="totalJumlahBarang"
          label="Total Jumlah Barang"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric
          name="totalHarga"
          label="Total Harga (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>

      <Grid size={{ md: 4 }}>
        <RHFNumeric
          name="totalDiskon"
          label="Total Diskon (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>

      <Grid size={{ md: 3 }}>
        <RHFNumeric
          name="jumlahDpp"
          label="Jumlah DPP (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>

      <Grid size={{ md: 3 }}>
        <RHFNumeric
          name="jumlahDppLain"
          label="Jumlah DPP Lain (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>

      <Grid size={{ md: 3 }}>
        <RHFNumeric
          name="jumlahPpn"
          label="Jumlah PPN (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
          onValueChange={() => {
            setValue('isPpnManual', true, { shouldDirty: false });
          }}
        />
      </Grid>

      <Grid size={{ md: 3 }}>
        <RHFNumeric
          name="jumlahPpnbm"
          label="Jumlah PPnBM (Rp)"
          allowDecimalValue
          decimalScale={2}
          displayOnly
        />
      </Grid>
    </Grid>
  );
};

export default TotalTransaksi;
