import { AddShoppingCart } from "@mui/icons-material";
import { Box, Card, CardActionArea, CardContent, CardMedia, IconButton, Paper, Rating, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next';
import { useNavigate } from "react-router-dom";
import Item from "../../components/Item";
import { useBasket } from "../BasketProvider";
import "../helper.css";

export default function ItemCard({ item }: { item: Item }) {

    const { t } = useTranslation();
    const navigate = useNavigate()
    const { addToBasket } = useBasket();

    const handleAddToCart = () => {
        addToBasket(item, 1);
        console.log(`Added ${1} of ${item.name} to basket`);
    };

    const handleClick = () => {
        navigate(`/product/${item.id}`, { state: { item } });
    }
    const [imageUrl, setImageUrl] = useState<string>("/src/assets/default.jpg"); // Fallback-Bild

    useEffect(() => {
        const fetchImage = async () => {
            try {
                const response = await fetch(`http://localhost:8085/image?uuid=${item.uuid}`); //image/* as base64
                var data = await response.text();
                if(!data.startsWith("data:image/")) {
                    data = "data:image/jpeg;base64," + data
                }
                setImageUrl(data);
            } catch (error) {
                console.error("Fehler beim Laden des Bildes:", error);
            }
        };

        fetchImage();
    }, [item.uuid]);


    return (
        <Paper elevation={4}>
            <Card sx={{height: "100%", width: "100%" }}>
                <CardActionArea onClick={handleClick} sx={{ height: "100%" }} component="div">
                    <CardMedia
                        component="img"
                        height="140"
                        image={imageUrl}
                        alt={item.name}
                        onError={(event) => {
                            event.currentTarget.src = "/src/assets/default.jpg"; // Standardbild setzen
                        }}
                        sx={{
                            objectFit: "contain", // Bild wird skaliert, um vollständig sichtbar zu sein
                            maxWidth: "100%", // Begrenze die maximale Breite auf den Container
                            maxHeight: "100%", // Begrenze die maximale Höhe auf den Container
                        }}
                    />
                    <CardContent>
                        <Typography gutterBottom variant="h5" component="div">
                            {item.name}
                        </Typography>
                        <Rating name="half-rating" readOnly defaultValue={item.rating /2} precision={0.01} />
                        <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
                            <Typography variant="body2" sx={{ color: 'text.secondary' }} className="item-description">
                                {(item.price100 / 100 * (1 - item.discount100 / 100)).toFixed(2)} €
                            </Typography>
                            <IconButton
                                aria-label={t('addToCart')}
                                onClick={(event) => {
                                    event.stopPropagation();
                                    handleAddToCart();
                                }}
                            >
                                <AddShoppingCart />
                            </IconButton>
                        </Box>

                        {item.stock > 10 ? (
                            <Typography variant="body2">
                                {t('inStock')}
                            </Typography>
                        ) : item.stock > 0 ? (
                            <Typography variant="body2" sx={{ color: 'orange' }}>
                                {t('almostSoldOut')}
                            </Typography>
                        ) : (
                            <Typography variant="body2" sx={{ color: 'red' }}>
                                {t('outOfStock')}
                            </Typography>
                        )}
                    </CardContent>
                </CardActionArea>
            </Card>
        </Paper>
    )
}