import React, { useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import products from '../data/products';
import {
  Grid,
  Card,
  CardMedia,
  CardContent,
  Typography,
  Button,
  TextField,
  Select,
  MenuItem,
  InputLabel,
  FormControl,
} from '@mui/material';

const Home: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [category, setCategory] = useState<string>('');
  const [sortBy, setSortBy] = useState<string>('');

  const categories = useMemo(() => Array.from(new Set(products.map((p) => p.category))), [products]);

  const filteredProducts = useMemo(() => {
    return products.filter(product => {
      const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesCategory = category ? product.category === category : true;
      return matchesSearch && matchesCategory;
    });
  }, [searchTerm, category, products]);

  const sortedProducts = useMemo(() => {
    const sortFunctions: { [key: string]: (a: typeof products[0], b: typeof products[0]) => number } = {
      "price_asc": (a, b) => a.price - b.price,
      "price_desc": (a, b) => b.price - a.price,
      "name_asc": (a, b) => a.name.localeCompare(b.name),
      "name_desc": (a, b) => b.name.localeCompare(a.name),
    };
    return sortFunctions[sortBy]
      ? [...filteredProducts].sort(sortFunctions[sortBy])
      : filteredProducts;
  }, [filteredProducts, sortBy]);

  const ProductCard: React.FC<{ product: typeof products[0] }> = ({ product }) => (
    <Card>
      <CardMedia
        component="img"
        height="200"
        image={product.image}
        alt={product.name}
      />
      <CardContent>
        <Typography variant="h6">{product.name}</Typography>
        <Typography variant="body2" color="textSecondary" gutterBottom>
          {product.description}
        </Typography>
        <Typography variant="h6">{product.price} ₽</Typography>
        <Button
          variant="contained"
          color="primary"
          component={Link}
          to={`/product/${product.id}`}
        >
          Подробнее
        </Button>
      </CardContent>
    </Card>
  );
  
  return (
    <div>
      <Typography variant="h4" gutterBottom>
        Наши товары
      </Typography>

      <Grid container spacing={2} sx={{ marginBottom: 4 }}>
        <Grid item xs={12} sm={8}>
          <TextField
            label="Поиск"
            variant="outlined"
            fullWidth
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </Grid>
        <Grid item xs={6} sm={2}>
          <FormControl variant="outlined" fullWidth>
            <InputLabel id="category-label">Категория</InputLabel>
            <Select
              labelId="category-label"
              label="Категория"
              value={category}
              onChange={(e) => setCategory(e.target.value as string)}
            >
              <MenuItem value="">
                <em>Все категории</em>
              </MenuItem>
              {categories.map((cat) => (
                <MenuItem value={cat} key={cat}>
                  {cat}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
        <Grid item xs={6} sm={2}>
          <FormControl variant="outlined" fullWidth>
            <InputLabel id="sort-label">Сортировать</InputLabel>
            <Select
              labelId="sort-label"
              label="Сортировать"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as string)}
            >
              <MenuItem value="">
                <em>По умолчанию</em>
              </MenuItem>
              <MenuItem value="price_asc">Цена: по возрастанию</MenuItem>
              <MenuItem value="price_desc">Цена: по убыванию</MenuItem>
              <MenuItem value="name_asc">Название: А-Я</MenuItem>
              <MenuItem value="name_desc">Название: Я-А</MenuItem>
            </Select>
          </FormControl>
        </Grid>
      </Grid>

      <Grid container spacing={4}>
        {sortedProducts.length > 0 ? (
          sortedProducts.map((product) => (
            <Grid item xs={12} sm={6} md={4} key={product.id}>
              <ProductCard product={product} />
            </Grid>
          ))
        ) : (
          <Typography variant="h6">Товары не найдены</Typography>
        )}
      </Grid>
    </div>
  );
};

export default Home; упростить код