import { useState } from 'react';
import { Button, Form } from 'react-bootstrap';
import { setViewKey } from '../../../../../../store/reducers/currentClusterReducer';
import { useDispatch } from 'react-redux';
import { addSplitterToCluster } from '../../../../../../store/asyncMethods/splitterMethod';

const AddSplitter = () => {
    const dispatch = useDispatch();
    const [splitter, setSplitter] = useState({
        name: '',
        split_ratio: '',
        remarks: '',
    });

    const onChangeHandler = (e) => {
        setSplitter({ ...splitter, [e.target.name]: e.target.value });
    };

    const onSubmitHandler = async (e) => {
        e.preventDefault();
        const newSplitter = {
            name: splitter.name,
            split_ratio: parseInt(splitter.split_ratio),
            remarks: splitter.remarks,
        };

        dispatch(
            addSplitterToCluster(newSplitter, () => {
                dispatch(setViewKey('view'));
                setSplitter({
                    name: '',
                    ratio: '',
                    remarks: '',
                });
            })
        );
    };

    return (
        <Form onSubmit={onSubmitHandler}>
            <Form.Group className='mb-3'>
                <Form.Control
                    type='text'
                    placeholder='Splitter Name'
                    name='name'
                    onChange={onChangeHandler}
                    value={splitter.name}
                />
            </Form.Group>
            <Form.Group className='mb-3'>
                <Form.Select
                    name='split_ratio'
                    onChange={onChangeHandler}
                    value={splitter.split_ratio}
                >
                    <option value='null'>Select Splitter Ratio</option>
                    <option value='2'>1:2</option>
                    <option value='4'>1:4</option>
                    <option value='8'>1:8</option>
                    <option value='16'>1:16</option>
                    <option value='32'>1:32</option>
                </Form.Select>
            </Form.Group>
            <Form.Group className='mb-3'>
                <Form.Control
                    as='textarea'
                    placeholder='Remarks'
                    rows={3}
                    name='remarks'
                    onChange={onChangeHandler}
                    value={splitter.remarks}
                />
            </Form.Group>
            <Button type='submit'>Submit</Button>
        </Form>
    );
};

export default AddSplitter;
