const Territory_list = {
    init: async () => {
        let html = await fetch('/lib/pages/territory/list/index.html').then((response) => response.text());
        app.innerHTML = html;

        let selectStatus = document.getElementById('list-controls-filter-status');
        let territory_list_filter = localStorage.getItem("territory_list_filter") ? Number(localStorage.getItem("territory_list_filter")) : 0;
        selectStatus.value = territory_list_filter;

        if (USER.mode == 2) {
            document.getElementById("historyButton").style.display = "";
        }
        if (USER.possibilities.can_add_territory) {
            document.getElementById("constructorButton").style.display = "";
        }

        // Застосовуємо режим сортування
        Territory_list.sort(localStorage.getItem('territory_list_sort'));


        if (localStorage.getItem('territory_list_entrances') == 'true') {
            document.getElementById('territory_entrances_true').setAttribute('data-state', '')
            document.getElementById('territory_entrances_false').setAttribute('data-state', 'active')
        } else {
            document.getElementById('territory_entrances_true').setAttribute('data-state', 'active')
            document.getElementById('territory_entrances_false').setAttribute('data-state', '')
        }
    },

    // Сортування
    sort(mode) {
        const idx = Math.max(1, Math.min(4, Number(mode) || 1));
        ['sort_1', 'sort_2', 'sort_3', 'sort_4'].forEach((id, i) => {
            document.getElementById(id)?.setAttribute('data-state', i + 1 === idx ? 'active' : '');
        });
        localStorage.setItem('territory_list_sort', idx);

        Territory_list.house.setHTML();
        Territory_list.homestead.setHTML();
    },

    house: {
        url: null,
        list: [],
        loadAPI: async function (url) {
            const uuid = localStorage.getItem("uuid");
            const response = await fetch(url ?? Territory_list.house.url, {
                method: 'GET',
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": uuid
                }
            });
            Territory_list.house.list = await response.json();
            return Territory_list.house.list;
        },
        setHTML: async function () {
            const block = document.getElementById('list-house');
            const territory_entrances = localStorage.getItem('territory_list_entrances') === 'true';
            const sort_mode = localStorage.getItem('territory_list_sort') ?? "1";
            const territory_list_filter = Number(localStorage.getItem("territory_list_filter") ?? 0);

            const url = `${CONFIG.api}houses/list${territory_entrances ? '/entrances' : ''}`;
            Territory_list.house.url = url;
            let list = this.list.length > 0 ? this.list : await this.loadAPI(url);

            const isEnd = territory_list_filter === "2";
            const field = isEnd ? "end" : "start";

            const compare = {
                "1": (a, b) => this.compareAB(a, b, territory_entrances, 'asc'),
                "2": (a, b) => this.compareAB(a, b, territory_entrances, 'desc'),
                "3": (a, b) => (a.history?.date?.[field] ?? 0) - (b.history?.date?.[field] ?? 0),
                "4": (a, b) => (b.history?.date?.[field] ?? 0) - (a.history?.date?.[field] ?? 0),
            }[sort_mode] ?? ((a, b) => a.id - b.id);

            list.sort(compare);

            block.innerHTML = '';
            for (const element of list) {
                const qty = element.entrance?.quantity ?? 0;
                const work = element.entrance?.working ?? 0;

                const statusMatch =
                    territory_list_filter === 0 ||
                    (territory_list_filter === 1 && qty === work && !territory_entrances) ||
                    (territory_list_filter === 1 && element.working === true) ||
                    (territory_list_filter === 2 && qty !== work && !territory_entrances) ||
                    (territory_list_filter === 2 && element.working === false);

                if (statusMatch) {
                    const card = document.createElement('app-territory-card');

                    if (territory_entrances) {
                        const working = element.working;
                        const person = working
                            ? `${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}`
                            : ``;
                        const overdue = working && (element.history.date.start + (1000 * 2629743 * 4)) <= Date.now();

                        card.image = `${CONFIG.web}cards/house/T${element.house.id}.webp`;
                        card.address = `${element.house.title} ${element.house.number} (${element.title})`;
                        card.link = `/territory/manager/house/${element.house.id}`;
                        card.sheep = person;
                        card.overdue = overdue;
                        block.appendChild(card);
                    } else {
                        const qty = element.entrance.quantity;
                        const work = element.entrance.working;

                        card.image = `${CONFIG.web}cards/house/T${element.id}.webp`;
                        card.address = `${element.title} ${element.number}`;
                        card.link = `/territory/manager/house/${element.id}`;
                        card.atWork = work;
                        card.quantity = qty;
                    }

                    block.appendChild(card);
                }
            }
        },
        compareAB: (a, b, entrances, order = 'asc') => {
            const dir = order === 'asc' ? 1 : -1;
            const ah = entrances ? a.house : a;
            const bh = entrances ? b.house : b;

            const tA = ah.title?.toLowerCase() ?? '';
            const tB = bh.title?.toLowerCase() ?? '';
            if (tA < tB) return -1 * dir;
            if (tA > tB) return 1 * dir;

            const nA = ah.number?.toLowerCase() ?? '';
            const nB = bh.number?.toLowerCase() ?? '';
            if (nA < nB) return -1 * dir;
            if (nA > nB) return 1 * dir;

            return 0;
        },
        territoryType: (type) => {
            localStorage.setItem('territory_list_entrances', type);
            document.getElementById('territory_entrances_true').setAttribute('data-state', type === 'false' ? 'active' : '');
            document.getElementById('territory_entrances_false').setAttribute('data-state', type === 'true' ? 'active' : '');
            Territory_list.house.list = [];
            Territory_list.house.setHTML();
        }
    },
    homestead: {
        list: [],
        loadAPI: async function () {
            const uuid = localStorage.getItem("uuid");
            const URL = `${CONFIG.api}homestead/list`;

            const response = await fetch(URL, {
                method: 'GET',
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": uuid
                }
            });

            Territory_list.homestead.list = await response.json();
            return Territory_list.homestead.list;
        },
        setHTML: async function () {
            const block = document.getElementById('list-homestead');
            const sortMode = localStorage.getItem('territory_list_sort') ?? "1";
            const territory_list_filter = Number(localStorage.getItem("territory_list_filter") ?? 0);

            let list = this.list.length > 0 ? this.list : await this.loadAPI();

            const compare = {
                "1": (a, b) => a.id - b.id,
                "2": (a, b) => b.id - a.id,
                "3": (a, b) => (a.history?.date?.start ?? 0) - (b.history?.date?.start ?? 0),
                "4": (a, b) => (b.history?.date?.start ?? 0) - (a.history?.date?.start ?? 0),
            }[sortMode] ?? ((a, b) => a.id - b.id);

            list.sort(compare);

            block.innerHTML = '';
            for (const element of list) {
                const statusMatch =
                    territory_list_filter === 0 ||
                    (territory_list_filter === 1 && element.working) ||
                    (territory_list_filter === 2 && !element.working);

                if (statusMatch) {
                    const working = element.working;

                    const person = working
                        ? `${element.history.name === 'Групова' ? 'Група ' + element.history.group_id : element.history.name}`
                        : ``;
                       
                    const overdue = working && (element.history.date.start + (1000 * 2629743 * 4)) <= Date.now();

                    const card = document.createElement('app-territory-card');
                    card.image = `${CONFIG.web}cards/homestead/H${element.id}.webp`;
                    card.address = `${element.title} ${element.number}`;
                    card.link = `/territory/manager/homestead/${element.id}`;
                    card.sheep = person;
                    card.overdue = overdue;
                    block.appendChild(card);
                }
            }
        }
    },
    filter: () => {
        let selectStatus = document.getElementById('list-controls-filter-status').value;

        localStorage.setItem("territory_list_filter", selectStatus);


        Territory_list.house.setHTML();
        Territory_list.homestead.setHTML();
    },
    report: async () => {
        Notifier.info('Запит на генерацію звіту опрацювання відправлено');

        const uuid = localStorage.getItem("uuid");
        const url = `${CONFIG.api}generator/report/territories`;
        await fetch(url, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                "Authorization": uuid
            }
        }).then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.blob();
        })
            .then(blob => {
                const link = document.createElement('a');
                const url = window.URL.createObjectURL(blob);
                link.href = url;
                link.download = 'report.xlsx';
                document.body.appendChild(link);
                link.click();
                link.remove();
                window.URL.revokeObjectURL(url);
            })
            .catch(err => {
                console.error('Fetch error:', err);
            });
    }
}