import * as React from 'react';
import type { GridToolbarProps } from '@mui/x-data-grid-premium';
import { GridToolbarContainer } from '@mui/x-data-grid-premium';
import { Stack, Divider, IconButton, Tooltip } from '@mui/material';
import { CustomFilterButton } from './CustomFilterButton';
import CustomColumnsButton from './CustomColumnsButton';
import type { ActionItem } from '../../types/types';

interface CustomToolbarProps extends GridToolbarProps {
  actions?: ActionItem[][];
  columns: any[]; // GridColDef[]
  filterModel: any;
  setFilterModel: (m: any) => void;
  statusOptions?: { value: string; label: string }[];
}

// ✅ React.memo mencegah render ulang kalau props sama
export const CustomToolbar = React.memo(function CustomToolbar({
  actions = [],
  columns,
  filterModel,
  setFilterModel,
  statusOptions = [],
  ...gridToolbarProps
}: CustomToolbarProps) {
  return (
    <GridToolbarContainer
      sx={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        p: 1.5,
      }}
      {...gridToolbarProps}
    >
      <Stack direction="row" alignItems="center" gap={1}>
        {actions.map((group, groupIdx) => (
          <Stack key={groupIdx} direction="row" gap={0.5} alignItems="center">
            {group.map((action, idx) => (
              <Tooltip key={idx} title={action.title}>
                <span>
                  <IconButton
                    sx={{ color: action.disabled ? 'action.disabled' : '#123375' }}
                    size="small"
                    onClick={action.func}
                    disabled={action.disabled}
                  >
                    {action.icon}
                  </IconButton>
                </span>
              </Tooltip>
            ))}
            {groupIdx < actions.length - 1 && <Divider orientation="vertical" flexItem />}
          </Stack>
        ))}
      </Stack>

      <Stack direction="row" alignItems="center" gap={0.5}>
        <CustomColumnsButton />
        <CustomFilterButton
          columns={columns}
          filterModel={filterModel}
          setFilterModel={setFilterModel}
          statusOptions={statusOptions}
        />
      </Stack>
    </GridToolbarContainer>
  );
});
