import Button from '@mui/material/Button';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { Link as RouterLink } from 'react-router-dom';
import { paths } from 'src/routes/paths';
import React, { useCallback, useEffect, useMemo, useRef, useState, startTransition } from 'react';
import { useNavigate } from 'react-router';
import type {
  GridColDef,
  GridFilterModel,
  GridRowSelectionModel,
  GridSortModel,
  GridToolbarProps,
  GridPaginationModel,
} from '@mui/x-data-grid-premium';
import { DataGridPremium, useGridApiRef } from '@mui/x-data-grid-premium';
import { unstable_batchedUpdates } from 'react-dom';
import { LoadingButton } from '@mui/lab';
import {
  ArticleTwoTone,
  AutorenewTwoTone,
  DeleteSweepTwoTone,
  EditNoteTwoTone,
  HighlightOffTwoTone,
  UploadFileTwoTone,
  SwapHorizontalCircleTwoTone,
  SearchRounded,
  PlaylistAddCheckTwoTone,
  PlaylistRemoveTwoTone,
} from '@mui/icons-material';
import { Controller, FormProvider, useForm } from 'react-hook-form';
import { DateRangePicker, LocalizationProvider } from '@mui/x-date-pickers-pro';
import { enqueueSnackbar } from 'notistack';
import { usePaginationStore } from '../store/paginationStore';
import StatusChip from '../components/StatusChip';
import { useDebounce, useThrottle } from 'src/shared/hooks/useDebounceThrottle';
import useAdvancedFilter from '../hooks/useAdvancedFilterFakturPK';
import { CustomToolbar } from '../components/CustomToolbar';
import { formatDateToDDMMYYYY, useGetDokumenLainMasukan } from '../hooks/useGetDokumenLainMasukan';
import { formatRupiah } from 'src/shared/FormatRupiah/FormatRupiah';
import {
  DETAIL_TRANSAKSI_TEXT,
  DOKUMEN_TRANSAKSI_TEXT,
  KD_TRANSAKSI_TEXT,
  KODE_DOKUMEN_TEXT,
} from '../constant';
import ModalUploadDokumenLainKeluaran from '../components/dialog/ModalUploadDokumenLainMasukan';
import ModalDeleteDokumenLainKeluaran from '../components/dialog/ModalDeleteDokumenLainMasukan';
import { STATUS_OPTIONS } from '../constant/statusOptions';
import { TRANSAKSI_CODE_OPTIONS } from '../constant/detailTransaksiOptions';
import { DETAIL_TRANSAKSI_OPTIONS } from '../constant/transaksiCodeOptions';
import { DOKUMEN_TRANSAKSI_OPTIONS } from '../constant/dokumenTransaksiOptions';
import { KODE_DOKUMEN_OPTIONS } from '../constant/kodeDokumenOptions';
import { mapValue } from '../utils/gridFormatter';
import { Field } from 'src/components/hook-form';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import dayjs from 'dayjs';
import { AdapterDayjs } from '@mui/x-date-pickers-pro/AdapterDayjs';
import type { Dayjs } from 'dayjs';
import ModalCetakDokumenLainMasukan from '../components/dialog/ModalCetakDokumenLainMasukan';
import ModalCancelDokumenLainMasukan from '../components/dialog/ModalCancelDokumenLainMasukan';
import ModalPrepolulatedDokumenLainMasukan from '../components/dialog/ModalPrepopulatedDokumenLainMasukan';
import ModalReturDokumenLainMasukan from '../components/dialog/ModalReturDokumenLainMasukan';
import ModalUploadCreditedDokumenLainMasukan from '../components/dialog/ModalUploadCreditedDokumenLainMasukan';

// import ModalReturDokumenLainKeluaran from '../components/dialog/ModalReturDokumenLainKeluaran';

export type IColumnGrid = GridColDef & {
  field:
    | 'statusdokumen'
    | 'nomordokumen'
    | 'kdtransaksi'
    | 'detailtransaksi'
    | 'dokumentransaksi'
    | 'kodedokumen'
    | 'tanggaldokumen'
    | 'nomordokumendiganti'
    | 'npwppembeli'
    | 'masapajak'
    | 'tahunpajak'
    | 'masacredit'
    | 'tahuncredit'
    | 'jumlahdpp'
    | 'jumlahppn'
    | 'jumlahppnbm'
    | 'namapenjual'
    | 'tanggalapproval'
    | 'keterangantambahan'
    | 'namapenandatangan'
    | 'kodeapproval'
    | 'referensi'
    | 'created_by'
    | 'created_at'
    | 'updated_by'
    | 'npwppenjual'
    | 'updated_at';
  // valueOptions?: string[];
  valueOptions?: readonly (string | number | { value: string | number; label: string })[];
};

type FilterType = 'all' | 'nomordokumen' | 'npwp' | 'periode' | 'customDate';

interface FormValues {
  filter: FilterType;
  periode: string | null;

  kataKunci?: [Dayjs | null, Dayjs | null];

  nomordokumen: string;
  npwp: string;
  all: string;
}
type TPengkreditan = 'CREDITED' | 'UNCREDITED' | 'INVALID';

export function DlmListView() {
  const apiRef = useGridApiRef();
  const navigate = useNavigate();

  const tableKey = 'faktur-pk';

  const { tables, filters, setPagination, resetPagination, setFilter } =
    usePaginationStore.getState();

  const [filterModel, setFilterModel] = useState<GridFilterModel>({
    items: filters[tableKey]?.items ?? [],
  });

  const [sortModel, setSortModel] = useState<GridSortModel>([]);
  const [rowSelectionModel, setRowSelectionModel] = useState<GridRowSelectionModel | undefined>(
    undefined
  );

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState<boolean>(false);
  const [isUploadModalOpenCredit, setIsUploadModalOpenCredit] = useState<boolean>(false);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState<boolean>(false);
  const [isPrepopulatedOpen, setIsPrepopulatedOpen] = useState(false);

  const [isReturOpen, setIsReturOpen] = useState(false);
  const [isPreviewOpen, setIsPreviewOpen] = useState<boolean>(false);
  const [previewPayload, setPreviewPayload] = useState<Record<string, any> | undefined>(undefined);

  const [requestParams, setRequestParams] = useState<any>(null);
  const [statusPengkreditan, setStatusPengkreditan] = useState<TPengkreditan>('CREDITED');

  const dataSelectedRef = useRef<any[]>([]);
  const [selectionVersion, setSelectionVersion] = useState(0);
  const [localPagination, setLocalPagination] = useState({
    page: tables[tableKey]?.page ?? 0,
    pageSize: tables[tableKey]?.pageSize ?? 10,
  });

  const { buildAdvancedFilter, buildRequestParams } = useAdvancedFilter();

  const page = tables[tableKey]?.page ?? 0;
  const pageSize = tables[tableKey]?.pageSize ?? 10;

  const isSyncingRef = useRef(false);
  const isEqual = (a: any, b: any) => a === b || JSON.stringify(a) === JSON.stringify(b);

  const methods = useForm<FormValues>({
    defaultValues: {
      filter: 'all',
      periode: null,
      nomordokumen: '',
      npwp: '',
    },
  });

  const { watch } = methods;
  const selectedFilter = watch('filter');

  useEffect(() => {
    const unsub = usePaginationStore.subscribe((state) => {
      const newStoreItems = state.filters[tableKey]?.items ?? [];
      const localItems = filterModel.items ?? [];

      if (!isEqual(newStoreItems, localItems)) {
        isSyncingRef.current = true;
        setFilterModel({ items: newStoreItems });
        queueMicrotask(() => (isSyncingRef.current = false));
      }
    });

    return () => unsub();
  }, [filterModel.items]);

  useEffect(() => {
    const unsub = usePaginationStore.subscribe((state) => {
      const storePage = state.tables[tableKey]?.page ?? 0;
      const storePageSize = state.tables[tableKey]?.pageSize ?? 10;

      setLocalPagination((prev) =>
        prev.page !== storePage || prev.pageSize !== storePageSize
          ? { page: storePage, pageSize: storePageSize }
          : prev
      );
    });
    return () => unsub();
  }, []);

  useEffect(() => {
    if (isSyncingRef.current) return;
    const currentStore = usePaginationStore.getState().filters[tableKey]?.items ?? [];
    if (!isEqual(currentStore, filterModel.items)) {
      setFilter(tableKey, { items: filterModel.items });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterModel]);

  const params = useMemo(() => {
    const advanced = buildAdvancedFilter(filterModel.items);

    return buildRequestParams(
      {
        page,
        limit: pageSize,
        sortingMode: sortModel[0]?.field ?? '',
        sortingMethod: sortModel[0]?.sort ?? '',
        ...requestParams,
      },
      advanced
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    page,
    pageSize,
    sortModel,
    filterModel.items,
    requestParams, // ⬅️ WAJIB
  ]);

  const { data, isFetching, refetch } = useGetDokumenLainMasukan({
    params,
  });
  const idStatusMapRef = useRef<Map<string | number, string>>(new Map());
  const rows = useMemo(() => (data?.data || []).filter(Boolean), [data?.data]);
  const totalRows = Number(data?.total ?? 0);

  useEffect(() => {
    try {
      const m = new Map<string | number, string>();
      (rows || []).forEach((r: any) => {
        const id = String(r.id ?? r.internal_id ?? '');
        m.set(id, r?.fgStatus ?? '');
      });
      idStatusMapRef.current = m;
    } catch {
      idStatusMapRef.current = new Map();
    }
  }, [rows]);

  const handlePaginationChange = (model: GridPaginationModel) => {
    setLocalPagination(model);
    setPagination(tableKey, {
      page: model.page,
      pageSize: model.pageSize,
    });
  };

  const debouncedFilterChange = useDebounce((model: GridFilterModel) => {
    setFilterModel(model);
  }, 400);

  const debouncedSortChange = useDebounce((model: GridSortModel) => {
    setSortModel(model);
    resetPagination(tableKey);
  }, 400);

  const columns = useMemo<IColumnGrid[]>(
    () => [
      {
        field: 'statusdokumen',
        headerName: 'Status',
        width: 300,
        type: 'singleSelect',
        valueOptions: STATUS_OPTIONS.map((o) => o.value),
        valueFormatter: mapValue(STATUS_OPTIONS),
        renderCell: (value) => (
          <StatusChip
            value={value?.value}
            fgpelunasan={value?.row?.fgpelunasan}
            fguangmuka={value?.row?.fguangmuka}
            fgpengganti={value?.row?.fgpengganti}
            credit={value.row.statuspembeli}
          />
        ),
      },
      { field: 'nomordokumen', headerName: 'Nomor Dokumen', width: 150 },
      {
        field: 'kdtransaksi',
        headerName: 'Kode Transaksi',
        width: 150,
        valueOptions: TRANSAKSI_CODE_OPTIONS.map((o) => o.value),
        valueFormatter: mapValue(TRANSAKSI_CODE_OPTIONS),
        renderCell: (value) => KD_TRANSAKSI_TEXT[value?.value] ?? value?.value ?? '-',
      },

      {
        field: 'detailtransaksi',
        headerName: 'Detail Transaksi',
        width: 150,
        valueOptions: DETAIL_TRANSAKSI_OPTIONS.map((o) => o.value),
        valueFormatter: mapValue(DETAIL_TRANSAKSI_OPTIONS),
        renderCell: (value) => DETAIL_TRANSAKSI_TEXT[value?.value] ?? value?.value ?? '-',
      },
      {
        field: 'dokumentransaksi',
        headerName: 'Dokumen Transaksi',
        width: 150,
        valueOptions: DOKUMEN_TRANSAKSI_OPTIONS.map((o) => o.value),
        valueFormatter: mapValue(DOKUMEN_TRANSAKSI_OPTIONS),
        renderCell: (value) => DOKUMEN_TRANSAKSI_TEXT[value?.value] ?? value?.value ?? '-',
      },
      {
        field: 'kodedokumen',
        headerName: 'Kode Dokumen',
        width: 150,
        valueOptions: KODE_DOKUMEN_OPTIONS.map((opt) => opt.value),
        valueFormatter: mapValue(KODE_DOKUMEN_OPTIONS),
        renderCell: (value) => KODE_DOKUMEN_TEXT[value?.value] ?? value?.value ?? '-',
      },
      {
        field: 'tanggaldokumen',
        headerName: 'Tanggal Dokumen',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.tanggaldokumen),
      },
      {
        field: 'nomordokumendiganti',
        headerName: 'Nomor Dokumen Diganti',
        width: 150,
      },
      {
        field: 'masapajak',
        headerName: 'Masa Pajak',
        width: 100,
      },
      {
        field: 'tahunpajak',
        headerName: 'Tahun Pajak',
        width: 100,
      },
      {
        field: 'masacredit',
        headerName: 'Masa Pengkreditan',
        width: 100,
      },
      {
        field: 'tahuncredit',
        headerName: 'Tahun Pengkreditan',
        width: 100,
      },
      {
        field: 'jumlahdpp',
        headerName: 'DPP',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.jumlahdpp),
      },
      {
        field: 'jumlahppn',
        headerName: 'PPN',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.jumlahppn),
      },
      {
        field: 'jumlahppnbm',
        headerName: 'PPnBM',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.jumlahppnbm),
      },
      {
        field: 'namapenjual',
        headerName: 'Nama Penjual',
        width: 150,
      },
      {
        field: 'npwppenjual',
        headerName: 'NPWP Penjual',
        width: 150,
      },

      {
        field: 'npwppembeli',
        headerName: 'NPWP',
        width: 150,
      },
      {
        field: 'kodeapproval',
        headerName: 'Kode Approval',
        width: 150,
      },

      {
        field: 'tanggalapproval',
        headerName: 'Tanggal Approval',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.tanggalapproval),
      },
      { field: 'namapenandatangan', headerName: 'Penandatangan', width: 150 },
      { field: 'referensi', headerName: 'Referensi', width: 150 },
      { field: 'keterangantambahan', headerName: 'Keterangan', width: 150 },
      {
        field: 'created_at',
        headerName: 'Tanggal Rekam',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.created_at),
      },
      { field: 'created_by', headerName: 'User Perekam', width: 150 },
      {
        field: 'updated_at',
        headerName: 'Tanggal Ubah',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.updated_at),
      },
      { field: 'updated_by', headerName: 'User Pengubah', width: 150 },
    ],
    []
  );

  const handleNavigateBySelection = useCallback(
    (type: 'ubah' | 'retur' | 'pengganti') => {
      const selectedRow = dataSelectedRef.current[0];
      if (!selectedRow) return;

      navigate(`/faktur/dokumen-lain/pajak-masukan/${selectedRow.id}/${type}`);
    },
    [navigate]
  );

  const throttledSelectionChange = useThrottle((newSelection: any) => {
    if (!apiRef.current) return;
    const ids =
      newSelection?.ids instanceof Set ? Array.from(newSelection.ids) : newSelection || [];
    const selectedData = ids.map((id: any) => apiRef.current!.getRow(id)).filter(Boolean);

    unstable_batchedUpdates(() => {
      dataSelectedRef.current = selectedData;
      setRowSelectionModel(newSelection);
      setSelectionVersion((v) => v + 1);
    });
  }, 150);

  useEffect(() => {
    const api = apiRef.current;
    if (!api) return;
    const unsubscribe = api.subscribeEvent('rowsSet', () => {
      const exec = () => {
        const ids =
          api.state?.rowSelection?.ids instanceof Set ? Array.from(api.state.rowSelection.ids) : [];
        const updatedSelected = ids.map((id) => api.getRow(id)).filter(Boolean);
        dataSelectedRef.current = updatedSelected;
        setSelectionVersion((v) => v + 1);
      };
      if ((window as any).requestIdleCallback) (window as any).requestIdleCallback(exec);
      else setTimeout(exec, 0);
    });
    // eslint-disable-next-line consistent-return
    return () => unsubscribe();
  }, [apiRef]);

  const validatedActions = useMemo(() => {
    const dataSelected = dataSelectedRef.current;
    const count = dataSelected.length;
    const hasSelection = count > 0;

    if (!hasSelection) {
      return {
        canDetail: false,
        canEdit: false,
        canDelete: false,
        canUpload: false,
        canReplacement: false,
        canCancel: false,
        canRetur: false,
      };
    }

    const allDraft = dataSelected.every((d) => d.statusdokumen === 'DRAFT');
    const allApproved = dataSelected.every((d) => d.statusdokumen === 'APPROVED');

    const item = dataSelected[0];

    const isSingle = count === 1;
    const isSingleReplacement = isSingle && item.statusdokumen === 'APPROVED';

    // ✅ RULE RETUR
    const canRetur =
      isSingle && item.kdtransaksi === 'PURCHASE' && ['APPROVED'].includes(item.statusdokumen);

    return {
      canDetail: isSingle,
      canEdit: isSingle && allDraft,
      canDelete: hasSelection && allDraft,
      canUpload: hasSelection && allDraft,
      canReplacement: isSingleReplacement,
      canCancel: hasSelection && allApproved,
      canCredit: hasSelection && allApproved,
      canRetur,
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectionVersion]);

  const handleOpenPreview = () => {
    const selectedRow = dataSelectedRef.current?.[0];
    if (!selectedRow) {
      enqueueSnackbar('Pilih 1 baris untuk melihat detail', { variant: 'warning' });
      return;
    }

    console.log(selectedRow);

    setPreviewPayload(selectedRow);
    setIsPreviewOpen(true);
  };

  const actions = useMemo(
    () => [
      [
        {
          title: 'Refresh List',
          icon: <AutorenewTwoTone sx={{ width: 26, height: 26 }} />,
          func: () =>
            startTransition(() => {
              resetPagination(tableKey);
              void refetch();
            }),
        },
        {
          title: 'Edit',
          icon: <EditNoteTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => handleNavigateBySelection('ubah'),
          disabled: !validatedActions.canEdit,
        },
        {
          title: 'Detail',
          icon: <ArticleTwoTone sx={{ width: 26, height: 26 }} />,
          func: handleOpenPreview,
          disabled: !validatedActions.canDetail,
        },
        {
          title: 'Hapus',
          icon: <DeleteSweepTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsDeleteModalOpen(true),
          disabled: !validatedActions.canDelete,
        },
      ],
      [
        {
          title: 'Upload',
          icon: <UploadFileTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsUploadModalOpen(true),
          disabled: !validatedActions.canUpload,
        },
        // {
        //   title: 'Pengganti',
        //   icon: <FileOpenTwoTone sx={{ width: 26, height: 26 }} />,
        //   func: () => handleNavigateBySelection('pengganti'),
        //   disabled: !validatedActions.canReplacement,
        // },
        {
          title: 'Batal',
          icon: <HighlightOffTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsCancelModalOpen(true),
          disabled: !validatedActions.canCancel,
        },
        {
          title: 'Retur',
          icon: <SwapHorizontalCircleTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => handleNavigateBySelection('retur'),
          disabled: !validatedActions.canRetur,
        },
      ],
      [
        {
          title: 'Credit',
          icon: <PlaylistAddCheckTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => {
            setStatusPengkreditan('CREDITED');
            setIsUploadModalOpenCredit(true);
          },
          disabled: !validatedActions.canCredit,
        },
        {
          title: 'Uncredit',
          icon: <PlaylistRemoveTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => {
            setStatusPengkreditan('UNCREDITED');
            setIsUploadModalOpenCredit(true);
          },
          disabled: !validatedActions.canCredit,
        },
        // {
        //   title: 'Invalid',
        //   icon: <RemoveCircleTwoTone sx={{ width: 26, height: 26 }} />,
        //   func: () => {
        //     setStatusPengkreditan('INVALID');
        //     setIsUploadModalOpen(true);
        //   },
        //   disabled: !validatedActions.canCredit,
        // },
      ],
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [validatedActions, refetch, handleNavigateBySelection]
  );

  const pinnedColumns = useMemo(
    () => ({ left: ['__check__', 'statusdokumen', 'nomordokumen'] }),
    []
  );

  const ToolbarWrapper: React.FC<GridToolbarProps> = useCallback(
    (gridToolbarProps) => (
      <CustomToolbar
        actions={actions}
        columns={columns}
        filterModel={filterModel}
        setFilterModel={setFilterModel}
        statusOptions={STATUS_OPTIONS}
        {...gridToolbarProps}
      />
    ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [actions, columns, filterModel, setFilterModel, STATUS_OPTIONS]
  );

  const onSubmit = (values: FormValues) => {
    const nextParams: any = {};

    if (values.filter === 'periode' && values.periode) {
      const d = dayjs(values.periode);
      nextParams.periode = JSON.stringify(d.toISOString());
      nextParams.periode = d.format('MM/YYYY');
    }

    if (values.filter === 'nomordokumen' && values.nomordokumen) {
      nextParams.nomordokumen = values.nomordokumen.trim();
    }

    if (values.filter === 'npwp' && values.npwp) {
      nextParams.npwp = values.npwp.trim();
    }

    if (values.filter === 'all' && values.all) {
      nextParams.all = values.all.trim();
    }

    if (values.filter === 'customDate' && values.kataKunci) {
      const [start, end] = values.kataKunci;

      if (start && end) {
        nextParams.startDate = start.startOf('day').toISOString();
        nextParams.endDate = end.endOf('day').toISOString();

        nextParams.tglAwal = start.format('YYYY-MM-DD');
        nextParams.tglAkhir = end.format('YYYY-MM-DD');
      }
    }

    // ⬅️ URUTAN PENTING
    resetPagination(tableKey); // reset ke page 0
    setRequestParams(nextParams); // trigger query
  };

  useEffect(() => {
    methods.resetField('all');
    methods.resetField('periode');
    methods.resetField('nomordokumen');
    methods.resetField('npwp');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedFilter]);

  return (
    <>
      <DashboardContent>
        <CustomBreadcrumbs
          heading="Dokumen Lain Masukan"
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'e-Faktur Dokumen Lain Masukan' },
          ]}
          action={[
            <Button component={RouterLink} to={paths.faktur.rekamDlm} variant="contained">
              Rekam Data
            </Button>,
            <Button variant="contained" onClick={() => setIsPrepopulatedOpen(true)}>
              Prepopulated
            </Button>,
          ]}
        />

        <FormProvider {...methods}>
          <form onSubmit={methods.handleSubmit(onSubmit)}>
            <Box sx={{ mt: 4, display: 'flex', gap: 1, justifyContent: 'center' }}>
              <Box sx={{ width: 200 }}>
                <Field.Select name="filter" label="Pencarian Berdasarkan" size="medium">
                  <MenuItem value="all">Semua</MenuItem>
                  <MenuItem value="nomordokumen">Nomor Dokumen</MenuItem>
                  <MenuItem value="npwp">NPWP</MenuItem>
                  <MenuItem value="periode">Periode</MenuItem>
                  <MenuItem value="customDate">Custom (by Date)</MenuItem>
                </Field.Select>
              </Box>
              <Box sx={{ width: 300 }}>
                {selectedFilter === 'all' && <Field.Text name="all" label="Kata Kunci" />}

                {selectedFilter === 'nomordokumen' && (
                  <Field.Text name="nomordokumen" label="Nomor Dokumen" />
                )}

                {selectedFilter === 'npwp' && <Field.Text name="npwp" label="NPWP" />}

                {selectedFilter === 'periode' && <Field.Text name="periode" label="Periode" />}

                {selectedFilter === 'customDate' && (
                  <Controller
                    name="kataKunci"
                    control={methods.control}
                    defaultValue={[null, null]}
                    render={({ field, fieldState }) => (
                      <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <DateRangePicker
                          value={field.value}
                          onChange={(newValue) => {
                            field.onChange(newValue);
                          }}
                          maxDate={dayjs()}
                          sx={{ width: 300 }}
                          calendars={1}
                          localeText={{ start: 'Start', end: 'End' }}
                          slotProps={{
                            textField: {
                              error: !!fieldState.error,
                              helperText: fieldState.error?.message,
                            },
                          }}
                        />
                      </LocalizationProvider>
                    )}
                  />
                )}
              </Box>
              <Box sx={{ width: 200 }}>
                <LoadingButton
                  size="xLarge"
                  type="submit"
                  variant="contained"
                  // loading={loading}
                  startIcon={<SearchRounded />}
                  loadingIndicator="Loading..."
                  // onClick={methods.handleSubmit(onSubmit)}
                >
                  Search
                </LoadingButton>
              </Box>
            </Box>
          </form>
        </FormProvider>

        <DataGridPremium
          apiRef={apiRef}
          checkboxSelection
          rows={rows || []}
          getRowId={(row: any) => {
            if (!row) return '';
            return String(row.id ?? row.internal_id ?? '');
          }}
          columns={columns}
          loading={isFetching}
          rowCount={totalRows}
          pagination
          paginationMode="server"
          paginationModel={localPagination}
          initialState={{
            pagination: {
              paginationModel: {
                page,
                pageSize,
              },
            },
            columns: {
              columnVisibilityModel: {
                jenisInvoice: false, // hide on load
              },
            },
          }}
          onPaginationModelChange={handlePaginationChange}
          pageSizeOptions={[5, 10, 15, 25, 50, 100]}
          filterMode="server"
          onFilterModelChange={debouncedFilterChange}
          sortingMode="server"
          onSortModelChange={debouncedSortChange}
          rowSelectionModel={rowSelectionModel}
          onRowSelectionModelChange={throttledSelectionChange}
          pinnedColumns={pinnedColumns}
          cellSelection
          showToolbar
          slots={{ toolbar: ToolbarWrapper }}
          sx={{
            border: 1,
            borderColor: 'divider',
            borderRadius: 2,
            mt: 3,
            '& .MuiDataGrid-cell': {
              borderColor: 'divider',
              userSelect: 'text',
              cursor: 'text',
            },
            '& .MuiDataGrid-columnHeaders': { borderColor: 'divider' },
          }}
          onColumnVisibilityModelChange={(newModel) => {
            if (newModel['__check__'] === false) {
              newModel['__check__'] = true;
            }
            apiRef.current?.setColumnVisibilityModel(newModel);
          }}
          disableVirtualization
        />
      </DashboardContent>

      {isDeleteModalOpen && (
        <ModalDeleteDokumenLainKeluaran
          dataSelected={rowSelectionModel}
          setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogDelete={isDeleteModalOpen}
          setIsOpenDialogDelete={setIsDeleteModalOpen}
          successMessage="Data berhasil dihapus"
          onConfirmDelete={async () => {
            await refetch();
          }}
        />
      )}

      {isUploadModalOpenCredit && (
        <ModalUploadCreditedDokumenLainMasukan
          dataSelected={rowSelectionModel}
          // setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogUpload={isUploadModalOpenCredit}
          setIsOpenDialogUpload={setIsUploadModalOpenCredit}
          successMessage="Data berhasil diupload"
          statusPembeli={statusPengkreditan}
          onConfirmUpload={async () => {
            await refetch();
          }}
        />
      )}

      {isUploadModalOpen && (
        <ModalUploadDokumenLainKeluaran
          dataSelected={rowSelectionModel}
          setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogUpload={isUploadModalOpen}
          setIsOpenDialogUpload={setIsUploadModalOpen}
          successMessage="Data berhasil diupload"
          onConfirmUpload={async () => {
            await refetch();
          }}
        />
      )}

      {isCancelModalOpen && (
        <ModalCancelDokumenLainMasukan
          dataSelected={rowSelectionModel}
          setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogCancel={isCancelModalOpen}
          setIsOpenDialogCancel={setIsCancelModalOpen}
          successMessage="Data berhasil dibatalkan"
          onConfirmCancel={async () => {
            await refetch();
          }}
        />
      )}

      {isReturOpen && (
        <ModalReturDokumenLainMasukan
          dataSelected={rowSelectionModel}
          setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogCancel={isReturOpen}
          setIsOpenDialogCancel={setIsReturOpen}
          type="retur"
        />
      )}

      {isPreviewOpen && (
        <ModalCetakDokumenLainMasukan
          payload={previewPayload}
          isOpen={isPreviewOpen}
          onClose={() => {
            setIsPreviewOpen(false);
            setPreviewPayload(undefined);
          }}
        />
      )}

      {isPrepopulatedOpen && (
        <ModalPrepolulatedDokumenLainMasukan
          isOpenDialogUpload={isPrepopulatedOpen}
          setIsOpenDialogUpload={setIsPrepopulatedOpen}
          successMessage="Berhasil unduh faktur prepopulated"
          onConfirmUpload={async () => {
            await refetch();
          }}
        />
      )}
    </>
  );
}
