import Button from '@mui/material/Button';
import { DataGridPremium } from '@mui/x-data-grid-premium/DataGridPremium';
import { useMemo, useState } from 'react';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { RouterLink } from 'src/routes/components';
import { paths } from 'src/routes/paths';
import TableHeaderLabel from 'src/shared/components/TableHeaderLabel';
import useGetDn from '../../bupot-dn/hooks/useGetDn';
import type { GridFilterModel } from 'node_modules/@mui/x-data-grid/esm/models/gridFilterModel';
import type { GridSortModel } from 'node_modules/@mui/x-data-grid/esm/models/gridSortModel';
import type { GridColDef } from 'node_modules/@mui/x-data-grid/esm/models/colDef/gridColDef';
// import CustomToolbarDn from '../../bupot-dn/components/customToolbarDn';

export type IColumnGrid = GridColDef & {
  field:
    | 'fgStatus'
    | 'noBupot'
    | 'masaPajak'
    | 'tahunPajak'
    | 'kdObjPjk'
    | 'pasalPPh'
    | 'npwp'
    | 'nama'
    | 'dpp'
    | 'pphDipotong'
    | 'idTku'
    | 'dokReferensi'
    | 'nomorDokumen'
    | 'created_by'
    | 'created_at'
    | 'updated_by'
    | 'updated_at'
    | 'internal_id'
    | 'keterangan1'
    | 'keterangan2'
    | 'keterangan3'
    | 'keterangan4'
    | 'keterangan5';
  valueOptions?: string[];
};

export function DigunggungListView() {
  const [paginationModel, setPaginationModel] = useState({
    page: 0, // 0-based index
    pageSize: 10,
  });
  const [filterModel, setFilterModel] = useState<GridFilterModel>({ items: [] });
  const [sortModel, setSortModel] = useState<GridSortModel>([]);

  const buildAdvancedFilter = (filters?: GridFilterModel['items']) => {
    if (!filters || filters.length === 0) return '';

    return filters
      .map((f) => {
        if (!f.value || !f.field) return null;

        const field = `LOWER("${f.field}")`;
        const val = String(f.value).toLowerCase();

        switch (f.operator) {
          case 'contains':
            return `${field} LIKE '%${val}%'`;
          case 'equals':
          case 'is':
            return `${field} = '${val}'`;
          case 'isNot':
            return `${field} <> '${val}'`;
          default:
            return null;
        }
      })
      .filter(Boolean)
      .join(' AND ');
  };

  const { data, isLoading } = useGetDn({
    params: {
      Page: paginationModel.page + 1, // API biasanya 1-based
      Limit: paginationModel.pageSize,
      advanced: buildAdvancedFilter(filterModel?.items),
      sortingMode: sortModel[0]?.field,
      sortingMethod: sortModel[0]?.sort,
    },
    option: {
      refetchOnWindowFocus: false,
    },
  });

  const totalRows = data?.total || 0;
  const rows = useMemo(() => data?.data || [], [data?.data]);

  // type aman
  type Status = 'draft' | 'normal' | 'cancelled' | 'amendment';

  type StatusOption = {
    value: Status;
    label: string;
  };

  const statusOptions: StatusOption[] = [
    { value: 'draft', label: 'Draft' },
    { value: 'normal', label: 'Normal' },
    { value: 'cancelled', label: 'Dibatalkan' },
    { value: 'amendment', label: 'Normal Pengganti' },
  ];

  const columns: IColumnGrid[] = [
    {
      field: 'fgStatus',
      headerName: 'Status',
      width: 300,
      type: 'singleSelect',
      valueOptions: statusOptions.map((opt) => opt.value), // filter dropdown pakai value
      valueFormatter: (params: any) => {
        const option = statusOptions.find((opt) => opt.value === params.value);
        return option ? option.label : (params.value as string);
      },
    },
    { field: 'noBupot', headerName: 'Nomor Bukti Pemotongan', width: 200 },
    { field: 'masaPajak', headerName: 'Masa Pajak', width: 150 },
    { field: 'tahunPajak', headerName: 'Tahun Pajak', width: 150 },
    { field: 'kdObjPjk', headerName: 'Kode Objek Pajak', width: 150 },
    { field: 'npwp', headerName: 'Identitas', width: 150 },
    { field: 'nama', headerName: 'Nama', width: 150 },
    { field: 'dpp', headerName: 'Jumlah Penghasilan Bruto (Rp)', width: 150 },
    { field: 'pphDipotong', headerName: 'Jumlah PPh Terutang (Rp)', width: 200 },
    { field: 'idTku', headerName: 'NITKU Pemotong', width: 150 },
    { field: 'dokReferensi', headerName: 'Nama dokumen', width: 150 },
    { field: 'nomorDokumen', headerName: 'Nomor dokumen', width: 150 },
    { field: 'created_by', headerName: 'Created', width: 150 },
    { field: 'created_at', headerName: 'Created At', width: 200 },
    { field: 'updated_by', headerName: 'Updated', width: 150 },
    { field: 'updated_at', headerName: 'Update At', width: 150 },
    { field: 'internal_id', headerName: 'Referensi', width: 150 },
    { field: 'keterangan1', headerName: 'Keterangan 1', width: 150 },
    { field: 'keterangan2', headerName: 'Keterangan 2', width: 200 },
    { field: 'keterangan3', headerName: 'Keterangan 3', width: 150 },
    { field: 'keterangan4', headerName: 'Keterangan 4', width: 150 },
    { field: 'keterangan5', headerName: 'Keterangan 5', width: 150 },
  ];
  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Bupot Disetor Sendiri"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'e-Bupot Disetor Sendiri' },
        ]}
        action={
          <Button component={RouterLink} href={paths.unifikasi.sspNew} variant="contained">
            Rekam Data
          </Button>
        }
      />

      <TableHeaderLabel label="Daftar Bukti Setor atas PPh yang disetor Sendiri" />

      <DataGridPremium
        checkboxSelection
        rows={rows}
        columns={columns}
        loading={isLoading}
        rowCount={totalRows}
        initialState={{
          pagination: { paginationModel: { pageSize: 10, page: 0 } },
        }}
        pagination
        pageSizeOptions={[5, 10, 15, 25, 50, 100, 250, 500, 750, 100]}
        paginationMode="server"
        onPaginationModelChange={setPaginationModel}
        filterMode="server"
        onFilterModelChange={setFilterModel}
        sortingMode="server"
        onSortModelChange={setSortModel}
        pinnedColumns={{
          left: ['__check__', 'fgStatus', 'noBupot'],
        }}
        cellSelection
        // slots={{
        //   toolbar: CustomToolbarDn, // BENAR: pakai object
        // }}
      />
    </DashboardContent>
  );
}
