import Button from '@mui/material/Button';
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 type { GridColDef, GridFilterModel, GridSortModel } from '@mui/x-data-grid-premium';
import { DataGridPremium } from '@mui/x-data-grid-premium';
import { useMemo, useState } from 'react';
import TableHeaderLabel from 'src/shared/components/TableHeaderLabel';
import useGetBulanan from '../hooks/useGetBulanan';
import { isEmpty } from 'lodash';
// import CustomToolbarDn from '../components/customToolbarDn';
// import CustomToolbar, { CustomFilterButton } from '../components/customToolbarDn2';

const numberIDR = (number: string) =>
  new Intl.NumberFormat('id-ID', {
    currency: 'IDR',
    // style: 'currency'
  }).format(Number(number));

export type IColumnGrid = GridColDef & {
  field:
    | 'fgStatus'
    | 'noBupot'
    | 'masaPajak'
    | 'tahunPajak'
    | 'kdObjPjk'
    | 'pasalPPh'
    | 'passportNo'
    | 'countryCode'
    | 'npwp16Dipotong'
    | 'namaDipotong'
    | 'bruto'
    | 'pph21ditanggungperusahaan'
    | 'pphDipotong'
    | 'nitkuPemotong'
    | 'created'
    | 'created_at'
    | 'updated'
    | 'updated_at'
    | 'internal_id'
    | 'keterangan1'
    | 'keterangan2'
    | 'keterangan3'
    | 'keterangan4'
    | 'keterangan5';
  valueOptions?: string[];
};

export function BulananListView() {
  // const [tabs1, setTabs1] = useState<number>(1);
  // const [tabs2, setTabs2] = useState<number>(0);
  const [paginationModel, setPaginationModel] = useState({
    page: 0, // 0-based index
    pageSize: 10,
  });
  const [filterModel, setFilterModel] = useState<GridFilterModel>({ items: [] });
  const [sortModel, setSortModel] = useState<GridSortModel>([]);
  // const [rowSelectionModel, setRowSelectionModel] = useState<any>([]);
  // const [rowSelectionModel, setRowSelectionModel] =
  // useState<GridRowSelectionModel>(new Set<GridRowId>());

  // const navigate = useNavigate();

  // Enhance tabs dengan navigate
  // const enhancedTabsTop = TABS_TOP_UNIFIKASI.map((tab) =>
  //   tab.value ? { ...tab, onClick: () => navigate(tab.value) } : tab
  // );

  // const enhancedTabsChoice = TABS_CHOICE.map((tab) => ({
  //   ...tab,
  //   onClick: () => navigate(tab.value),
  // }));

  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 } = useGetBulanan({
    params: {
      Page: paginationModel.page + 1, // API biasanya 1-based
      Limit: paginationModel.pageSize,
      advanced: buildAdvancedFilter(filterModel?.items),
      sortingMode: sortModel[0]?.field,
      sortingMethod: sortModel[0]?.sort,
    },
    refetchOnWindowFocus: false,
  });

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

  // const handleChange = (event: React.SyntheticEvent, newValue: number) => {
  //   setTabs1(newValue);
  // };

  // const handleChange2 = (event: React.SyntheticEvent, newValue: number) => {
  //   setTabs2(newValue);
  // };

  // 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',
      headerAlign: 'center',
      align: 'left',
      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',
      headerAlign: 'center',
      align: 'left',
      width: 200,
    },
    {
      field: 'masaPajak',
      headerName: 'Masa - Tahun Pajak',
      headerAlign: 'center',
      align: 'center',

      minWidth: 150,
      renderCell: (params) => `${params.row.masaPajak} - ${params.row.thnPajak}`,
    },
    {
      field: 'kdObjPjk',
      headerName: 'Kode Objek Pajak',
      headerAlign: 'center',
      align: 'center',
      width: 150,
      minWidth: 150,
    },
    {
      field: 'pasalPPh',
      headerName: 'Pasal PPh',
      headerAlign: 'center',
      align: 'center',
      minWidth: 150,
    },
    {
      field: 'passportNo',
      headerName: 'Nomor Paspor',
      headerAlign: 'center',
      minWidth: 200,
      align: 'left',
    },
    {
      field: 'countryCode',
      headerName: 'Negara',
      headerAlign: 'center',
      align: 'left',

      minWidth: 200,
      renderCell: (params) =>
        isEmpty(params.value) ? '' : `${params.value} - ${params.row.namaNegara}`,
    },
    {
      field: 'internal_id',
      headerName: 'Referensi',
      headerAlign: 'center',
      align: 'left',

      minWidth: 200,
    },
    {
      field: 'npwp16Dipotong',
      headerName: 'NPWP',
      headerAlign: 'center',
      align: 'left',
      minWidth: 200,
    },
    {
      field: 'namaDipotong',
      headerName: 'Nama',
      headerAlign: 'center',
      align: 'left',
      minWidth: 200,
    },
    {
      field: 'bruto',
      headerName: 'Jumlah Bruto (Rp)',
      headerAlign: 'center',
      align: 'right',
      minWidth: 200,
      valueFormatter: (params) => {
        if (params == null) {
          return '0';
        }
        return numberIDR(params);
      },
    },
    {
      field: 'pph21ditanggungperusahaan',
      headerName: 'Tunjangan PPh (Rp)',
      headerAlign: 'center',
      align: 'right',
      minWidth: 200,
      type: 'number',
      valueFormatter: (params) => {
        if (params == null) {
          return '0';
        }
        return numberIDR(params);
      },
    },
    {
      field: 'pphDipotong',
      headerName: 'Jumlah PPh Terutang (Rp)',
      headerAlign: 'center',
      align: 'right',
      type: 'number',
      valueFormatter: (params) => {
        if (params == null) {
          return '0';
        }
        return numberIDR(params);
      },
    },
    {
      field: 'nitkuPemotong',
      headerName: 'NITKU Pemotong',
      headerAlign: 'center',
      align: 'left',
      minWidth: 200,
    },
    {
      field: 'created',
      headerName: 'Created',
      headerAlign: 'center',
      minWidth: 150,
    },
    { field: 'created_at', headerName: 'Created At', width: 150 },
    { field: 'updated', headerName: 'Updated', width: 150 },
    { field: 'updated_at', headerName: 'Update At', width: 150 },
    {
      field: 'keterangan1',
      headerName: 'Keterangan 1',
      minWidth: 200,
      flex: 1,
    },
    {
      field: 'keterangan2',
      headerName: 'Keterangan 2',
      minWidth: 200,
      flex: 1,
    },
    {
      field: 'keterangan3',
      headerName: 'Keterangan 3',
      minWidth: 200,
      flex: 1,
    },
    {
      field: 'keterangan4',
      headerName: 'Keterangan 4',
      minWidth: 200,
      flex: 1,
    },
    {
      field: 'keterangan5',
      headerName: 'Keterangan 5',
      minWidth: 200,
      flex: 1,
    },
  ];

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Bupot Bulanan"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'e-Bupot PPh Pasal 21 Bulanan' },
        ]}
        action={
          <Button component={RouterLink} href={paths.pph21.bulananRekam} variant="contained">
            Rekam Data
          </Button>
        }
      />

      <TableHeaderLabel label="Daftar Bupot Bulanan" />

      <DataGridPremium
        sx={{
          border: 1,
          borderColor: 'divider',
          borderRadius: 2,
          '& .MuiDataGrid-cell': {
            borderColor: 'divider',
          },
          '& .MuiDataGrid-columnHeaders': {
            borderColor: 'divider',
          },
        }}
        checkboxSelection
        rows={rows}
        columns={columns}
        loading={isLoading}
        rowCount={totalRows}
        initialState={{
          pagination: { paginationModel: { pageSize: 10, page: 0 } },
        }}
        disableVirtualization
        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: () => (
        //     <CustomToolbar
        //       actions={[
        //         [
        //           {
        //             title: 'Edit',
        //             icon: <EditNoteTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: true,
        //           },
        //           {
        //             title: 'Detail',
        //             icon: <ArticleTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: true,
        //           },
        //           {
        //             title: 'Hapus',
        //             icon: <DeleteSweepTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: false,
        //           },
        //         ],
        //         [
        //           {
        //             title: 'Upload',
        //             icon: <UploadFileTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: false,
        //           },
        //           {
        //             title: 'Pengganti',
        //             icon: <FileOpenTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: false,
        //           },
        //           {
        //             title: 'Batal',
        //             icon: <HighlightOffTwoTone sx={{ width: 26, height: 26 }} />,
        //             func: () => {},
        //             disabled: true,
        //           },
        //         ],
        //       ]}
        //       columns={columns}
        //       filterModel={filterModel}
        //       setFilterModel={setFilterModel}
        //       statusOptions={statusOptions.map((s) => ({ value: s.value, label: s.label }))}
        //     />
        //   ),
        // }}
      />
    </DashboardContent>
  );
}
