let allHardwareInputAutomations = [];
let isHardwareInputAutomationsCardView = false;
let inputAutomationsDebounceTimer = null;
let allUserVisitorSchedules = [];

$(document).ready(async function () {
    window.scrollTo({
        top: 0,
        behavior: "smooth",
    });
    const sessionPreferences = sessionStorage.getItem("preferences");
    if(sessionPreferences){
        const preferencesData = await parseJSONData(sessionPreferences);
        preferencesData?.is_card_view==1? isHardwareInputAutomationsCardView = true:isHardwareInputAutomationsCardView = false;
    }else {
        const preferences = await asyncGetPreferencesRequestForView({
        get_preferences_for_property_user: true,
        property_id: sessionStorage.getItem("propertyId"),
        });
        if(preferences?.length>0) sessionStorage.setItem("preferences",JSON.stringify(preferences[0])); 
        if(preferences?.length>0 && preferences[0]?.is_card_view==1) isHardwareInputAutomationsCardView = true;
    }

    document.getElementById("addAutomation_button")?.addEventListener("click", addAutomation);
    get_inputs_automation_request({get_inputs_automation_request: true, property_id: sessionStorage.getItem("propertyId")});
    get_inputs_automation_request({
        getScheduleRequest: true,
        type:'visitor',
        property_id:sessionStorage.getItem("propertyId")
    });
});

function get_inputs_automation_request(data){
    $.ajax({
        url: "/include/property_builder/hardwares/hardwares_request.php",
        type: "post",
        data,
        timeout: 10000,
        success: function (resp) {
            if(data?.delete_automation_request){
                showSuccessGlobalToastMessage("Automation deleted successfully");
                get_inputs_automation_request({get_inputs_automation_request: true, property_id: sessionStorage.getItem("propertyId")});
                return;
            }else if(data?.get_inputs_automation_request){
                allHardwareInputAutomations = resp?.data || [];
                if (window.innerWidth <= 600 || isHardwareInputAutomationsCardView){
                  createInputAutomationsCardsPreview(allHardwareInputAutomations);
                }else createInputAutomationsTablePreview(allHardwareInputAutomations);
            }else if(data?.getScheduleRequest){
                allUserVisitorSchedules = resp?.data || [];
            }else if(data?.update_automation_request){
                showSuccessGlobalToastMessage("Automation updated successfully");
                get_inputs_automation_request({get_inputs_automation_request: true, property_id: sessionStorage.getItem("propertyId")});
                $('#editAutomationModal').modal('hide');
                return;
            }
        },
        error: function (xhr, status, error) {
            if (xhr?.responseJSON?.error)
            showErrorGlobalToastMessage(xhr?.responseJSON?.error);
            else showErrorGlobalToastMessage(error);
        },
    });
}

function resetAutomationForm(){
    // document.getElementById("addAutomationForm").reset();
    document.getElementById("automation_fields").innerHTML = "";
    document.getElementById("hardware_device_id").value = "";
    document.getElementById("automationId").value = "";
}

function createInputAutomationsCardsPreview(hardware_automations){
    const automations_container = document.getElementById("automations_container");
    automations_container.innerHTML = ``;
    
    if (!hardware_automations || hardware_automations.length === 0) {
        automations_container.innerHTML = `
            <div class="no-automations">
                <i class="fas fa-info-circle"></i>
                <p>No automations configured yet. Create your first automation above!</p>
            </div>
        `;
        return;
    }
    
    const automations_grid = document.createElement("div");
    automations_grid.className = "automations-grid";
    
    hardware_automations.forEach(automation => {
        const automation_card = document.createElement("div");
        automation_card.className = "automation-text automation-card my-3";
        const doorName = automation.door_name || 'N/A';
        const createdDate = automation.created_at ? new Date(automation.created_at).toLocaleDateString('en-US', { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric' 
        }) : 'Unknown Date';
        
        automation_card.innerHTML = `
            <div class="automation-header">
                <div class="automation-title">
                    <i class="fas fa-bolt"></i>
                    <span class="door-name">${doorName}</span>
                </div>
                <div class="automation-actions">
                    <i class='fas fa-edit text-primary mx-1 cursor_pointer' title='Edit ' onclick="editAutomation(${automation.automation_id})"></i>
                    <i class='fas fa-trash-alt text-danger mx-1 cursor_pointer' title='Delete' onclick="deleteAutomation(${automation.automation_id})"></i>
                </div>
            </div>
            <div class="automation-content">
                <div class="automation-rule-display">
                    <div class="rule-text">${automation.automation_rules_text || 'N/A'}</div>
                </div>
            </div>
            <div class="automation-meta">
                <div class="automation-info">
                    <span class="automation-date">
                        <i class="fas fa-calendar-alt"></i>
                        Created: ${createdDate}
                    </span>
                    ${automation.input ? `
                        <span class="automation-input">
                            <i class="fas fa-microchip"></i>
                            Input: ${automation.input}
                        </span>
                    ` : ''}
                </div>
            </div>
        `;
        
        automations_grid.appendChild(automation_card);
    });
    
    automations_container.appendChild(automations_grid);
}

function createInputAutomationsTablePreview(hardware_automations){
    console.log("hardware_automations",hardware_automations);
    const automations_container = document.getElementById("automations_container");
    automations_container.innerHTML = ``;
    if (!hardware_automations || hardware_automations.length === 0) {
        automations_container.innerHTML = `
            <div class="no-automations">
                <i class="fas fa-info-circle"></i>
                <p>No automations configured yet. Create your first automation above!</p>
            </div>
        `;
        return;
    }
    
    let html = `
        <table id="automations_data_table" class="table table-bordered table-hover text-nowrap" style="width:100%; table-layout:auto;">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Door Name</th>
                    <th>Input</th>
                    <th>Trigger Source</th>
                    <th>Automation Rule</th>
                    <th>Created Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    hardware_automations.forEach(automation => {
        const doorName = automation.door_name || 'N/A';
        const createdDate = automation.created_at ? new Date(automation.created_at).toLocaleDateString('en-US', { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric' 
        }) : 'Unknown Date';
        
       
        
        html += `
            <tr>
                <td>${automation.id}</td>
                <td>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-bolt text-primary mr-2"></i>
                        <span class="font-weight-bold">${doorName}</span>
                    </div>
                </td>
                <td>
                    <span class="badge badge-info">${automation.input || 'N/A'}</span>
                </td>
                <td>
                    <span class="badge badge-${getTriggerBadgeClass(automation.triggered_by || 'N/A')}">${automation.triggered_by || 'N/A'}</span>
                </td>
                <td>
                    <div class="automation-rule-cell">
                        <span class="rule-text">${automation.automation_rules_text || 'N/A'}</span>
                    </div>
                </td>
                <td>
                    <small class="text-muted">
                        <i class="fas fa-calendar-alt mr-1"></i>
                        ${createdDate}
                    </small>
                </td>
                <td>
                    <i class='fas fa-edit text-primary mx-1 cursor_pointer' title='Edit ' onclick="editAutomation(${automation.automation_id})"></i>
                    <i class='fas fa-trash-alt text-danger mx-1 cursor_pointer' title='Delete' onclick="deleteAutomation(${automation.automation_id})"></i>
                </td>
            </tr>
        `;
    });
    
    html += `
            </tbody>
        </table>
    `;
    
    automations_container.innerHTML =html;
    
    // Initialize DataTable
    if ($.fn?.DataTable?.isDataTable("#automations_data_table")) {
        $("#automations_data_table").DataTable().destroy();
    }
    $("#automations_data_table")?.DataTable({
        responsive: true,
        order: [],
        paging: false,
        pageLength: -1,
        searching: false,
    });
}

function searchInputAutomations() {
    if(!isHardwareInputAutomationsCardView){
      searchTable('automations_data_table', 'searchInputAutomationInput');
      return;
    }
    clearTimeout(inputAutomationsDebounceTimer);
    inputAutomationsDebounceTimer = setTimeout(() => {
      const searchInput = document.getElementById("searchInputAutomationInput");
      if (!searchInput) {
        console.warn("Search input not found: searchInputAutomationInput");
        return;
      }
      
      const searchValue = searchInput.value.toLowerCase();
      
      // Filter streets data
      let matchedInputAutomations = allHardwareInputAutomations.filter(
        (inputAutomation) =>
          !searchValue ||
          Object.values(inputAutomation).some(
            (field) => field && field.toString().toLowerCase().includes(searchValue)    
          )
      );
      
      if (window.innerWidth <= 600 || isHardwareInputAutomationsCardView) {
        createInputAutomationsCardsPreview(matchedInputAutomations);
      } else {
        createInputAutomationsTablePreview(matchedInputAutomations);
      }
    }, 200);
}

// Helper function to get badge class for trigger source
function getTriggerBadgeClass(triggerSource) {
    switch(triggerSource) {
        case 'APP':
            return 'success';
        case 'WEBSITE':
            return 'primary';
        case 'BOTH':
            return 'warning';
        case 'NEITHER':
            return 'secondary';
        default:
            return 'light';
    }
}

async function get_hardware_device_details(hardware_device_id){
    return new Promise((resolve, reject) => {
        $.ajax({
        url: "/include/property_builder/hardwares/hardwares_request.php",
        type: "post",
        timeout: 10000,
        data:{get_hardware_device_details:true,device_id:hardware_device_id},
        success: function (resp) {
            const device_details = resp.data;
            console.log("device_details",device_details);
            
            addAutomationFields(device_details);
            resolve(resp.data);
        },
        error: function (xhr, status, error) {
            if (xhr?.responseJSON?.error)
            showErrorGlobalToastMessage(xhr?.responseJSON?.error);
            else showErrorGlobalToastMessage(error);
            reject(error);
        },
        });
    });
}

function addAutomationFields(device_details){
    const automation_fields = document.getElementById("automation_fields");
    if(device_details.inputs == "[]" || device_details.inputs == null){
        automation_fields.innerHTML = ``;
        showErrorGlobalToastMessage("No input sensors is assigned to this door");
        return;
    }

    const inputs = parseInputsString(device_details.inputs);
    automation_fields.innerHTML = ``;
    inputs.forEach(input => {
        let input_html = `
            <div class="automation-text" id="automation_text_${input}">
                <input type="hidden" name="input_name_hardware_automation" value="${input}">
                <input type="hidden" name="output_name_${input}" value="${device_details.output}">
                <input type="hidden" name="device_id_${input}" value="${device_details.id}">
                <input type="hidden" name="user_schedule_id_${input}" value="${device_details.timer_id==undefined?'':device_details.timer_id}">
                If ${input} is 
                <select name="input_status_${input}">
                    <option value="OFF">OFF</option>
                    <option value="ON">ON</option>
                </select> THEN allow ${device_details.output} to be triggered by <select name="trigger_source_${input}">
                    <option value="APP">APP</option>
                    <option value="WEBSITE">WEBSITE</option>
                    <option value="BOTH">BOTH</option>
                </select> during the user schedule  <select name="selected_user_schedule_${input}">
                    <option value="">Select a schedule</option>
                    ${allUserVisitorSchedules.map(schedule => `<option value="${schedule.id}">${schedule.title}</option>`).join('')}
                </select>
            </div>
        `;
        automation_fields.innerHTML += input_html;
    });
}

function parseInputsString(stringifyData) {
    try {
        const decodedData = stringifyData.replace(/&quot;/g, '"');
        return JSON.parse(decodedData);
    } catch (error) {
        return "";
    }
}

function addAutomation(){
    const automation_fields = document.getElementById("automation_fields");
    const formData = new FormData();
    const hardware_device_id = document.getElementById("hardware_device_id").value;
    
    if (!hardware_device_id) {
        showErrorGlobalToastMessage("Please select a hardware device");
        return;
    }
    
    formData.append("hardware_device_id", hardware_device_id);
    formData.append("add_automation_request", true);
    
    // Get all automation rules
    let automationRules = [];
    const automationTexts = automation_fields.querySelectorAll('.automation-text');
    
    automationTexts.forEach((automationText, index) => {
        const inputName = automationText.querySelector(`input[name="input_name_hardware_automation"]`).value;
        const inputStatus = automationText.querySelector(`select[name="input_status_${inputName}"]`).value;
        const triggerSource = automationText.querySelector(`select[name="trigger_source_${inputName}"]`).value;
        const outputName = automationText.querySelector(`input[name="output_name_${inputName}"]`).value;
        const deviceId = automationText.querySelector(`input[name="device_id_${inputName}"]`).value;
        // const userSchedule = automationText.querySelector(`input[name="user_schedule_${inputName}"]`).value;
        const userScheduleId = automationText.querySelector(`select[name="selected_user_schedule_${inputName}"]`).value;

        let userScheduleName=''
        if(userScheduleId){
            const userSchedule = allUserVisitorSchedules.find(schedule => schedule.id == userScheduleId);
            userScheduleName = userSchedule.title;
        }
        const automation_rules_text = `If ${inputName} is ${inputStatus} THEN allow ${outputName} to be triggered by ${triggerSource}${
            userScheduleId ? ` during schedule ${userScheduleName}` : ""
          }`;
        const payload = {
            input: inputName,
            input_status: inputStatus,
            device_id: Number(deviceId),
            output: outputName,
            triggered_by: triggerSource,
            user_schedule: userScheduleId?userScheduleId:'',
            property_id:sessionStorage.getItem("propertyId"),
            automation_rules_text: automation_rules_text,
        };
        automationRules.push(payload);
    });
    formData.append("automation_rules", JSON.stringify(automationRules));
    addAutomationRequest(formData);
}

async function addAutomationRequest(formData){
    return new Promise((resolve, reject) => {
        $.ajax({
        url: "/include/property_builder/hardwares/hardwares_request.php",
        type: "post",
        timeout: 10000,
        data: formData,
        processData: false,
        contentType: false,
        success: function (resp) {
            console.log("Automation added successfully:", resp);
            if (resp.success) {
                showSuccessGlobalToastMessage("Automation added successfully");
                // Close modal and reset form
                $('#addNewAutomation').modal('hide');
                resetAutomationForm();
                // Refresh the automations display
                get_inputs_automation_request({
                    get_inputs_automation_request: true, 
                    property_id: sessionStorage.getItem("propertyId")
                });
            } else {
                showErrorGlobalToastMessage(resp.error || "Failed to add automation");
            }
            resolve(resp);
        },
        error: function (xhr, status, error) {
            if (xhr?.responseJSON?.error)
            showErrorGlobalToastMessage(xhr?.responseJSON?.error);
            else showErrorGlobalToastMessage(error);
            reject(error);
        },
        });
    });
}

// Delete automation function
function deleteAutomation(automationId) {
    showConfirmModal("Are you sure you want to delete this automation?", function () {
        get_inputs_automation_request({
            property_id: sessionStorage.getItem("propertyId"),
            delete_automation_request: true,
            automation_id: automationId
        });
    });
}

// Delete automation function
function editAutomation(automationId) {
    console.log("Going to edit automation",allHardwareInputAutomations);
    const automation = allHardwareInputAutomations.find(automation => automation.automation_id == automationId);
    console.log("Automation inpuy",automation?.input);
    if(!automation){
        showErrorGlobalToastMessage("Automation not found");
        return;
    }

    document.getElementById("automation_input").value = automation?.input;
    document.getElementById("automationId").value = automationId;
    document.getElementById("automation_output").value = automation?.output;
    const input=automation?.input;
    const automation_fields = document.getElementById("edit_automation_fields");
    automation_fields.innerHTML = ``;
    let input_html = `
        <div class="automation-text" id="automation_text_${input}">
            If ${automation?.input} is 
            <select id="edit_input_status_${input}" name="edit_input_status_${input}">
                <option value="OFF" ${automation?.input_status == 'OFF' ? 'selected' : ''}>OFF</option>
                <option value="ON" ${automation?.input_status == 'ON' ? 'selected' : ''}>ON</option>
            </select> THEN allow ${automation?.output} to be triggered by <select id="edit_trigger_source_${input}" name="edit_trigger_source_${input}">
                <option value="APP" ${automation?.triggered_by == 'APP' ? 'selected' : ''}>APP</option>
                <option value="WEBSITE" ${automation?.triggered_by == 'WEBSITE' ? 'selected' : ''}>WEBSITE</option>
                <option value="BOTH" ${automation?.triggered_by == 'BOTH' ? 'selected' : ''}>BOTH</option>
            </select> during the user schedule  <select id="edit_user_schedule_${input}" name="edit_user_schedule_${input}">
                <option value="">Select a schedule</option>
                ${allUserVisitorSchedules.map(schedule => `<option ${automation?.user_schedule == schedule.id ? 'selected' : ''} value="${schedule.id}">${schedule.title}</option>`).join('')}
            </select>
        </div>
    `;
    automation_fields.innerHTML += input_html;
    $('#editAutomationModal').modal('show');
}

function updateAutomation(){
    const automation_fields = document.getElementById("edit_automation_fields");
    const input=document.getElementById("automation_input")?.value;
    const output=document.getElementById(`automation_output`)?.value;

    let payload = {
        id:document.getElementById("automationId")?.value,
        automation_input:document.getElementById("automation_input")?.value,
        input_status:document.getElementById(`edit_input_status_${input}`)?.value,
        triggered_by:document.getElementById(`edit_trigger_source_${input}`)?.value,
        user_schedule:document.getElementById(`edit_user_schedule_${input}`)?.value,
        update_automation_request:true
    }
    let userScheduleName=''
    if(payload.user_schedule){
        const userSchedule = allUserVisitorSchedules.find(schedule => schedule.id == payload.user_schedule);
        userScheduleName = userSchedule.title;
    }
    payload.automation_rules_text = `If ${input} is ${payload.input_status} THEN allow ${output} to be triggered by ${payload.triggered_by}${
        payload.user_schedule ? ` during schedule ${userScheduleName}` : ""
    }`;

    get_inputs_automation_request(payload);
}

