use yew::prelude::*;
use yewdux::prelude::*;

use web_sys::HtmlDialogElement;

use crate::components::states::MainState;
use plate_tool_lib::plate_instances::PlateInstance;

use crate::components::callbacks::new_plate_dialog_callbacks;

#[derive(PartialEq, Properties)]
pub struct NewPlateDialogProps {
    pub close_callback: Callback<()>,
}

#[function_component]
pub fn NewPlateDialog(props: &NewPlateDialogProps) -> Html {
    let (_, dispatch) = use_store::<MainState>();

    let new_plate_callback = {
        let close_callback = props.close_callback.clone();
        new_plate_dialog_callbacks::new_plate_callback(dispatch, close_callback)
    };

    let onclose = {
        let close_callback = props.close_callback.clone();
        new_plate_dialog_callbacks::onclose(close_callback)
    };

    // This whole section is optional, only if you want the backdrop
    let dialog_ref = use_node_ref();
    {
        let dialog_ref = dialog_ref.clone();

        use_effect_with_deps(
            |dialog_ref| {
                dialog_ref
                    .cast::<HtmlDialogElement>()
                    .unwrap()
                    .show_modal()
                    .ok();
            },
            dialog_ref,
        );
    }

    html! {
        <dialog ref={dialog_ref} class="dialog new_plate_dialog" onclose={onclose}>
            <h2>{"Create a plate:"}</h2>
            <form onsubmit={new_plate_callback}>
            <input type="text" name="new_plate_name" placeholder="Name"/>
            <select name="plate_format">
                <option value="6">{"6"}</option>
                <option value="12">{"12"}</option>
                <option value="24">{"24"}</option>
                <option value="48">{"48"}</option>
                <option value="96" selected={true}>{"96"}</option>
                <option value="384">{"384"}</option>
                <option value="1536">{"1536"}</option>
                <option value="3456">{"3456"}</option>
            </select>
            <input type="radio" name="new_plate_type" id="npt_src" value="src" />
            <label for="npt_src">{"Source"}</label>
            <input type="radio" name="new_plate_type" id="npt_dest" value="dest" />
            <label for="npt_dest">{"Destination"}</label>
            <input type="submit" name="new_plate_button" value="Create" />
            </form>
            <form class="modal_close" method="dialog"><button /></form>
        </dialog>
    }
}
