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 CustomToolbarDn from '../components/customToolbarDn';
// import CustomToolbar, { CustomFilterButton } from '../components/customToolbarDn2';

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

  console.log(data, '123');

  // 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',
      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 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 } },
        }}
        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>
  );
}
