import { useState, useEffect } from 'react';
import Radio from './../../atoms/Radio/Radio';
import Text from './../../atoms/Text/Text';
import Block from './../../atoms/Block/Block';
import Label from './../../atoms/Label/Label';

export interface RadioProp {
    value: string;
    label: string;
    message?: string;
}

export interface RadioGroupProps {
    /**
     * An array that will be used to render the radio group.
     */
    data?: RadioProp[];
    /**
     * name for all radio inputs.
     */
    name: string;
    /**
     * Tailwind css classes for the main container and included components.
     */
    className?: string;
    /**
     * Text for the Label of the radio group.
     */
    label?: string;
    /**
     * Text for the message of the radio group.
     */
    message?: string;

    /**
     * Will disable the radio group
     */
    disabled?: boolean;
    /**
     * A function that will trigger on change, and return an string with the selected radio value.
     */
    onChange?: (value?: string) => void;
    /**
     * RadioGroup variation that will switch between styles .
     */
    variation?: 'initial' | 'default' | 'primary' | 'secondary';
    /**
     * ClassName on the message element.
     */
    messageClassName?: string;
}

export const RadioGroup: React.FC<RadioGroupProps> = (props) => {
    const { label, className, disabled, data, onChange, variation, messageClassName } = props;
    const [state, setState] = useState(data ? data[0].value : undefined);

    useEffect(() => {
        if (onChange) onChange(state);
    }, [state, onChange]);

    return (
        <Block className={`w-full ml-1 flex flex-col ${className}`}>
            {label ? <Label className="cursor-auto">{label}</Label> : ''}
            {data
                ? data.map((radio) => (
                      <span onClick={() => setState(radio.value)} className={'pb-1'} key={radio.value}>
                          <span
                              className={`relative flex w-full items-center ${
                                  !disabled ? 'cursor-pointer' : 'cursor-not-allowed'
                              }`}
                          >
                              <Radio variation={variation} checked={state === radio.value} value={radio.value} />
                              <Text className="inline-block pl-2 truncate">{radio.label}</Text>
                          </span>
                          {radio.message ? (
                              <Text
                                  className={`inline-flex pt-1 pb-2 text-sm font-light pl-7 ${messageClassName ?? ''}`}
                              >
                                  {radio.message}
                              </Text>
                          ) : (
                              ''
                          )}
                      </span>
                  ))
                : ''}
        </Block>
    );
};

export default RadioGroup;
