import React from 'react';
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Badge,
  Box,
  Button,
  TextField,
  Typography,
  InputAdornment,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import FilterListIcon from '@mui/icons-material/FilterList';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';

export interface FilterBarProps {
  searchValue?: string;
  onSearchChange?: (value: string) => void;
  searchPlaceholder?: string;
  children?: React.ReactNode;
  activeFilterCount?: number;
  onClearFilters?: () => void;
  collapsible?: boolean;
}

/** Search + filter controls bar. Supports collapsible accordion mode. */
export const FilterBar: React.FC<FilterBarProps> = ({
  searchValue,
  onSearchChange,
  searchPlaceholder = 'Suchen...',
  children,
  activeFilterCount = 0,
  onClearFilters,
  collapsible = false,
}) => {
  const searchField = onSearchChange ? (
    <TextField
      size="small"
      placeholder={searchPlaceholder}
      value={searchValue ?? ''}
      onChange={(e) => onSearchChange(e.target.value)}
      sx={{ minWidth: 200 }}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon fontSize="small" />
          </InputAdornment>
        ),
      }}
    />
  ) : null;

  const clearButton = activeFilterCount > 0 && onClearFilters ? (
    <Button size="small" onClick={onClearFilters}>
      Filter zurücksetzen
    </Button>
  ) : null;

  if (collapsible) {
    return (
      <Accordion disableGutters elevation={0} sx={{ mb: 2, '&:before': { display: 'none' } }}>
        <AccordionSummary expandIcon={<ExpandMoreIcon />}>
          <Box display="flex" alignItems="center" gap={1}>
            <Badge badgeContent={activeFilterCount} color="primary">
              <FilterListIcon />
            </Badge>
            <Typography variant="body2">Filter</Typography>
          </Box>
        </AccordionSummary>
        <AccordionDetails>
          <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', alignItems: 'center' }}>
            {searchField}
            {children}
            {clearButton}
          </Box>
        </AccordionDetails>
      </Accordion>
    );
  }

  return (
    <Box sx={{ display: 'flex', gap: 1.5, mb: 2, flexWrap: 'wrap', alignItems: 'center' }}>
      {searchField}
      {children}
      <Box sx={{ flex: 1 }} />
      {clearButton}
    </Box>
  );
};
