import { Box, Button, Typography, useTheme } from "@mui/material";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useBasket } from "../helper/BasketProvider";
import ItemCard from "../helper/homepage/ItemCard";
import AddShoppingCartIcon from '@mui/icons-material/AddShoppingCart';

import farmingStation from '../assets/fscomponents/fs_components_0.png';
import environment from '../assets/fscomponents/fs_components_1.png';
import hoses from '../assets/fscomponents/fs_components_2.png';
import pipes from '../assets/fscomponents/fs_components_3.png';
import pumps from '../assets/fscomponents/fs_components_4.png';
import sensors from '../assets/fscomponents/fs_components_5.png';
import shelf from '../assets/fscomponents/fs_components_6.png';
import connectors from '../assets/fscomponents/fs_components_7.png';
import clips from '../assets/fscomponents/fs_components_8.png';
import arduino from '../assets/fscomponents/fs_components_9.png';
import Item from "../components/Item";

// API-Funktion, Items laden (URL anpassen!)
async function fetchItemList(): Promise<Item[]> {
    const response = await fetch('/api/items');
    if (!response.ok) throw new Error('Failed to fetch items');
    return response.json();
}

export default function FSComponents() {
    const { t } = useTranslation();
    const theme = useTheme();
    const { addToBasket } = useBasket();
    const [hoverIndex, setHoverIndex] = useState<number | null>(null);

    // Sehr sehr dummer Weg das zu machen, aber wird später noch refactored
    const wantedIds = ["60", "67", "68", "69", "70", "71", "72", "73", "74", "75"];

    // Daten mit react-query laden
    const { data = [], isLoading, error } = useQuery<Item[]>({
        queryKey: ['fetchItemList'],
        queryFn: fetchItemList,
        retry: 3,
        retryDelay: 1000,
    });

    // Filter auf wantedIds
    const filteredItems = data.filter(item => wantedIds.includes(item.id));

    // Button-Funktion: alle gefilterten Items in den Warenkorb packen
    const handleAddAllToCart = () => {
        filteredItems.forEach(item => {
            addToBasket(item, 1);
        });
    };

    // Zuordnung Bilder (Annahme: 9 Bilder für 9 Items)
    const componentImages = [
        arduino,
        farmingStation,
        environment,
        pipes,
        pumps,
        sensors,
        shelf,
        hoses,
        connectors,
        clips,
    ];

    if (isLoading) return <Typography>{t('loading')}</Typography>;
    if (error) return <Typography color="error">{t('errorLoadingItems')}</Typography>;

    return (
        <Box sx={{ width: '100%', display: 'flex', maxWidth: 1600, mx: 'auto', pt: 2, height: '100vh' }}>
            {/* Bild links */}
            <Box sx={{
                width: 'auto',
                height: '90vh',
                position: 'sticky',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                padding: 2,
                overflow: 'hidden',
            }}>
                <Box
                    component="img"
                    src={hoverIndex !== null ? componentImages[hoverIndex] : farmingStation}
                    alt={t('componentsFarmingStation')}
                    sx={{
                        width: '100%',
                        height: 'auto',
                        maxHeight: '80vh',
                        objectFit: 'contain',
                        borderRadius: 2,
                        border: `4px solid ${theme.palette.primary.main}`,
                        marginBottom: 2,
                    }}
                />
                <Button
                    variant="contained"
                    fullWidth
                    startIcon={<AddShoppingCartIcon />}
                    onClick={handleAddAllToCart}
                >
                    {t('addAllToCart')}
                </Button>
            </Box>

            {/* Items rechts */}
            <Box sx={{
                width: '60%',
                height: '90vh',
                overflowY: 'auto',
                padding: 2,
            }}>
                <Box mb={2}>
                    <Typography variant="h4" align="center" gutterBottom sx={{ color: 'text.primary' }}>
                        {t('componentsFarmingStation')}
                    </Typography>
                </Box>
                <Box className="cardgrid">
                    {filteredItems.map((item, index) => (
                        <div
                            key={item.id}
                            onMouseEnter={() => setHoverIndex(index)}
                            onMouseLeave={() => setHoverIndex(null)}
                        >
                            <ItemCard item={item} />
                        </div>
                    ))}
                </Box>
            </Box>
        </Box>
    );
}
