// node modules
import React, { ChangeEvent } from 'react';

// local components
import { Typography } from "../typography";

// local files
import ddArrow from '../../assets/dropdown-arrow.svg';
import { useStyles } from "./styles";
import { theming } from "../../theme";

type Option = {
    value: number | string;
    displayValue: number | string;
}

export interface SelectProps {
    options?: Option[];
    value?: Option;
    onChange?: (e :ChangeEvent<HTMLSelectElement>) => void;
    rootClassName?: string;
    selectClassName?: string;
    disabled?: boolean;
    error?: boolean,
    placeholder?: string;
}

const defaultValue: Option = {
    value: '',
    displayValue: ''
}

export const Select = ({
    error = false,
    rootClassName = '',
    selectClassName = '',
    options = [],
    placeholder,
    value = defaultValue,
    onChange,
    disabled,
    ...otherProps
}: SelectProps) => {
    const { value: selectedValue } = value;
    const {
        root,
        labelClass,
        selectClass,
        active,
        activeSelect,
        arrowWrapper,
        disabledClass,
        errorClass,
        hideFirstOption
    } = useStyles({ theme: theming.useTheme() });
    const rootClass = `${root} ${rootClassName} ${disabled ? disabledClass : ''} ${error ? errorClass : '' }`;
    const labelClassName = `${labelClass} ${selectedValue !== '' ? active : ''}`;
    const selectRootClassName = `${selectClass} ${selectClassName} ${selectedValue ? activeSelect: ''}`;

    const handleChange = (e: ChangeEvent<HTMLSelectElement>) => {
        if(onChange) {
            onChange(e)
        }
    };

    return (
        <div className={rootClass}>
            {placeholder && <Typography variant="body2" className={labelClassName}>{placeholder}</Typography>}
            <div className={arrowWrapper}>
                <img src={ddArrow} alt=""/>
            </div>
            <select
                disabled={disabled}
                onChange={handleChange}
                value={selectedValue}
                className={selectRootClassName}
                {...otherProps}
            >
                <option disabled className={hideFirstOption}/>
                <option disabled value="">
                    {placeholder}
                </option>
                {options.map(({ value, displayValue }: Option) => {
                    return (
                        <option key={value} value={value}>
                            {displayValue}
                        </option>
                    )
                })}
            </select>
        </div>
    )
}
