import React, { useEffect, useMemo } from 'react';
import { useForm, FormProvider, useWatch, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import DialogUmum from 'src/shared/components/dialog/DialogUmum';
import DialogContent from '@mui/material/DialogContent';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';

import type {
  TGoods,
  TGoodsResult,
  TSatuanResult,
  TServiceResult,
  TServices,
} from '../../../types/types';

import type { TBarangJasaSchema } from '../../../schemas/detailBarangSchema';
import { BarangJasaSchema } from '../../../schemas/detailBarangSchema';
import Grid from '@mui/material/Grid';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import Divider from '@mui/material/Divider';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';
import { Field, RHFCheckbox } from 'src/components/hook-form';
import MenuItem from '@mui/material/MenuItem';
import type z from 'zod';

/* ===============================
 * CONSTANT DETAIL TRANSAKSI
 * =============================== */
const DETAIL_EKSPOR_BKP_TIDAK_BERWUJUD = 'TD.00312';
const DETAIL_EKSPOR_JKP = 'TD.00313';

interface ModalDetailTransaksiBarangProps {
  payload?: {
    goods?: TGoodsResult;
    services?: TServiceResult;
    satuan?: TSatuanResult;
  };
  isOpen: boolean;
  onClose: () => void;
  detailTransaksi?: string;
  onSave?: (obj: any) => void;
  defaultValues?: TBarangJasaSchema | null;
}

const DEFAULT_FORM: TBarangJasaSchema = {
  type: 'GOODS',
  kdBrgJasa: '',
  namaBrgJasa: '',
  satuanBrgJasa: '',
  jmlBrgJasa: '0',
  hargaSatuan: '0',
  totalHarga: '0',
  diskon: '0',
  fgPmk: '',
  dpp: '0',
  tarifPpn: '0',
  dppLain: '0',
  ppn: '0',
  tarifPpnbm: '0',
  ppnbm: '0',
  cekDppLain: false,
};

const toString = (v: any, fallback = '0') => (v === undefined || v === null ? fallback : String(v));

const normalizeDefaultValues = (src?: any): TBarangJasaSchema => ({
  type: String(src?.type ?? src?.brgJasa ?? 'GOODS'),
  kdBrgJasa: src?.kdBrgJasa ?? src?.kode ?? '',
  namaBrgJasa: src?.namaBrgJasa ?? src?.nama ?? '',
  satuanBrgJasa: src?.satuanBrgJasa ?? src?.satuan ?? '',
  jmlBrgJasa: toString(src?.jmlBrgJasa ?? src?.jumlah ?? '0'),
  hargaSatuan: toString(src?.hargaSatuan ?? src?.harga ?? '0'),
  totalHarga: toString(src?.totalHarga ?? src?.total ?? '0'),
  diskon: toString(src?.diskon ?? '0'),
  fgPmk: src?.fgPmk ?? '',
  dpp: toString(src?.dpp ?? '0'),
  tarifPpn: toString(src?.tarifPpn ?? '0'),
  dppLain: toString(src?.dppLain ?? '0'),
  ppn: toString(src?.ppn ?? '0'),
  tarifPpnbm: toString(src?.tarifPpnbm ?? '0'),
  ppnbm: toString(src?.ppnbm ?? '0'),
  // cekDppLain: Boolean(src?.cekDppLain ?? false),
  cekDppLain: src?.cekDppLain === true,
});

const ModalDetailTransaksiBarang: React.FC<ModalDetailTransaksiBarangProps> = ({
  payload,
  isOpen,
  onClose,
  detailTransaksi = '',
  onSave,
  defaultValues = null,
}) => {
  type FormValues = z.infer<typeof BarangJasaSchema>;

  const methods = useForm<FormValues>({
    mode: 'all',
    resolver: zodResolver(BarangJasaSchema),
    defaultValues: DEFAULT_FORM,
  });

  const { control, setValue, reset, handleSubmit } = methods;

  const type = useWatch({ control, name: 'type' });
  const kdBrgJasa = useWatch({ control, name: 'kdBrgJasa' });
  const jmlBrgJasa = useWatch({ control, name: 'jmlBrgJasa' });
  const hargaSatuan = useWatch({ control, name: 'hargaSatuan' });
  const diskon = useWatch({ control, name: 'diskon' });
  // const fgPmk = useWatch({ control, name: 'fgPmk' });
  const tarifPpnbm = useWatch({ control, name: 'tarifPpnbm' });
  const cekDppLain = useWatch({ control, name: 'cekDppLain' });

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const goods = payload?.goods ?? [];
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const services = payload?.services ?? [];
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const satuan = payload?.satuan ?? [];

  const isEksporBkpTidakBerwujud = detailTransaksi === DETAIL_EKSPOR_BKP_TIDAK_BERWUJUD;
  const isEksporJkp = detailTransaksi === DETAIL_EKSPOR_JKP;

  /* ===============================
   * FORCE TYPE BERDASARKAN TRANSAKSI
   * =============================== */
  useEffect(() => {
    if (!isOpen) return;

    if (isEksporBkpTidakBerwujud) {
      setValue('type', 'GOODS');
    }

    if (isEksporJkp) {
      setValue('type', 'SERVICES');
    }
  }, [isOpen, isEksporBkpTidakBerwujud, isEksporJkp, setValue]);

  /* ===============================
   * RESET ADD / EDIT
   * =============================== */
  useEffect(() => {
    if (!isOpen) return;

    if (defaultValues) {
      // reset(normalizeDefaultValues(defaultValues));
      reset(normalizeDefaultValues(defaultValues), {
        keepDefaultValues: true,
      });
    } else {
      // reset(DEFAULT_FORM);
      reset(DEFAULT_FORM, {
        keepDefaultValues: true,
      });
    }
  }, [isOpen, defaultValues, reset]);

  /* ===============================
   * KODE LIST (ADJUST DI SINI)
   * =============================== */
  type ItemKode = TGoods | TServices;

  const kodeList: ItemKode[] = useMemo(() => {
    if (type === 'GOODS') {
      if (isEksporBkpTidakBerwujud) {
        return goods.slice(-2); // ⬅️ 2 item terakhir
      }
      return goods;
    }
    return services;
  }, [goods, services, type, isEksporBkpTidakBerwujud]);

  const filteredSatuan = useMemo(
    () =>
      satuan.filter((item: any) => {
        const num = Number(String(item.code).split('.')[1]);
        if (type === 'GOODS') return num >= 0 && num <= 22;
        if (type === 'SERVICES') return num >= 23 && num <= 33;
        return true;
      }),
    [satuan, type]
  );

  /* ===============================
   * AUTO FILL NAMA
   * =============================== */
  useEffect(() => {
    if (!kdBrgJasa) return;
    const selected = kodeList.find((it) => String((it as any).code) === String(kdBrgJasa));
    if (selected) {
      setValue('namaBrgJasa', (selected as any).bahasa ?? '');
    }
  }, [kdBrgJasa, kodeList, setValue]);

  /* ===============================
   * AUTO HITUNG (TIDAK DIUBAH)
   * =============================== */
  useEffect(() => {
    const jumlah = Number(jmlBrgJasa || 0);
    const harga = Number(hargaSatuan || 0);
    setValue('totalHarga', String(jumlah * harga));
  }, [jmlBrgJasa, hargaSatuan, setValue]);

  useEffect(() => {
    const jumlah = Number(jmlBrgJasa || 0);
    const harga = Number(hargaSatuan || 0);
    const disc = Number(diskon || 0);
    setValue('dpp', String(jumlah * harga - disc));
  }, [jmlBrgJasa, hargaSatuan, diskon, setValue]);

  useEffect(() => {
    setValue('tarifPpn', '0');
  }, [setValue]);

  useEffect(() => {
    const raw = Number(tarifPpnbm || 0);
    setValue('tarifPpnbm', String(Math.max(0, Math.min(100, Math.round(raw)))));
  }, [tarifPpnbm, setValue]);

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

  // useEffect(() => {
  //   setValue('dppLain', dpp ?? '0', {
  //     shouldDirty: false,
  //     shouldTouch: false,
  //     shouldValidate: false,
  //   });
  // }, [dpp, setValue]);

  useEffect(() => {
    if (cekDppLain) {
      setValue('dppLain', dpp ?? '0', {
        shouldDirty: false,
        shouldTouch: false,
        shouldValidate: false,
      });
    } else {
      setValue('dppLain', '0', {
        shouldDirty: false,
        shouldTouch: false,
        shouldValidate: false,
      });
    }
  }, [cekDppLain, dpp, setValue]);

  useEffect(() => {
    setValue('tarifPpn', '0');
    setValue('ppn', '0');
    setValue('tarifPpnbm', '0');
    setValue('ppnbm', '0');
  }, [setValue]);

  /* ===============================
   * SUBMIT
   * =============================== */
  const onSubmit = (data: TBarangJasaSchema) => {
    onSave?.({
      ...data,
      brgJasa: data.type,
      jmlBrgJasa: Number(data.jmlBrgJasa),
      hargaSatuan: Number(data.hargaSatuan),
      totalHarga: Number(data.totalHarga),
      diskon: Number(data.diskon),
      dpp: Number(data.dpp),
      dppLain: Number(data.dppLain),
      tarifPpn: Number(data.tarifPpn),
      tarifPpnbm: Number(data.tarifPpnbm),
      ppn: Number(data.ppn),
      ppnbm: Number(data.ppnbm),
      // cekDppLain: data.cekDppLain,
      cekDppLain: data.cekDppLain === true,
    });

    reset(DEFAULT_FORM);
  };

  const handleClose = () => {
    reset(DEFAULT_FORM);
    onClose();
  };

  /* ===============================
   * RENDER
   * =============================== */
  return (
    <DialogUmum
      title="Detail Penyerahan Barang/Jasa"
      maxWidth="md"
      isOpen={isOpen}
      onClose={handleClose}
    >
      <FormProvider {...methods}>
        <DialogContent classes={{ root: 'p-16 sm:p-24' }}>
          <Grid container spacing={2}>
            <Grid size={{ md: 12 }}>
              <Divider sx={{ fontWeight: 'bold' }}>Detail Transaksi</Divider>
            </Grid>

            {/* TYPE RADIO */}
            <Grid size={{ md: 4 }}>
              <Controller
                name="type"
                control={control}
                render={({ field }) => (
                  <>
                    <FormLabel sx={{ mb: 1, fontWeight: 600 }}>Type</FormLabel>
                    <RadioGroup row {...field}>
                      {!isEksporJkp && (
                        <FormControlLabel value="GOODS" control={<Radio />} label="Barang" />
                      )}
                      {!isEksporBkpTidakBerwujud && (
                        <FormControlLabel value="SERVICES" control={<Radio />} label="Jasa" />
                      )}
                    </RadioGroup>
                  </>
                )}
              />
            </Grid>

            <Grid size={{ md: 8 }} sx={{ display: 'flex', alignItems: 'end' }}>
              <Field.Select name="kdBrgJasa" label="Kode Barang/Jasa">
                {goods.length === 0 && services.length === 0 ? (
                  <MenuItem disabled>Loading...</MenuItem>
                ) : kodeList.length > 0 ? (
                  kodeList.map((item, idx) => (
                    <MenuItem key={idx} value={(item as any).code}>
                      {`${(item as any).code} - ${(item as any).bahasa}`}
                    </MenuItem>
                  ))
                ) : (
                  <MenuItem disabled value="">
                    Tidak ada data
                  </MenuItem>
                )}
              </Field.Select>
            </Grid>

            <Grid size={{ md: 6 }}>
              <Field.Text name="namaBrgJasa" label="Nama Barang/Jasa" />
            </Grid>

            <Grid size={{ md: 6 }}>
              <Field.Select name="satuanBrgJasa" label="Satuan Barang/Jasa">
                {!satuan.length ? (
                  <MenuItem disabled>Loading...</MenuItem>
                ) : filteredSatuan.length > 0 ? (
                  filteredSatuan.map((item, idx) => (
                    <MenuItem key={idx} value={(item as any).code}>
                      {`${(item as any).code} - ${(item as any).description}`}
                    </MenuItem>
                  ))
                ) : (
                  <MenuItem disabled value="">
                    Tidak ada data
                  </MenuItem>
                )}
              </Field.Select>
            </Grid>

            {/* Nilai Barang */}
            <Grid size={{ md: 6 }}>
              <RHFNumeric
                name="jmlBrgJasa"
                label="Jumlah Barang/Jasa"
                allowDecimalValue
                decimalScale={2}
              />
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric
                name="hargaSatuan"
                label="Harga Satuan (Rp)"
                allowDecimalValue
                decimalScale={2}
              />
            </Grid>

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

            <Grid size={{ md: 6 }}>
              <RHFNumeric name="diskon" label="Diskon (Rp)" allowDecimalValue decimalScale={2} />
            </Grid>

            {/* Divider */}
            <Grid size={{ md: 12 }} sx={{ mt: 3 }}>
              <Divider sx={{ fontWeight: 'bold', fontSize: '1rem', mb: 2 }} textAlign="left">
                PPN
              </Divider>
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric name="dpp" label="DPP (Rp)" allowDecimalValue decimalScale={2} readOnly />
            </Grid>

            <Grid size={{ md: 2 }}>
              <RHFCheckbox name="cekDppLain" label="DPP Nilai Lain" />
            </Grid>

            <Grid size={{ md: 4 }}>
              {/* <RHFNumeric
                name="dppLain"
                label="DPP Nilai Lain (Rp)"
                allowDecimalValue
                decimalScale={2}
                readOnly={detailTransaksi === 'TD.00301' || fgPmk !== '1'}
              /> */}
              <RHFNumeric
                name="dppLain"
                label="DPP Nilai Lain (Rp)"
                allowDecimalValue
                decimalScale={2}
                readOnly={!cekDppLain}
              />
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric name="tarifPpn" label="Tarif PPN %" allowDecimalValue={false} readOnly />
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric name="ppn" label="PPN (Rp)" allowDecimalValue decimalScale={2} readOnly />
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric
                name="tarifPpnbm"
                label="Tarif PPnBM %"
                allowDecimalValue={false}
                readOnly
              />
            </Grid>

            <Grid size={{ md: 6 }}>
              <RHFNumeric
                name="ppnbm"
                label="PPnBM (Rp)"
                allowDecimalValue
                decimalScale={2}
                readOnly
              />
            </Grid>
          </Grid>

          <Box sx={{ display: 'flex', justifyContent: 'right', mt: 3 }}>
            <Button onClick={handleSubmit(onSubmit)} variant="contained">
              Simpan
            </Button>
          </Box>
        </DialogContent>
      </FormProvider>
    </DialogUmum>
  );
};

export default ModalDetailTransaksiBarang;
