import { hideUpdateModal, showUpdateModal } from "./lines-modal";
import {
    createLine, deleteLine, getAllItemTypes, getAllLines, getLine, updateLine,
} from "./lines-rest-api";
import {
    cntrls, createItemsOption, createTableRow, imagePlaceholder,
} from "./lines-ui";

async function drawItemsSelect() {
    const data = await getAllItemTypes();
    cntrls.itemsType.innerHTML = "";
    cntrls.itemsType.appendChild(createItemsOption("Выберите значение", "", true));
    data.forEach((item) => {
        cntrls.itemsType.appendChild(createItemsOption(item.name, item.id));
    });
}

async function drawLinesTable() {
    console.info("Try to load data");
    if (!cntrls.table) {
        return;
    }
    const data = await getAllLines();
    cntrls.table.innerHTML = "";
    data.forEach((item, index) => {
        cntrls.table.appendChild(
            createTableRow(
                item,
                index,
                () => showUpdateModal(item),
                () => location.assign(`page-edit.html?id=${item.id}`),
                () => removeLine(item.id),
            ),
        );
    });
}

async function addLine(item, price, count, image) {
    console.info("Try to add item");
    const data = await createLine(item, price, count, image);
    console.info("Added");
    console.info(data);
    drawLinesTable();
}

async function editLine(id, item, price, count, image) {
    console.info("Try to update item");
    const data = await updateLine(id, item, price, count, image);
    console.info("Updated");
    console.info(data);
    drawLinesTable();
}

async function removeLine(id) {
    if (!confirm("Do you really want to remove this item?")) {
        console.info("Canceled");
        return;
    }
    console.info("Try to remove item");
    const data = await deleteLine(id);
    console.info(data);
    drawLinesTable();
}
async function readFile(file) {
    const reader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onloadend = () => {
            const fileContent = reader.result;
            resolve(fileContent);
        };
        reader.onerror = () => {
            reject(new Error("oops, something went wrong with the file reader."));
        };

        reader.readAsDataURL(file);
    });
}
async function updateImagePreview() {
    const file = cntrls.image.files[0];
    const fileContent = await readFile(file);
    console.info("base64 ", fileContent);

    cntrls.imagePreview.src = fileContent;
}

export function linesForm() {
    console.info("linesForm");
    drawItemsSelect();
    drawLinesTable();
    cntrls.image.addEventListener("change", () => updateImagePreview());
    cntrls.button.addEventListener("click", () => showUpdateModal(null));
    cntrls.form.addEventListener("submit", async (event) => {
        console.info("Form onSubmit");
        event.preventDefault();
        event.stopPropagation();
        if (!cntrls.form.checkValidity()) {
            return;
        }
        let imageBase64 = "";
        if (cntrls.imagePreview.src !== imagePlaceholder) {
            const result = await fetch(cntrls.imagePreview.src);
            const blob = await result.blob();
            imageBase64 = await readFile(blob);
        }
        const currentId = cntrls.lineId.value;
        if (!currentId) {
            await addLine(
                cntrls.itemsType.value,
                cntrls.price.value,
                cntrls.count.value,
                imageBase64,
            );
        } else {
            await editLine(
                currentId,
                cntrls.itemsType.value,
                cntrls.price.value,
                cntrls.count.value,
                imageBase64,
            );
        }
        hideUpdateModal();
    });
}

export async function linesPageForm() {
    console.info("linesPageForm");
    drawItemsSelect();
    const goBack = () => location.assign("/page4.html");
    cntrls.image.addEventListener("change", () => updateImagePreview());
    const urlParams = new URLSearchParams(location.search);
    const currentId = urlParams.get("id");
    if (currentId) {
        try {
            const line = await getLine(currentId);
            cntrls.itemsType.value = line.itemsId;
            cntrls.price.value = line.price;
            cntrls.count.value = line.count;
            cntrls.imagePreview.src = line.image ? line.image : imagePlaceholder;
        } catch {
            goBack();
        }
    }

    cntrls.form.addEventListener("submit", async (event) => {
        console.info("Form onSubmit");
        event.preventDefault();
        event.stopPropagation();
        if (!cntrls.form.checkValidity()) {
            return;
        }
        let imageBase64 = "";
        if (cntrls.imagePreview.src !== imagePlaceholder) {
            const result = await fetch(cntrls.imagePreview.src);
            const blob = await result.blob();
            imageBase64 = await readFile(blob);
        }
        if (!currentId) {
            await addLine(
                cntrls.itemsType.value,
                cntrls.price.value,
                cntrls.count.value,
                imageBase64,
            );
        } else {
            await editLine(
                currentId,
                cntrls.itemsType.value,
                cntrls.price.value,
                cntrls.count.value,
                imageBase64,
            );
        }
        goBack();
    });
}