import { Combobox, Option, Spinner } from "@fluentui/react-components";
import { CustomCellEditorProps } from "ag-grid-react";
import axios from "axios";
import useSWR from "swr";

export default ({ value, onValueChange }: CustomCellEditorProps) => {
    const { data: fuelTypes } = useSWR('/fuel/fuel-types', () => axios.get(`/fuel/fuel-types`, {
        baseURL: import.meta.env.VITE_API_NEST_URL
    }).then(res => res.data))

    if (fuelTypes) {
        return (
            <Combobox
                autoFocus
                placeholder="Тип топлива"
                clearable
                value={fuelTypes.find((f: {
                    id: number
                    name: string
                }) => f.id === value).name}
                style={{
                    width: '100%',
                    height: '100%',
                    marginTop: '-4px'
                }}
                size='small'
                onOptionSelect={(_, data) => {
                    onValueChange(data.optionValue === '' || data.optionValue === undefined ? null : data.optionValue)
                }}
            >
                {fuelTypes && Array.isArray(fuelTypes) && fuelTypes.map((option) => (
                    <Option key={option.id} text={option.name} value={option.id}>
                        {option.name}
                    </Option>
                ))}
            </Combobox>
        );
    } else {
        return (
            <Spinner />
        )
    }
}