import {useState} from "react";
import {Box, TextField, Tooltip, Typography} from "@mui/material";

type Props = {
    allSprites: any[]; // [{key, name, drawFn, ...}]
    selected: any;
    onSelect: (s: any) => void;
    orientation?: "vertical" | "horizontal";
};

export default function SpritePalette({allSprites, selected, onSelect, orientation = "vertical"}: Props) {
    const [search, setSearch] = useState("");
    const [hovered, setHovered] = useState<any | null>(null);

    // Simple filtre sur nom ou catégorie
    const filtered = allSprites.filter(s =>
        s.key.toLowerCase().includes(search.toLowerCase()) ||
        (s.category && s.category.toLowerCase().includes(search.toLowerCase()))
    );

    return (
        <Box sx={{
            width: 110, minWidth: 90, maxWidth: 140, bgcolor: "#f4f5fa", py: 1, px: 1,
            overflowY: "auto", borderRight: "1px solid #ccc"
        }}>
            <TextField
                placeholder="Recherche sprite..."
                value={search}
                onChange={e => setSearch(e.target.value)}
                size="small"
                sx={{mb: 1, width: "100%"}}
            />
            <Box sx={{
                display: "flex",
                flexDirection: orientation === "vertical" ? "column" : "row",
                gap: 1,
                flexWrap: "wrap"
            }}>
                {filtered.map(sprite => (
                    <Tooltip key={sprite.key} title={
                        <Box>
                            <Typography fontWeight="bold">{sprite.name || sprite.key}</Typography>
                            <Typography fontSize={12}>{sprite.category}</Typography>
                            <Box sx={{width: 48, height: 48}}>
                                {/* Mini preview */}
                                <canvas ref={ref => {
                                    if (ref && sprite.drawFn) {
                                        const ctx = ref.getContext("2d")!;
                                        ctx.clearRect(0, 0, 48, 48);
                                        drawSpritePreview(sprite, ctx, 48, 48);
                                    }
                                }} width={48} height={48}/>
                            </Box>
                        </Box>
                    }>
                        <Box
                            onClick={() => onSelect(sprite)}
                            onMouseEnter={() => setHovered(sprite)}
                            onMouseLeave={() => setHovered(null)}
                            sx={{
                                width: 48,
                                height: 48,
                                mb: 1,
                                borderRadius: 1,
                                border: sprite === selected ? "2px solid #1976d2" : "1px solid #aaa",
                                overflow: "hidden",
                                cursor: "pointer",
                                bgcolor: hovered === sprite ? "#e3e6f6" : "#fff"
                            }}
                        >
                            {/* Aperçu direct */}
                            <canvas ref={ref => {
                                if (ref && sprite.drawFn) {
                                    const ctx = ref.getContext("2d")!;
                                    ctx.clearRect(0, 0, 48, 48);
                                    drawSpritePreview(sprite, ctx, 48, 48);
                                }
                            }} width={48} height={48}/>
                        </Box>
                    </Tooltip>
                ))}
            </Box>
        </Box>
    );
}

// Ajoute cette fonction dans SpritePalette.tsx ou dans un util
function drawSpritePreview(sprite, ctx, w, h) {
    try {
        if (!sprite || !sprite.drawFn) return;
        // Si animé : force frame 0
        if (sprite.type === "animated" && sprite.frames?.length > 0) {
            sprite.drawFn(ctx, 0, 0, {w, h, frame: 0});
        }
        // Si static : normal
        else if (sprite.type === "static") {
            sprite.drawFn(ctx, 0, 0, {w, h});
        }
        // Fallback : tente sans rien
        else {
            sprite.drawFn(ctx, 0, 0, {w, h});
        }
    } catch (e) {
        ctx.clearRect(0, 0, w, h);
        ctx.fillStyle = "#f88";
        ctx.fillRect(0, 0, w, h);
        ctx.fillStyle = "#222";
        ctx.font = "bold 10px sans-serif";
        ctx.fillText("?", 16, 32);
    }
}

