'use client'

import { ReactNode } from 'react'
import Card from '@mui/material/Card'
import Stack from '@mui/material/Stack'
import Button from '@mui/material/Button'
import Grid from '@mui/material/Grid2'
import Typography from '@mui/material/Typography'

type TableFiltersLayoutProps = {
  searchSlot: ReactNode
  filters?: ReactNode
  actionsSlot?: ReactNode
  afterFiltersSlot?: ReactNode
  activeFiltersCount?: number
  clearFiltersLabel?: string
  onClearFilters?: () => void
  isClearingDisabled?: boolean
}

const TableFiltersLayout = ({
  searchSlot,
  filters,
  actionsSlot,
  afterFiltersSlot,
  activeFiltersCount = 0,
  clearFiltersLabel = 'Clear filters',
  onClearFilters,
  isClearingDisabled
}: TableFiltersLayoutProps) => {
  const showClearButton = Boolean(onClearFilters)
  const isButtonDisabled = isClearingDisabled || activeFiltersCount === 0

  const ClearButton = showClearButton ? (
    <Button
      variant='outlined'
      color='error'
      onClick={onClearFilters}
      disabled={isButtonDisabled}
      startIcon={<i className='tabler-refresh' />}
    >
      {clearFiltersLabel}
    </Button>
  ) : null

  return (
    <Stack spacing={3}>
      <Card className='p-4'>
        <Stack
          direction={{ xs: 'column', md: 'row' }}
          spacing={2}
          alignItems={{ xs: 'flex-end' }}
          justifyContent='space-between'
          flexWrap='wrap'
        >
          <div className='flex-1 w-full'>{searchSlot}</div>
          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} alignItems={{ xs: 'stretch', sm: 'center' }}>
            {actionsSlot}
            {ClearButton}
          </Stack>
        </Stack>
        {!filters && !actionsSlot && !showClearButton && (
          <Typography variant='caption' color='text.secondary' className='mt-2 block'>
            {clearFiltersLabel}
          </Typography>
        )}
      </Card>

      {filters && (
        <Card className='p-4'>
          <Stack spacing={3}>
            <Grid container spacing={3} alignItems={'flex-end'}>
              {filters}
            </Grid>
            {afterFiltersSlot}
          </Stack>
        </Card>
      )}

      {!filters && afterFiltersSlot}
    </Stack>
  )
}

export default TableFiltersLayout
