import React from "react"
import { IconButton, SvgIcon } from "@mui/material"
import { DataFilterType, FiltersMessage } from "../types/filter.type"
import { FilterAutocompleteField, FilterInputContainer, FilterTextField } from "./style"

export interface DataTableFilterBooleanProps {
    style?: React.CSSProperties,
    messages: FiltersMessage,
    value: DataFilterType | [DataFilterType, DataFilterType]
    onChange: (value: boolean | null) => void,
}

export const DataTableFilterBoolean: React.FC<DataTableFilterBooleanProps> = ({ style, messages, value, onChange }) => {
    const getValue = () => {
        const bool = (v: any): boolean | null => {
            return typeof v === 'boolean'
                ? v
                : v === 'true'
                    ? true
                    : v === 'false'
                        ? false
                        : null
        }
        return Array.isArray(value)
            ? !value.length
                ? null
                : bool(value[0])
            : bool(value)
    }
    const handleChange = (event: any, value: any) => {
        onChange(value)
    }
    const handleClear = () => {
        onChange(null)
    }

    return (
        <FilterInputContainer style={style}>
            <FilterAutocompleteField
                options={[true, false]}
                getOptionLabel={(option: any) => option ? messages.true : messages.false}
                value={getValue()}
                onChange={handleChange}
                renderInput={(params: any) => {
                    let endAdornment = params.InputProps.endAdornment as any;
                    const adornmentChildren = endAdornment && endAdornment.props && endAdornment.props.children
                        ? endAdornment.props.children
                        : null;

                    if (adornmentChildren && Array.isArray(adornmentChildren) && adornmentChildren.length > 0) {
                        endAdornment = adornmentChildren[adornmentChildren.length - 1];
                    }
                    return (
                        <FilterTextField
                            {...params}
                            variant="standard"
                            InputProps={{ ...params.InputProps, endAdornment }} />
                    )
                }}
            />
            <IconButton className="filter-clear-button" onClick={handleClear} >
                <CloseIcon />
            </IconButton>
        </FilterInputContainer>
    )
}

const CloseIcon = () => (
    <SvgIcon fontSize="small" width="24" height="24" overflow="hidden" viewBox="0 0 24 24">
        <g>
            <path d="M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
        </g>
    </SvgIcon>
)