import styled from 'styled-components';
import * as React from 'react';
import { Colors, Sizes, Variants } from "../../styles";

const sizes = {
    xxs: '5px',
    xs: '10px',
    sm: '20px',
    md: '30px',
    lg: '35px',
    xl: '45px',
    xxl: '60px',
};

interface Props {
    color: Colors;
    size: Sizes;
    variant: Variants;
    round?: boolean;
    fullWidth?: boolean;
}

function getDefaultColor(type: 'font' | 'hover', color: string) {
    let red = 0;
    let green = 0;
    let blue = 0;

    if (color.indexOf('#') !== -1) {
        red = parseInt(color.substr(1, 2), 16);
        green = parseInt(color.substr(3, 2), 16);
        blue = parseInt(color.substr(5, 2), 16);
    } else if (color.indexOf('rgb') !== -1) {
        const array = color.substr(4).replace(')', '').split(',');
        red = parseInt(array[0]);
        green = parseInt(array[0]);
        blue = parseInt(array[0]);
    } else {
    }

    if (red * 0.299 + green * 0.587 + blue * 0.114 > 186) {
        if (type === 'hover') {
            return `rgb(${red * 0.8}, ${green * 0.8}, ${blue * 0.8})`;
        }
        return '#000';
    }
    if (type === 'hover') {
        return `rgb(${red * 1.2}, ${green * 1.2}, ${blue * 1.2})`;
    }
    return '#fff';
}

const StyledButton = styled.button<Props>`
    border: none;
    outline: 0;
    color: ${props => props.variant === 'outlined' ? props.color: getDefaultColor('font', props.color)};
    height: ${props => sizes[props.size]};
    background: ${props => props.theme.colorPalette[props.color]?.main};
    border: ${props => props.variant === 'outlined' && `1px solid ${props.theme.colorPalette[props.color]?.main}`};
    border-radius: ${props => props.round ? '100px' : '3px'};
    width: ${props => props.fullWidth ? '100%' : ''};

    ${ props => (props.variant === 'transparent' || props.variant === 'outlined') && `
        background: transparent;
        color: ${props.theme.colorPalette[props.color]?.main};
    `}

    &:hover {
        cursor: pointer;
        opacity: 0.8;
        background: ${ props => getDefaultColor('hover', props.color)};
        ${ props => (props.variant === 'transparent' || props.variant === 'outlined') && `
            background: ${props.theme.colorPalette[props.color]?.main};
            color: ${props.theme.colorPalette[props.color]?.fontColor};
        `}
    }

    &:focus {
        outline: 0;
    }

    &:active {
        transform: scale(0.95);
    }

    &:disabled,
    &:disabled:hover {
        color: gray;
        background: gray;
        cursor: not-allowed;
    }
`;

export default StyledButton;
