import React, {FC, useState} from "react";

interface Props {
    value: number;
    setValue: (value: number) => void;
}

const RecurrenceInput: FC<Props> = ({ value, setValue}) => {
    const [openInput, setOpenInput] = useState<'category' | 'number'>([7, 365].includes(value) ? 'category' : 'number')

    const toggleInput = (e: React.MouseEvent<HTMLButtonElement>) => {
        e.preventDefault()
        setOpenInput(openInput == 'category' ? 'number' : 'category')
    }

    const toggleButton = () => {
        return (
            <button onClick={toggleInput} className={'mt-2'}>
                {
                    openInput === 'number'
                        ? 'or select from presets'
                        : 'or choose amount of days...'
                }
            </button>
        )
    }

    const prepareValue = (v: string) => {
        setValue(parseInt(v))
    }

    return (
        <div>
        <div className={openInput === 'number' ? 'hidden' : ''}>
                <label htmlFor="recurrence-category" className="block text-sm font-medium">Recurrence</label>
                <select
                    id="recurrence-category"
                    name="recurrence-category"
                    value={value}
                    onChange={(e) => prepareValue(e.target.value)}
                    className="w-full p-2 mb-4 border rounded bg-primary border-secondary bg-gray-600 text-secondary"
                >
                    <option value="7">Weekly</option>
                    <option value="365">Yearly</option>
                </select>
                { toggleButton() }
            </div>

            <div className={openInput === 'number' ? '' : 'hidden'}>
                <label htmlFor="recurrence-number" className="block text-sm font-medium">Recurrence</label>
                <input
                    type="number"
                    id="recurrence-number"
                    name="recurrence-number"
                    value={value}
                    onChange={(e) => prepareValue(e.target.value)}
                    className="p-2 border rounded w-full bg-gray-500 border-secondary"
                />
                { toggleButton() }
            </div>
        </div>
    )
}

export default RecurrenceInput