import { useReminder } from "./ReminderContext";

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

    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) {
                            return { error: "File too large." };
                        }

                        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">{attachment_name || "Add Attachment"}</span>
                    <span class="file-icon">
                        <i class="fas fa-upload"></i>
                    </span>
                </span>
            </label>
        </div>
    );
};
