import { getEvent, getMyAccount, unhideElementById, getMyRegisteredEventIds } from './generalUseHelpers.js';

var redirected = false;

document.addEventListener("DOMContentLoaded", async () => {

    var container = document.getElementById("mainContainer");
    const modifyBtn = document.getElementById("editBtn");
    const removeBtn = document.getElementById("removeBtn");
    const applyBtn = document.getElementById("applyBtn");
    const leaveBtn = document.getElementById("leaveBtn");
    var org_id: number = -1;
    var org_name: string = "";

    try {
        var user = await getMyAccount();
        if (user && user.isOrganisation) {
            const org_id = user.organisationId;
            fetch('/api/organizations/' + org_id)
                .then(response => response.json())
                .then(data => {
                    org_name = data.name;
                    unhideElementById(document, "orgname");
                })
                .catch(error => {
                    console.error('Failed to fetch organization:', error);
                });
        } else {
            unhideElementById(document, "orgno");
        }
    } catch (e) {
        window.location.href = "login.html";
    }

    var thisAccount = null;
    thisAccount = await getMyAccount();
    if (thisAccount.isOrganisation) org_id = thisAccount.organisationId;

    if (thisAccount == null) {
        if (container !== null) container.innerHTML = `<p class="text-danger">Błąd we wczytywaniu wydarzenia. <a href="/" style="color:#2898BD;">Powrót -></a></p>`;
    } else {

        const nameText = document.getElementById("nameText") as HTMLElement;
        const orgnameText = document.getElementById("orgname") as HTMLElement;
        const dateText = document.getElementById("dateText") as HTMLElement;
        const newdateText = new Date(thisAccount.createdAt).toLocaleDateString('pl-PL');
        const newtimeText = new Date(thisAccount.createdAt).toLocaleTimeString('pl-PL');


        nameText.innerHTML = thisAccount.firstName + " " + thisAccount.lastName + " (" + thisAccount.email + ")";
        dateText.innerHTML = "📅 Account creation date: " + newdateText + " " + newtimeText;
        orgnameText.innerHTML = "👥 Organization: " + org_name;

        if (org_id == -1) {
            unhideElementById(document, "skillscont");
        } else if (org_id == -1) {
            // Użytkownik jest wolontariuszem
            try {
                const registeredIds = await getMyRegisteredEventIds();
            } catch (e) {

            }

        }

        unhideElementById(document, "mainContainer");

    }

});

window.onload = () => {
    const selectedSkillsContainer = document.getElementById('selected-skills') as HTMLDivElement;
    const dropdown = document.getElementById('skill-dropdown') as HTMLSelectElement;

    dropdown.addEventListener('change', () => {
        const skillName = dropdown.options[dropdown.selectedIndex].text;
        const skillId = dropdown.options[dropdown.selectedIndex].value;
        if (skillName) {
            addSkill(skillName, Number(skillId), false);
            dropdown.value = ''; // Reset dropdown
        }
    });

    function fetchSkills() {
        fetch('/api/skills')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                populateDropdown(data);
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });
    }

    function fetchUserSkills() {
        fetch('/api/auth/skills')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                populateSkills(data);
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });
    }

    // Populate dropdown with fetched skills
    function populateDropdown(skills: { skillId: number; skillName: string; }[]) {
        skills.forEach(skill => {
            const option = document.createElement('option');
            option.value = skill.skillId.toString();
            option.textContent = skill.skillName;
            dropdown.appendChild(option);
        });
    }

    function populateSkills(skills: { skillId: number; skillName: string; }[]) {
        skills.forEach(skill => {
            addSkill(skill.skillName, skill.skillId, true);
        });
    }

    // Call fetchSkills to populate dropdown on load, same for fetchUserSkills()
    fetchSkills();
    fetchUserSkills();

    function getRandomColor(): string {

        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);

        return `rgb(${r}, ${g}, ${b})`;
    }

    async function addSkill(skillName: string, skillId: number, dummy_add: boolean) {
        if (!document.querySelector(`#selected-skills .skill[data-skill="${skillName}"]`)) {
            const skillDiv = document.createElement('div');
            skillDiv.className = 'skill';
            skillDiv.textContent = skillName;
            skillDiv.setAttribute('data-skill', skillName);
            skillDiv.style.backgroundColor = getRandomColor();

            if (!dummy_add) {
                var skill = skillId;
                var payload = {
                    skill
                };

                var res = await fetch('/api/auth/add_skill', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                var data = await res.json();
                if (res.ok) skillDiv.remove();
                else alert(data.message);
            }

            const removeButton = document.createElement('button');
            removeButton.textContent = 'X';
            removeButton.addEventListener('click', async () => {
                var skill = skillId;
                var payload = {
                    skill
                };

                var res = await fetch('/api/auth/remove_skill', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                var data = await res.json();
                if (res.ok) skillDiv.remove();
                else alert(data.message);
            });

            skillDiv.appendChild(removeButton);
            selectedSkillsContainer.appendChild(skillDiv);
        }
    }
};
