import {
  Grid,
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  TextField,
} from '@mui/material';
import { StarBorder, Star, Delete } from '@mui/icons-material';
import { type Book } from './Book';
import { useState } from 'react';

type Props = {
  books: Book[];
};

const BooksList: React.FC<Props> = ({ books }) => {
  const [filter, setFilter] = useState('');
  const [booksState, setBooksState] = useState<Book[]>(books);

  function handleDelete(id: number) {
    setBooksState(booksState.filter((book) => book.id !== id));
  }

  return (
    <Grid container>
      <Grid size={{ md: 1 }} sx={{ display: { sm: 'none', md: 'block' } }} />

      <Grid size={{ xs: 12, md: 10 }}>
        <Paper>
          <TextField
            label="Liste filtern"
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
          />
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Titel</TableCell>
                <TableCell>Autor</TableCell>
                <TableCell>ISBN</TableCell>
                <TableCell>Bewertung</TableCell>
                <TableCell></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {booksState
                .filter((book) =>
                  book.title.toLowerCase().includes(filter.toLowerCase())
                )
                .map((book) => (
                  <TableRow key={book.id}>
                    <TableCell>{book.title}</TableCell>
                    <TableCell>{book.author}</TableCell>
                    <TableCell>{book.isbn}</TableCell>
                    <TableCell>
                      {Array(5)
                        .fill('')
                        .map((_, index) =>
                          book.rating <= index ? (
                            <StarBorder key={index} />
                          ) : (
                            <Star key={index} />
                          )
                        )}
                    </TableCell>
                    <TableCell>
                      <IconButton
                        color="primary"
                        aria-label="Buch löschen"
                        onClick={() => handleDelete(book.id)}
                      >
                        <Delete />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                ))}
            </TableBody>
          </Table>
        </Paper>
      </Grid>

      <Grid size={{ md: 1 }} sx={{ display: { sm: 'none', md: 'block' } }} />
    </Grid>
  );
};

export default BooksList;
