import { useState } from "react";
import { Button, Form } from "react-bootstrap";
import useEditablePolyline from "../../../../hooks/useEditablePolyline";
import { addNewCluster } from "../../../../store/asyncMethods/clusterMethod";
import { useDispatch } from "react-redux";
import { toast } from "react-hot-toast";

const ClusterCreate = ({ handleClose }) => {
    const dispatch = useDispatch();
    const [clusterForm, setClusterForm] = useState({
        name: "",
        remarks: "",
        isBox: false,
    });
    const { coordinates, reset } = useEditablePolyline();

    const onChangeHandler = (event) => {
        setClusterForm({
            ...clusterForm,
            [event.target.name]: event.target.value,
        });
    };

    const onCheckBoxClickHandler = (event) => {
        setClusterForm({ ...clusterForm, isBox: event.target.checked });
    };

    const onSubmitHandler = (event) => {
        event.preventDefault();
        if (coordinates.length !== 1) return;

        const clusterInfo = {
            name: clusterForm.name,
            coordinates: coordinates[0],
            isBox: clusterForm.isBox,
            remarks: clusterForm.remarks,
        };
        dispatch(
            addNewCluster(clusterInfo, (cluster) => {
                reset();
                handleClose();
                toast.success(`${cluster.name} Cluster Added Successfully.`);
            })
        );
    };

    return (
        <Form onSubmit={onSubmitHandler} className="mt-2">
            <Form.Group className="mt-2">
                <Form.Control
                    type="text"
                    placeholder="Enter Cluster Name"
                    onChange={onChangeHandler}
                    name="name"
                />
            </Form.Group>
            <Form.Group className="mt-2">
                <Form.Check
                    type="checkbox"
                    label={`Is it box?`}
                    className="mt-1 ms-1"
                    onChange={onCheckBoxClickHandler}
                />
            </Form.Group>
            <Form.Group className="mt-2">
                <Form.Control
                    as="textarea"
                    placeholder="Remarks"
                    rows={3}
                    onChange={onChangeHandler}
                    name="remarks"
                />
            </Form.Group>
            <Form.Group className="mt-2 text-right">
                <Button variant="secondary" onClick={handleClose}>
                    Close
                </Button>
                <Button variant="primary" type="submit" className="ms-1">
                    Submit
                </Button>{" "}
            </Form.Group>
        </Form>
    );
};

export default ClusterCreate;
