import React, { useEffect, useMemo, useState } from 'react';
import Box from '@mui/material/Box';
import { DataGridPremium, useGridApiRef } from '@mui/x-data-grid-premium';
import Stack from '@mui/material/Stack';
import type { GridColDef } from 'node_modules/@mui/x-data-grid/esm/models/colDef/gridColDef';
import IconButton from '@mui/material/IconButton';
import Grid from '@mui/material/Grid';
import Divider from '@mui/material/Divider';
import Button from '@mui/material/Button';
import { Delete, Edit } from '@mui/icons-material';
import { useFormContext, useWatch } from 'react-hook-form';
import { useParams } from 'react-router';

import ModalDetailTransaksiBarang from './dialog/ModalDetailTransaksiBarang';
import ModalDeleteBarangJasa from './dialog/ModalDeleteBarangJasa';
import useGetGoods from '../../hooks/useGetGoods';
import useGetServices from '../../hooks/useGetServices';
import useGetSatuan from '../../hooks/useGetSatuan';
import CustomNoRowsOverlay from './NoRowsOverlay';

const rupiahFormat = (value: any) => new Intl.NumberFormat('id-ID', {}).format(Number(value));

export type IColumnGrid = GridColDef & {
  field:
    | 'actions'
    | 'brgJasa'
    | 'namaBrgJasa'
    | 'kdBrgJasa'
    | 'jmlBrgJasa'
    | 'satuanBrgJasa'
    | 'hargaSatuan'
    | 'totalHarga'
    | 'diskon'
    | 'dpp'
    | 'dppLain'
    | 'ppn'
    | 'ppnbm'
    | 'tarifPpnbm';
};

type Props = {
  fakturData?: any | null;
  isLoading?: boolean;
};

const DetailTransaksi: React.FC<Props> = ({ fakturData = null, isLoading = false }) => {
  const { type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();
  const apiRef = useGridApiRef();
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [isOpenDelete, setIsOpenDelete] = useState(false);
  const [deleteId, setDeleteId] = useState<string | null>(null);

  const goodsQuery = useGetGoods();
  const servicesQuery = useGetServices();
  const satuanQuery = useGetSatuan();

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

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

  // data table
  const [rows, setRows] = useState<any[]>([]);
  const [editRow, setEditRow] = useState<any | null>(null);

  const { control, setValue, getValues } = useFormContext();
  const detailTransaksi = useWatch({ control, name: 'detailTransaksi' });

  const isOptionsReady = goodsQuery.isSuccess && servicesQuery.isSuccess && satuanQuery.isSuccess;
  // const isReady = goodsQuery.isSuccess && servicesQuery.isSuccess && satuanQuery.isSuccess;

  // const canEditRows = !isLoading && (!fakturData || isEdit);

  const handleAdd = () => {
    setEditRow(null); // Pastikan kosong
    setOpenModal(true);
  };

  // open modal edit
  const handleEdit = (params: any) => {
    // if (fakturData) return; // disable edit when faktur valid
    if (!canModify) return;
    // if (!isReady) return;

    console.log('ke klik');
    setEditRow(params.row);
    setOpenModal(true);
  };

  // open modal delete
  const handleDeleteClick = (params: any) => {
    // if (fakturData) return; // disable delete when faktur valid
    if (!canModify) return;
    setDeleteId(params.row.id);
    setIsOpenDelete(true);
  };

  // delete data setelah confirm
  const handleConfirmDelete = () => {
    if (deleteId) {
      setRows((prev) => prev.filter((r) => r.id !== deleteId));
      setDeleteId(null);
    }
  };

  const columns = useMemo<IColumnGrid[]>(
    () => [
      {
        field: 'actions',
        type: 'actions',
        headerName: 'Aksi',
        headerAlign: 'center',
        align: 'center',
        minWidth: 150,
        renderCell: (params) => (
          <Stack direction="row" gap={2}>
            <IconButton
              onClick={() => handleDeleteClick(params)}
              // disabled={!!fakturData}
              disabled={!canModify}
            >
              <Delete />
            </IconButton>
            <IconButton
              onClick={() => handleEdit(params)}
              // disabled={!!fakturData}
              disabled={!canModify}
            >
              <Edit />
            </IconButton>
          </Stack>
        ),
      },
      {
        field: 'brgJasa',
        headerName: 'Type',
        minWidth: 200,
      },
      {
        field: 'namaBrgJasa',
        headerName: 'Nama',
        minWidth: 200,
      },
      {
        field: 'kdBrgJasa',
        headerName: 'Kode',
        minWidth: 200,
      },
      {
        field: 'jmlBrgJasa',
        headerName: 'Jumlah Barang',
        minWidth: 200,
      },
      {
        field: 'satuanBrgJasa',
        headerName: 'Satuan Barang/Jasa',
        minWidth: 200,
      },
      {
        field: 'hargaSatuan',
        headerName: 'Harga Satuan (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
      {
        field: 'totalHarga',
        headerName: 'Jumlah Total (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
      {
        field: 'diskon',
        headerName: 'Diskon (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
      {
        field: 'dpp',
        headerName: 'DPP (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params.value)}</>,
      },
      {
        field: 'dppLain',
        headerName: 'DPP Nilai Lain (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params.value)}</>,
      },
      {
        field: 'ppn',
        headerName: 'PPN (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
      {
        field: 'ppnbm',
        headerName: 'PPnBM (Rp)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
      {
        field: 'tarifPpnbm',
        headerName: 'Tarif PPnBM (%)',
        minWidth: 200,
        renderCell: (params) => <>{rupiahFormat(params?.value)}</>,
      },
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [fakturData]
  );

  const handleSaveFromModal = (entry: any) => {
    if (editRow) {
      // mode edit
      setRows((prev) => prev.map((row) => (row.id === editRow.id ? { ...row, ...entry } : row)));
      setEditRow(null);
    } else {
      // mode tambah baru
      const id = String(Date.now());
      setRows((prev) => [...prev, { id, ...entry }]);
    }
    setOpenModal(false);
  };

  // Sync totals -> setValue (existing effect)
  useEffect(() => {
    const totalJumlahBarangRaw = rows.reduce((sum, r) => sum + (Number(r.jmlBrgJasa) || 0), 0);
    const totalHargaRaw = rows.reduce((sum, r) => sum + (Number(r.totalHarga) || 0), 0);
    const totalDiskonRaw = rows.reduce((sum, r) => sum + (Number(r.diskon) || 0), 0);
    const totalDppRaw = rows.reduce((sum, r) => sum + (Number(r.dpp) || 0), 0);
    const totalDppLainRaw = rows.reduce((sum, r) => sum + (Number(r.dppLain) || 0), 0);
    const totalPpnRaw = rows.reduce((sum, r) => sum + (Number(r.ppn) || 0), 0);
    const totalPpnbmRaw = rows.reduce((sum, r) => sum + (Number(r.ppnbm) || 0), 0);

    const totalJumlahBarang = Math.round(totalJumlahBarangRaw);
    const totalHarga = Math.round(totalHargaRaw);
    const totalDiskon = Math.round(totalDiskonRaw);
    const totalDpp = Math.round(totalDppRaw);
    const totalDppLain = Math.round(totalDppLainRaw);
    const totalPpn = Math.round(totalPpnRaw);
    const totalPpnbm = Math.round(totalPpnbmRaw);

    setValue('objekFaktur', rows);
    setValue('totalJumlahBarang', totalJumlahBarang);
    setValue('totalHarga', totalHarga);
    setValue('totalDiskon', totalDiskon);
    setValue('totalDpp', totalDpp);
    setValue('totalDppLain', totalDppLain);
    setValue('totalPpn', totalPpn);
    setValue('totalPpnbm', totalPpnbm);
  }, [rows, setValue]);

  // Sync rows from fakturData.objekFaktur
  useEffect(() => {
    if (fakturData && Array.isArray(fakturData.objekFaktur) && fakturData.objekFaktur.length > 0) {
      const mapped = fakturData.objekFaktur.map((it: any, idx: number) => {
        // safe map & cast numeric fields
        const num = (v: any) => {
          if (v === null || v === undefined || v === '') return 0;
          const n = Number(String(v).replace(/,/g, ''));
          return Number.isFinite(n) ? n : 0;
        };
        return {
          id: String(it.id ?? `${Date.now()}-${idx}`),
          brgJasa: it.brgJasa ?? it.type ?? '',
          namaBrgJasa: it.namaBrgJasa ?? it.nama ?? '',
          kdBrgJasa: it.kdBrgJasa ?? it.kode ?? '',
          jmlBrgJasa: num(it.jmlBrgJasa),
          satuanBrgJasa: it.satuanBrgJasa ?? it.satuan ?? '',
          hargaSatuan: num(it.hargaSatuan),
          totalHarga: num(it.totalHarga),
          diskon: num(it.diskon),
          dpp: num(it.dpp),
          dppLain: num(it.dppLain),
          ppn: num(it.ppn),
          ppnbm: num(it.ppnbm),
          tarifPpn: num(it.tarifPpn),
          tarifPpnbm: num(it.tarifPpnbm),
          cekDppLain: it.cekDppLain ?? false,
        };
      });
      setRows(mapped);
      setValue('objekFaktur', mapped, { shouldDirty: false, shouldValidate: false });

      return;
    }

    if (!fakturData) {
      const existing = getValues('objekFaktur');
      if (!existing || existing.length === 0) {
        setRows([]);
      }
    }
  }, [fakturData, setValue, getValues]);

  console.log(rows);

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

      <Box sx={{ width: '100%', display: 'flex', justifyContent: 'end' }}>
        <Button
          sx={{
            background: '#143B88',
            color: '#fff',
            mb: 3,
            '&:hover': {
              background: '#0F2F6A',
              boxShadow: 'none',
              transform: 'none',
            },
          }}
          onClick={() => {
            // if (fakturData) return;
            if (!canModify) return;
            handleAdd(); // GUNAKAN INI
          }}
          variant="outlined"
          // disabled={!isOptionsReady || !!fakturData || isLoading}
          disabled={!isOptionsReady || isLoading || !canModify}
        >
          Rekam Transaksi
        </Button>
      </Box>

      <DataGridPremium
        columns={columns}
        apiRef={apiRef}
        rows={rows}
        initialState={{
          pinnedColumns: {
            left: ['actions'],
          },
        }}
        slots={{
          // eslint-disable-next-line react/jsx-no-useless-fragment
          toolbar: () => <></>, // hilangkan toolbar filter/export
          noRowsOverlay: CustomNoRowsOverlay,
        }}
        sx={{
          border: 1,
          borderColor: 'divider',
          borderRadius: 2,
          mt: 3,
          minHeight: 350,
          '& .MuiDataGrid-cell': {
            borderColor: 'divider',
            userSelect: 'text',
            cursor: 'text',
          },
          '& .MuiDataGrid-columnHeaders': { borderColor: 'divider' },
        }}
        disableVirtualization
      />

      <ModalDetailTransaksiBarang
        key={`${editRow ? 'edit' : 'add'}-${goodsQuery.data?.length}-${servicesQuery.data?.length}-${satuanQuery.data?.length}`}
        isOpen={openModal}
        onClose={() => setOpenModal(false)}
        payload={{
          goods: goodsQuery.data,
          services: servicesQuery.data,
          satuan: satuanQuery.data,
        }}
        detailTransaksi={detailTransaksi}
        onSave={(obj) => handleSaveFromModal(obj)}
        defaultValues={editRow ?? undefined}
      />

      {/* Modal Delete */}
      <ModalDeleteBarangJasa
        isOpenDialogDelete={isOpenDelete}
        setIsOpenDialogDelete={setIsOpenDelete}
        dataSelected={
          deleteId
            ? { type: 'include', ids: new Set([deleteId]) }
            : { type: 'include', ids: new Set() }
        }
        onConfirmDelete={handleConfirmDelete}
      />
    </>
  );
};

export default DetailTransaksi;
