import {
  Box,
  Button,
  Card,
  Chip,
  MenuItem,
  Select,
  TextField,
  Typography,
} from '@mui/material'
import { AssetType, AvailabilityStatus } from '../../domain/enums'
import { getAssetTypeLabel, getAvailabilityLabel } from './propertyHelpers'

export interface PropertyTableFilters {
  search?: string
  assetTypes?: string[]
  availabilityStatus?: string
  sortBy?: 'dataQuality' | 'availability' | 'area' | 'rent' | 'confidence'
  sortDir?: 'asc' | 'desc'
}

interface PropertyFilterBarProps {
  filters: PropertyTableFilters
  onFiltersChange: (f: PropertyTableFilters) => void
}

const SORT_OPTIONS = [
  { value: 'dataQuality', label: 'Datenqualität' },
  { value: 'area', label: 'Fläche' },
  { value: 'rent', label: 'Miete' },
  { value: 'confidence', label: 'Konfidenz' },
  { value: 'availability', label: 'Verfügbarkeit' },
] as const

const ALL_ASSET_TYPES = Object.values(AssetType)
const ALL_AVAILABILITY = Object.values(AvailabilityStatus)

export function PropertyFilterBar({ filters, onFiltersChange }: PropertyFilterBarProps) {
  const isActive =
    !!filters.search ||
    (filters.assetTypes?.length ?? 0) > 0 ||
    !!filters.availabilityStatus ||
    !!filters.sortBy

  function update(partial: Partial<PropertyTableFilters>) {
    onFiltersChange({ ...filters, ...partial })
  }

  function reset() {
    onFiltersChange({})
  }

  const selectedAssetTypes = filters.assetTypes ?? []

  function toggleAssetType(type: string) {
    const current = selectedAssetTypes
    if (current.includes(type)) {
      update({ assetTypes: current.filter(t => t !== type) })
    } else {
      update({ assetTypes: [...current, type] })
    }
  }

  return (
    <Card sx={{ mx: 3, mb: 0, mt: 0, borderRadius: '0 0 8px 8px', borderTop: 'none', boxShadow: 'none', border: '1px solid #e2e8f0' }}>
      <Box sx={{ p: 1.5, display: 'flex', flexDirection: 'column', gap: 1.5 }}>

        {/* Row 1: Asset type chips */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
          <Typography variant="caption" sx={{ color: 'text.secondary', mr: 0.5, whiteSpace: 'nowrap' }}>
            Typ:
          </Typography>
          {ALL_ASSET_TYPES.map(t => (
            <Chip
              key={t}
              label={getAssetTypeLabel(t)}
              size="small"
              variant={selectedAssetTypes.includes(t) ? 'filled' : 'outlined'}
              onClick={() => toggleAssetType(t)}
              sx={{
                cursor: 'pointer',
                ...(selectedAssetTypes.includes(t) && { bgcolor: '#1e3a5f', color: 'white', borderColor: '#1e3a5f' }),
              }}
            />
          ))}
        </Box>

        {/* Row 2: Availability, Sort, Search, Reset */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
          <Select
            value={filters.availabilityStatus ?? ''}
            onChange={e => update({ availabilityStatus: e.target.value || undefined })}
            displayEmpty
            size="small"
            sx={{ minWidth: 160 }}
          >
            <MenuItem value="">Verfügbarkeit (alle)</MenuItem>
            {ALL_AVAILABILITY.map(s => (
              <MenuItem key={s} value={s}>{getAvailabilityLabel(s)}</MenuItem>
            ))}
          </Select>

          <Select
            value={filters.sortBy ?? ''}
            onChange={e => update({ sortBy: (e.target.value as PropertyTableFilters['sortBy']) || undefined })}
            displayEmpty
            size="small"
            sx={{ minWidth: 160 }}
          >
            <MenuItem value="">Sortierung</MenuItem>
            {SORT_OPTIONS.map(opt => (
              <MenuItem key={opt.value} value={opt.value}>{opt.label}</MenuItem>
            ))}
          </Select>

          <TextField
            value={filters.search ?? ''}
            onChange={e => update({ search: e.target.value || undefined })}
            placeholder="Titel, Stadt, Strasse …"
            size="small"
            sx={{ flex: 1, minWidth: 220 }}
          />

          {isActive && (
            <Button size="small" variant="outlined" onClick={reset} sx={{ textTransform: 'none', whiteSpace: 'nowrap' }}>
              Filter zurücksetzen
            </Button>
          )}
        </Box>
      </Box>
    </Card>
  )
}
