import { useReminder } from "./ReminderContext";
import { useFlash } from "../App/FlashContext";

export const Attachment = () => {
    const [{ attachment_name }, setReminder] = useReminder();

    const flash = useFlash();

    return (
        <div class="file is-small is-boxed">
            <label class="file-label">
                <input
                    class="file-input"
                    type="file"
                    name="attachment"
                    onInput={async (ev) => {
                        const input = ev.currentTarget;

                        let file = input.files[0];

                        if (file.size >= 8 * 1024 * 1024) {
                            flash({ message: "File too large (max. 8MB).", type: "error" });
                            return;
                        }

                        let attachment: string = await new Promise((resolve) => {
                            let fileReader = new FileReader();
                            fileReader.onload = () => resolve(fileReader.result as string);
                            fileReader.readAsDataURL(file);
                        });
                        attachment = attachment.split(",")[1];
                        const attachment_name = file.name;

                        setReminder((reminder) => ({
                            ...reminder,
                            attachment,
                            attachment_name,
                        }));
                    }}
                ></input>
                <span class="file-cta">
                    <span
                        class="file-label"
                        style={{
                            maxWidth: "200px",
                        }}
                    >
                        {attachment_name || "Add Attachment"}
                    </span>
                    <span class="file-icon">
                        <i class="fas fa-upload"></i>
                    </span>
                </span>
            </label>
            {attachment_name && (
                <>
                    <button
                        onClick={() => {
                            setReminder((reminder) => ({
                                ...reminder,
                                attachment: null,
                                attachment_name: null,
                            }));
                        }}
                        style={{
                            border: "none",
                            background: "none",
                            cursor: "pointer",
                        }}
                    >
                        <span class="sr-only">Remove attachment</span>
                        <span class="icon">
                            <i class="fas fa-trash"></i>
                        </span>
                    </button>
                </>
            )}
        </div>
    );
};
