import { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Button,
  InputAdornment,
} from '@mui/material';
import { Search, Clear } from '@mui/icons-material';
import { useIdeasStore } from '../../store/ideas';
import { useModulesQuery } from '../../hooks/useIdeas';
import type { IdeaStatus, IdeaPriority } from '../../types/idea';

const statusOptions: { value: IdeaStatus; label: string }[] = [
  { value: 'backlog', label: 'Бэклог' },
  { value: 'todo', label: 'К выполнению' },
  { value: 'in_progress', label: 'В работе' },
  { value: 'done', label: 'Готово' },
  { value: 'cancelled', label: 'Отменено' },
];

const priorityOptions: { value: IdeaPriority; label: string }[] = [
  { value: 'low', label: 'Низкий' },
  { value: 'medium', label: 'Средний' },
  { value: 'high', label: 'Высокий' },
  { value: 'critical', label: 'Критичный' },
];

export function IdeasFilters() {
  const { filters, setFilter, clearFilters } = useIdeasStore();
  const { data: modules = [] } = useModulesQuery();
  const [searchValue, setSearchValue] = useState(filters.search ?? '');

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      setFilter('search', searchValue || undefined);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchValue, setFilter]);

  const hasFilters = Boolean(
    filters.status ?? filters.priority ?? filters.module ?? filters.search,
  );

  return (
    <Box
      sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', alignItems: 'center' }}
    >
      <TextField
        size="small"
        placeholder="Поиск идей..."
        value={searchValue}
        onChange={(e) => setSearchValue(e.target.value)}
        sx={{ minWidth: 200 }}
        slotProps={{
          input: {
            startAdornment: (
              <InputAdornment position="start">
                <Search fontSize="small" />
              </InputAdornment>
            ),
          },
        }}
      />

      <FormControl size="small" sx={{ minWidth: 120 }}>
        <InputLabel>Статус</InputLabel>
        <Select<IdeaStatus | ''>
          value={filters.status ?? ''}
          label="Статус"
          onChange={(e) => {
            const val = e.target.value;
            setFilter('status', val === '' ? undefined : val);
          }}
        >
          <MenuItem value="">Все</MenuItem>
          {statusOptions.map((opt) => (
            <MenuItem key={opt.value} value={opt.value}>
              {opt.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      <FormControl size="small" sx={{ minWidth: 120 }}>
        <InputLabel>Приоритет</InputLabel>
        <Select<IdeaPriority | ''>
          value={filters.priority ?? ''}
          label="Приоритет"
          onChange={(e) => {
            const val = e.target.value;
            setFilter('priority', val === '' ? undefined : val);
          }}
        >
          <MenuItem value="">Все</MenuItem>
          {priorityOptions.map((opt) => (
            <MenuItem key={opt.value} value={opt.value}>
              {opt.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      <FormControl size="small" sx={{ minWidth: 120 }}>
        <InputLabel>Модуль</InputLabel>
        <Select
          value={filters.module ?? ''}
          label="Модуль"
          onChange={(e) => setFilter('module', e.target.value || undefined)}
        >
          <MenuItem value="">Все</MenuItem>
          {modules.map((module) => (
            <MenuItem key={module} value={module}>
              {module}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      {hasFilters && (
        <Button
          size="small"
          startIcon={<Clear />}
          onClick={() => {
            clearFilters();
            setSearchValue('');
          }}
        >
          Сбросить
        </Button>
      )}
    </Box>
  );
}
