// src/components/Home.tsx

import React, { useState } 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,
  Box,
} from '@mui/material';

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

  // Получаем список уникальных категорий
  const categories = Array.from(new Set(products.map((p) => p.category)));

  // Фильтрация товаров по поисковому запросу и категории
  const filteredProducts = products.filter((product) => {
    const matchesSearch = product.name
      .toLowerCase()
      .includes(searchTerm.toLowerCase());
    const matchesCategory = category ? product.category === category : true;
    return matchesSearch && matchesCategory;
  });

  // Сортировка товаров
  const sortedProducts = filteredProducts.slice().sort((a, b) => {
    if (sortBy === 'price_asc') {
      return a.price - b.price;
    } else if (sortBy === 'price_desc') {
      return b.price - a.price;
    } else if (sortBy === 'name_asc') {
      return a.name.localeCompare(b.name);
    } else if (sortBy === 'name_desc') {
      return b.name.localeCompare(a.name);
    } else {
      return products.indexOf(a) - products.indexOf(b); // Дефолтное расположение
    }
  });

  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}>
              <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>
            </Grid>
          ))
        ) : (
          <Typography variant="h6">Товары не найдены</Typography>
        )}
      </Grid>
    </div>
  );
};

export default Home; улучшить код