const select = document.getElementById("lawyersSelect");
const specializationId = document.getElementById("specializationLabel").dataset.id;
const specializationInput = document.getElementById("specializationInput");
const lawyerTable = document.getElementById("lawyerTable");
const updateBtn = document.getElementById("update-button");

var lawyers = [];
var specialization = null;

window.addEventListener("load", async () => {
    try {
        const lawyersResponse = await $.ajax({
            url: `/lawyers/getallbyuserandspecialization?specialization=${specializationId}`,
            type: "GET",
            contentType: "json"
        });
        lawyers = lawyersResponse;

        console.log(lawyers);
        lawyers.forEach((lawyer) => {
            createLawyerOption(lawyer);
        });

        const specializationResponse = await $.ajax({
            url: `/specializations/get?id=${specializationId}`,
            type: 'GET',
            contentType: 'json'
        });
        specialization = specializationResponse;
        fillSpecializationInput(specialization);
    } catch (error) {
        console.error(error);
    }
});


updateBtn.addEventListener("click", () => {
    if (select.selectedIndex === -1) {
        return;
    }

    var lawyer = lawyers.find(x => x.id === parseInt(select.value));
    lawyer.specializationId = specialization.id;

    $.ajax({
        url: "/lawyers/update",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(lawyer)
    }).done(() => {
        window.location.href = "/Home/Specializations";
    });
})

const createLawyerOption = (lawyer) => {
    const option = document.createElement("option");
    option.value = lawyer.id;
    option.innerHTML = lawyer.name + " " + lawyer.surname + " " + lawyer.patronymic + ", " + lawyer.experience;
    select.appendChild(option);
    select.selectedIndex = -1;
}

const fillSpecializationInput = (specialization) => {
    specializationInput.value = specialization.name
}

select.addEventListener("change", () => {
    lawyerTable.innerHTML = "";

    const createRow = (label, value) => {
        const tr = document.createElement('tr');
        const tdLabel = document.createElement('td');
        tdLabel.innerHTML = label;
        const tdValue = document.createElement('td');
        tdValue.innerHTML = value;

        tr.appendChild(tdLabel);
        tr.appendChild(document.createElement('td'));
        tr.appendChild(document.createElement('td'));
        tr.appendChild(tdValue);

        return tr;
    };

    const lawyer = lawyers.find(x => x.id === parseInt(select.value));

    const trName = createRow("Имя:", lawyer.name);
    const trSurname = createRow("Фамилия:", lawyer.surname);
    const trPatronymic = createRow("Отчество:", lawyer.patronymic);
    const trExperience = createRow("Опыт работы:", lawyer.experience);

    const trSpecializationName = document.createElement('tr');
    const tdSpecializationNameField = document.createElement('td');
    tdSpecializationNameField.innerHTML = "Специализация:";
    const tdNewSpecializationName = document.createElement('td');
    tdNewSpecializationName.innerHTML = specialization.name;
    const tdArrowSpecializationName = document.createElement('td');
    tdArrowSpecializationName.innerHTML = "-->";
    const tdSpecializationName = createRow("", lawyer.specializationName);

    trSpecializationName.appendChild(tdSpecializationNameField);
    trSpecializationName.appendChild(tdNewSpecializationName);
    trSpecializationName.appendChild(tdArrowSpecializationName);
    trSpecializationName.appendChild(tdSpecializationName);

    lawyerTable.append(
        trName,
        trSurname,
        trPatronymic,
        trExperience,
        trSpecializationName
    );
});

const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
};