import {
    FormControl,
    FormControlLabel,
    FormLabel,
    Radio,
    RadioGroup,
    Rating,
    useTheme,
} from "@mui/material";
import React from "react";

type FilterItemOption = {
    value: string;
    label: string;
};

type FilterItemProps = {
    filterName: string;
    filterItems: FilterItemOption[];
    value?: string | null;
    onChange?: (value: string) => void;
};

export default function FilterItem({
    filterName,
    filterItems,
    value,
    onChange,
}: FilterItemProps) {
    const theme = useTheme();

    if (!value && filterItems.length > 0) {
        value = filterItems[0].value;
    }

    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (onChange) {
            onChange(event.target.value);
        }
    };

    return (
        <div style={{ marginBottom: "1.5rem" }}>
            <FormLabel
                component="legend"
                sx={{
                    fontWeight: "bold",
                    color: theme.palette.text.primary,
                    mb: 1,
                }}
            >
                {filterName}
            </FormLabel>

            <FormControl>
                <RadioGroup value={value} onChange={handleChange}>
                    {filterItems.map((item, idx) => (
                        <FormControlLabel
                            key={idx}
                            value={item.value}
                            control={<Radio />}
                            label={
                                /^[1-5]$/.test(item.value) ? (
                                    <Rating
                                        readOnly
                                        value={Number(item.value)}
                                        precision={1}
                                        size="small"
                                    />
                                ) : (
                                    item.label
                                )
                            }
                            sx={{
                                color: theme.palette.text.primary,
                            }}
                        />
                    ))}
                </RadioGroup>
            </FormControl>
        </div>
    );
}
