import { Slider, Typography, Box, useTheme } from "@mui/material";
import { useState, useEffect, SyntheticEvent } from "react";
import { useTranslation } from "react-i18next";

type PriceSliderProps = {
    min?: number;
    max?: number;
    onChange?: (range: [number, number]) => void;
};

export default function PriceSlider({ min = 0, max = 10000, onChange }: PriceSliderProps) {
    const { t } = useTranslation();
    const theme = useTheme();

    const [value, setValue] = useState<[number, number]>([min, max]);

    useEffect(() => {
        setValue([min, max]);
        onChange?.([min, max]);
    }, [min, max]);

    const handleChange = (_: Event, newValue: number | number[]) => {
        if (Array.isArray(newValue)) {
            setValue([newValue[0], newValue[1]]);
        }
    };

    const handleCommitted = (_: Event | SyntheticEvent<Element, Event>, newValue: number | number[]) => {
        if (Array.isArray(newValue)) {
            onChange?.([newValue[0], newValue[1]]);
        }
    };

    const formatValueToEuro = (val: number) => `${(val/100).toFixed(2)} €`;

    return (
        <Box sx={{ mb: 4 }}>
            <Typography
                variant="h6"
                sx={{
                    fontWeight: "bold",
                    color: theme.palette.text.primary,
                    mb: 1,
                }}
            >
                {t("price")}
            </Typography>

            <Box sx={{ px: 1 }}>
                <Slider
                    value={value}
                    onChange={handleChange}
                    onChangeCommitted={handleCommitted}
                    valueLabelDisplay="auto"
                    valueLabelFormat={formatValueToEuro}
                    min={min}
                    max={max}
                    step={1}
                    sx={{
                        color: "#0fd13f",
                        '& .MuiSlider-valueLabel': {
                            color: theme.palette.text.primary,
                        },
                    }}
                />

                <Typography
                    variant="body2"
                    sx={{
                        mt: 1,
                        color: theme.palette.text.primary,
                        fontSize: "0.9rem",
                        textAlign: "center",
                    }}
                >
                    {formatValueToEuro(value[0])} – {formatValueToEuro(value[1])}
                </Typography>
            </Box>
        </Box>
    );
}
