// ListToolbar.tsx
import React, { ReactElement, memo } from 'react';
import { styled, useTheme } from '@mui/material/styles';
import PropTypes from 'prop-types';
import { Box, Divider, ToolbarProps, useMediaQuery } from '@mui/material';
import { Exporter, useListContext } from 'ra-core';
import { FilterContext, FilterForm } from 'react-admin';
import { ActiveFiltersChips, FilterSidebarContext } from './FilterSidebar';
import { isEmpty } from 'lodash';
import { ListTabToolbarConfig, ListTabsToolbar } from './ListTabsToolbar';

interface ListToolbarPropsExtended extends ListToolbarProps {
  hasFilterSidebar?: boolean;
  tabs?: ListTabToolbarConfig[];
}

function ListToolbarComp(props: ListToolbarPropsExtended): ReactElement | null {
  const { filters, actions, className, hasFilterSidebar, tabs, ...rest } = props;
  const theme = useTheme() as any;
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const Actions = actions ? React.cloneElement(actions, { ...rest, filters, ...actions.props }) : null;
  const { filterValues, data, isLoading } = useListContext();
  const shouldRenderEmptyList = !isLoading && data && data.length === 0;

  const hasTabs = tabs && tabs.length > 0;

  return Array.isArray(filters) ? (
    <FilterSidebarContext.Provider value={{ hasFilterSidebar }}>
      <FilterContext.Provider value={filters}>
        <Root className={className}>
          <Box sx={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 2 }}>
            {tabs ? <ListTabsToolbar tabs={tabs} /> : null}
            <Box>
              {isMobile && hasFilterSidebar ? (
                <Box
                  sx={{
                    border: isMobile ? (shouldRenderEmptyList ? '1px solid' : 0) : 0,
                    borderColor: theme.palette.mode === 'dark' ? theme.palette.divider : theme.palette.grey.A800
                  }}
                >
                  {Actions}
                  {!isEmpty(filterValues) ? (
                    <Box>
                      <Divider />
                      <ActiveFiltersChips />
                    </Box>
                  ) : null}
                </Box>
              ) : (
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: isMobile ? 'column' : 'row',
                    alignItems: isMobile ? 'flex-start' : 'center',
                    ...(hasFilterSidebar && { flexWrap: 'wrap' }),
                    gap: 2,
                    px: 2.5,
                    py: 2.5
                  }}
                >
                  {hasFilterSidebar ? <ActiveFiltersChips /> : <FilterForm />}
                  {!isMobile ? <Box sx={{ flex: 1 }} /> : null}
                  {Actions}
                </Box>
              )}
            </Box>
          </Box>
        </Root>
      </FilterContext.Provider>
    </FilterSidebarContext.Provider>
  ) : (
    <Root className={className}>
      <Box sx={{ display: 'flex', flex: 1, flexDirection: 'column', gap: 2, width: '100%' }}>
        {tabs ? <ListTabsToolbar tabs={tabs} /> : null}
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-end',
            gap: 2,
            p: hasTabs ? 0 : theme.spacing(2.5),
            px: theme.spacing(2.5),
            pb: theme.spacing(2.5),
            width: '100%'
          }}
        >
          {filters
            ? React.cloneElement(filters, {
                ...rest,
                context: 'form'
              })
            : null}
          <span />
          {actions
            ? React.cloneElement(actions, {
                ...rest,
                filters,
                ...actions.props
              })
            : null}
        </Box>
      </Box>
    </Root>
  );
}

ListToolbarComp.propTypes = {
  filters: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
  // @ts-ignore
  actions: PropTypes.oneOfType([PropTypes.bool, PropTypes.element]),
  // @ts-ignore
  exporter: PropTypes.oneOfType([PropTypes.func, PropTypes.bool])
};

interface ListToolbarProps extends Omit<ToolbarProps, 'classes' | 'onSelect'> {
  actions?: ReactElement | false;
  exporter?: Exporter | false;
  filters?: ReactElement | ReactElement[];
  hasCreate?: boolean;
}

const PREFIX = 'RaListToolbar';

const Root = styled('div', {
  name: PREFIX,
  overridesResolver: (styles) => styles.root
})(({ theme }) => ({
  display: 'flex',
  position: 'relative',
  justifyContent: 'space-between',
  alignItems: 'flex-end',
  width: '100%',
  padding: 0,
  // [theme.breakpoints.down('md')]: {
  //   flexWrap: 'wrap'
  // },
  [theme.breakpoints.down('sm')]: {
    backgroundColor: theme.palette.background.paper,
    flexWrap: 'inherit',
    flexDirection: 'column-reverse'
  }
}));

const ListToolbar = memo(ListToolbarComp);
export { ListToolbar };
export type { ListToolbarProps };
