import { useState } from "preact/hooks";
import { Modal } from "../Modal";
import { useQuery } from "react-query";
import { fetchGuildTemplates } from "../../api";
import { useParams } from "wouter";
import { useReminder } from "./ReminderContext";

export const LoadTemplate = () => {
    const [modalOpen, setModalOpen] = useState(false);

    return (
        <div>
            <button
                class="button is-outlined show-modal is-pulled-right"
                onClick={() => {
                    setModalOpen(true);
                }}
            >
                Load Template
            </button>
            {modalOpen && <LoadTemplateModal setModalOpen={setModalOpen}></LoadTemplateModal>}
        </div>
    );
};

const LoadTemplateModal = ({ setModalOpen }) => {
    const { guild } = useParams();
    const [reminder, setReminder] = useReminder();
    const { isSuccess, data: templates } = useQuery(fetchGuildTemplates(guild));

    const [selected, setSelected] = useState(null);

    return (
        <Modal setModalOpen={setModalOpen} title={"Load Template"}>
            <div class="control has-icons-left">
                <div class="select is-fullwidth">
                    <select
                        id="templateSelect"
                        onChange={(ev) => {
                            setSelected(ev.currentTarget.value);
                        }}
                    >
                        <option disabled={true} selected={true}>
                            Choose template...
                        </option>
                        {isSuccess &&
                            templates.map((template) => (
                                <option value={template.id}>{template.name}</option>
                            ))}
                    </select>
                </div>
                <div class="icon is-small is-left">
                    <i class="fas fa-file-spreadsheet"></i>
                </div>
            </div>
            <br></br>
            <div class="has-text-centered">
                <button
                    class="button is-success close-modal"
                    id="load-template"
                    onClick={() => {
                        setReminder((reminder) => ({
                            ...reminder,
                            // todo this probably needs to exclude some things
                            ...templates.find((template) => template.id === selected),
                        }));
                    }}
                >
                    Load Template
                </button>
                <button class="button is-danger" id="delete-template">
                    Delete
                </button>
            </div>
        </Modal>
    );
};
