import Button from '@mui/material/Button';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
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 {
  ArticleTwoTone,
  AutorenewTwoTone,
  FileOpenTwoTone,
  HighlightOffTwoTone,
  PlaylistAddCheckTwoTone,
  PlaylistRemoveTwoTone,
  RemoveCircleTwoTone,
  SwapHorizontalCircleTwoTone,
} from '@mui/icons-material';
import { FG_STATUS_FAKTUR_PK } from '../constant';
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/useAdvancedFilterFakturPM';
import { CustomToolbar } from '../components/CustomToolbar';
import useGetFakturPM, { formatDateToDDMMYYYY } from '../hooks/useGetFakturPM';
import { formatRupiah } from 'src/shared/FormatRupiah/FormatRupiah';
import ModalCetakFakturPM from '../components/dialog/ModalCetakFakturPM';
import ModalUploadCreditedPM from '../components/dialog/ModalUploadCreditedPM';
import ModalConfirmationWaitingFaktur from '../components/dialog/ModalConfirmationWaitingFakturPM';
import ModalPrepolulatedPM from '../components/dialog/ModalPrepopulatedPM';
import ModalReturFakturPM from '../components/dialog/ModalReturFakturPM';

export type IColumnGrid = GridColDef & {
  field:
    | 'statusfaktur'
    | 'nomorfaktur'
    | 'tahunkreditpajak'
    | 'masakreditpajak'
    | 'jenisInvoice'
    | 'npwppembeli'
    | 'namapembeli'
    | 'kdNegaraPembeli'
    | 'tanggalfaktur'
    | 'masapajak'
    | 'tahunpajak'
    | 'npwppenjual'
    | 'uangmukadpp'
    | 'uangmukadpplain'
    | 'uangmukappn'
    | 'uangmukappnbm'
    | 'totaldpp'
    | 'totaldpplain'
    | 'totalppn'
    | 'totalppnbm'
    | 'jumlahuangmuka'
    | 'jumlahpelunasan'
    | 'refDoc'
    | 'namapenandatangan'
    | 'referensi'
    | 'created_by'
    | 'created_at'
    | 'updated_by'
    | 'updated_at'
    | 'namatokopenjual'
    | 'keterangan1'
    | 'keterangan2'
    | 'keterangan3'
    | 'keterangan4'
    | 'keterangan5';
  // valueOptions?: string[];
  valueOptions?: readonly (string | number | { value: string | number; label: string })[];
};

type TPengkreditan = 'CREDITED' | 'UNCREDITED' | 'INVALID';

export function FakturPmListView() {
  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 [isUploadModalOpen, setIsUploadModalOpen] = useState<boolean>(false);

  const [isPreviewOpen, setIsPreviewOpen] = useState<boolean>(false);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState<boolean>(false);
  const [isPenggantiModalOpen, setIsPenggantiModalOpen] = useState<boolean>(false);
  const [previewPayload, setPreviewPayload] = useState<Record<string, any> | undefined>(undefined);
  const [statusPengkreditan, setStatusPengkreditan] = useState<TPengkreditan>('CREDITED');
  const [isPrepopulatedOpen, setIsPrepopulatedOpen] = useState(false);
  const [isReturOpen, setIsReturOpen] = useState(false);

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

  // const signer = useSelector((state: RootState) => state.user.data.signer);

  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);

  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);

    const baseParams = {
      page,
      limit: pageSize,
      sortingMode: sortModel[0]?.field ?? '',
      sortingMethod: sortModel[0]?.sort ?? '',
    };

    return buildRequestParams(baseParams, advanced);
  }, [page, pageSize, sortModel, filterModel.items, buildAdvancedFilter, buildRequestParams]);

  const { data, isFetching, refetch } = useGetFakturPM({
    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);

  type Status =
    | 'DRAFT'
    | 'APPROVED'
    | 'WAITING FOR AMENDMENT'
    | 'AMENDED'
    | 'WAITING FOR CANCELLATION';
  type StatusOption = { value: Status; label: string };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const statusOptions: StatusOption[] = [
    { value: 'DRAFT', label: 'Draft' },
    { value: 'APPROVED', label: 'Normal' },
    { value: 'WAITING FOR AMENDMENT', label: 'Normal Pengganti' },
    { value: 'AMENDED', label: 'Diganti' },
    { value: 'WAITING FOR CANCELLATION', label: 'Batal' },
  ];

  const columns = useMemo<IColumnGrid[]>(
    () => [
      {
        field: 'statusfaktur',

        headerName: 'Status',
        width: 350,
        type: 'singleSelect',
        valueOptions: statusOptions.map((opt) => opt.value),
        valueFormatter: ({ value }: { value: string }) => {
          const option = statusOptions.find((opt) => opt.value === value);
          return option ? option.label : value;
        },
        renderCell: ({ value, row }) => (
          <StatusChip value={value} credit={row.statuspembeli} valid={row.buyerstatus} />
        ),
      },
      { field: 'nomorfaktur', headerName: 'Nomor Faktur Pajak', width: 200 },
      {
        field: 'masapajak',
        headerName: 'Masa Pajak',
        width: 150,
      },
      {
        field: 'tahunpajak',
        headerName: 'Tahun Pajak',
        width: 200,
      },
      {
        field: 'masakreditpajak',
        headerName: 'Masa Pengkreditan',
        width: 150,
      },
      {
        field: 'tahunkreditpajak',
        headerName: 'Tahun Pengkreditan',
        width: 200,
      },
      {
        field: 'tanggalfaktur',
        headerName: 'Tanggal Faktur Pajak',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.tanggalfaktur),
      },
      { field: 'namatokopenjual', headerName: 'Nama Penjual', width: 150 },
      { field: 'npwppenjual', headerName: 'NPWP Penjual', width: 150 },
      {
        field: 'jenisInvoice',
        headerName: 'Jenis Invoice',
        width: 150,
        renderCell: ({ row }) => {
          if (row.fguangmuka) return 'Uang Muka';
          if (row.fgpelunasan) return 'Pelunasan';
          return 'Full Payment';
        },
      },
      {
        field: 'uangmukadpp',
        headerName: 'Nilai DPP',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.uangmukadpp),
      },
      {
        field: 'uangmukadpplain',
        headerName: 'DPP Nilai Lain',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.uangmukadpplain),
      },
      {
        field: 'uangmukappn',
        headerName: 'PPN',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.uangmukappn),
      },
      {
        field: 'uangmukappnbm',
        headerName: 'PPnBM',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.uangmukappnbm),
      },

      {
        field: 'jumlahuangmuka',
        headerName: 'Jumlah Uang Muka',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.jumlahuangmuka),
      },
      {
        field: 'jumlahpelunasan',
        headerName: 'Jumlah Pelunasan',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.jumlahpelunasan),
      },
      {
        field: 'totaldpp',
        headerName: 'DPP',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.totaldpp),
      },
      {
        field: 'totaldpplain',
        headerName: 'DPP Nilai Lain',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.totaldpplain),
      },
      {
        field: 'totalppn',
        headerName: 'PPN',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.totalppn),
      },
      {
        field: 'totalppnbm',
        headerName: 'PPnBM',
        width: 150,
        renderCell: ({ row }) => formatRupiah(row.totalppnbm),
      },

      { field: 'referensi', headerName: 'Referensi', width: 150 },
      { field: 'created_by', headerName: 'User Perekam', width: 150 },
      {
        field: 'created_at',
        headerName: 'Tanggal Rekam',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.created_at),
      },
      { field: 'updated_by', headerName: 'User Pengubah', width: 150 },
      {
        field: 'updated_at',
        headerName: 'Tanggal Ubah',
        width: 150,
        renderCell: ({ row }) => formatDateToDDMMYYYY(row.updated_at),
      },
      { field: 'keterangan1', headerName: 'Keterangan 1', width: 150 },
      { field: 'keterangan2', headerName: 'Keterangan 2', width: 150 },
      { field: 'keterangan3', headerName: 'Keterangan 3', width: 150 },
      { field: 'keterangan4', headerName: 'Keterangan 4', width: 150 },
      { field: 'keterangan5', headerName: 'Keterangan 5', width: 150 },
    ],
    [statusOptions]
  );

  const handleEditData = useCallback(
    (type = 'ubah') => {
      const selectedRow = dataSelectedRef.current[0];
      if (!selectedRow) return;
      navigate(`/faktur/pk/${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,
        canReplacement: false,
        canCancel: false,
        canCredit: false,
        canRetur: false,
      };
    }

    const isSingle = count === 1;

    const allApproved = dataSelected.every((d) => d.statusfaktur === FG_STATUS_FAKTUR_PK.APPROVED);

    const allWaitingAmendment = dataSelected.every(
      (d) => d.statusfaktur === 'WAITING FOR AMENDMENT'
    );

    const allWaitingCancellation = dataSelected.every(
      (d) => d.statusfaktur === 'WAITING FOR CANCELLATION'
    );

    const allValidForRetur = dataSelected.every(
      (d) =>
        d.statusfaktur === FG_STATUS_FAKTUR_PK.APPROVED &&
        d.buyerstatus !== 'INVALID' &&
        d.statuspembeli != null
    );

    return {
      canDetail: isSingle,
      canReplacement: allWaitingAmendment,
      canCancel: allWaitingCancellation,
      canCredit: allApproved,
      canRetur: isSingle && allValidForRetur,
    };
    // 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: 'Detail',
          icon: <ArticleTwoTone sx={{ width: 26, height: 26 }} />,
          func: handleOpenPreview,
          disabled: !validatedActions.canDetail,
        },
      ],
      [
        {
          title: 'Batal',
          icon: <HighlightOffTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsCancelModalOpen(true),
          disabled: !validatedActions.canCancel,
        },
        {
          title: 'Pengganti',
          icon: <FileOpenTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsPenggantiModalOpen(true),
          disabled: !validatedActions.canReplacement,
        },
        {
          title: 'Retur',
          icon: <SwapHorizontalCircleTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => setIsReturOpen(true),
          disabled: !validatedActions.canRetur,
        },
      ],
      [
        {
          title: 'Credit',
          icon: <PlaylistAddCheckTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => {
            setStatusPengkreditan('CREDITED');
            setIsUploadModalOpen(true);
          },
          disabled: !validatedActions.canCredit,
        },
        {
          title: 'Uncredit',
          icon: <PlaylistRemoveTwoTone sx={{ width: 26, height: 26 }} />,
          func: () => {
            setStatusPengkreditan('UNCREDITED');
            setIsUploadModalOpen(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, handleEditData]
  );

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

  const ToolbarWrapper: React.FC<GridToolbarProps> = useCallback(
    (gridToolbarProps) => (
      <CustomToolbar
        actions={actions}
        columns={columns}
        filterModel={filterModel}
        setFilterModel={setFilterModel}
        statusOptions={statusOptions}
        {...gridToolbarProps}
      />
    ),
    [actions, columns, filterModel, setFilterModel, statusOptions]
  );

  return (
    <>
      <DashboardContent>
        <CustomBreadcrumbs
          heading="Faktur Pajak Masukan"
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'e-Faktur Pajak Masukan' },
          ]}
          action={
            <Button variant="contained" onClick={() => setIsPrepopulatedOpen(true)}>
              Prepopulated
            </Button>
          }
        />

        <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: true, // 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>

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

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

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

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

      {isPenggantiModalOpen && (
        <ModalConfirmationWaitingFaktur
          dataSelected={rowSelectionModel}
          setSelectionModel={setRowSelectionModel}
          tableApiRef={apiRef}
          isOpenDialogCancel={isPenggantiModalOpen}
          setIsOpenDialogCancel={setIsPenggantiModalOpen}
          successMessage="Data berhasil diganti"
          variant="PENGGANTI"
          onConfirmCancel={async () => {
            await refetch();
          }}
        />
      )}

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