/**
 * Degvielas statistikas lapas modulis
 * 
 * Apstrādā degvielas patēriņa izsekošanu un pārvaldību darbiniekiem un darba devējiem.
 * Atļauj lietotājiem reģistrēt degvielas patēriņu aprīkojumam un apskatīt vēsturiskos ierakstus.
 * 
 * Funkcijas:
 * - Apskatīt visus degvielas ierakstus tabulā (filtrēti pēc lauksaimniecības)
 * - Pievienot jaunus degvielas patēriņa ierakstus ar datumu/laiku, aprīkojumu un litriem
 * - Dzēst savus degvielas ierakstus (darbinieki var dzēst tikai savus)
 * - Aprīkojuma nosaukuma un lietotāja vārda atrisināšana no datu bāzes
 * - Bākas tilpuma validācija (novērš pārpildīšanu)
 * - Masveida dzēšana ar izvēles rūtiņu atlasi
 * - Automātiska atsvaidzināšana ik pēc 30 sekundēm
 */

// Saglabā tehnikas datus priekš pārbaudes
let equipmentData = [];

/**
 * Ielādē degvielas ierakstus no serevra
 * Izvada tos tabulā ar lietotāja vārdu
 * Filtrē pēc farm_id
 */
async function loadFuelData() {
  try {
    const userData = localStorage.getItem("user");
    let farmId = null;
    let currentUserId = null;
    
    if (userData) {
      const user = JSON.parse(userData);
      farmId = user.farm_id;
      currentUserId = user.id;
    }
    
    let apiUrl = "http://localhost:3001/api/fuel";
    if (farmId) {
      apiUrl += `?farm_id=${farmId}`;
    }
    
    const response = await fetch(apiUrl);
    
    if (!response.ok) {
      throw new Error('Failed to fetch fuel data');
    }
    
    const fuelRecords = await response.json();
    
    const tbody = document.querySelector('.degv_tabula tbody');
    
    if (!tbody) {
      console.error('Table body not found');
      return;
    }
    
    tbody.innerHTML = '';
    
    // Parāda paziņojumu, ja nav ierakstu
    if (fuelRecords.length === 0) {
      tbody.innerHTML = `
        <tr>
          <td colspan="5" class="text-center text-muted py-4">
            No fuel records found in database
          </td>
        </tr>
      `;
      return;
    }
    
    // Izveido tabulu rindas priekš katra ieraksta
    fuelRecords.forEach(record => {
      const row = document.createElement('tr');
      
      // Pareizu noformējumu datumam
      const date = new Date(record.time);
      const formattedDate = date.toLocaleDateString('en-GB', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
      });
      const formattedTime = date.toLocaleTimeString('en-GB', {
        hour: '2-digit',
        minute: '2-digit'
      });
      
      // Parāda "checkbox" tikai konkrētā lietotāja ierakstiem
      const isOwnRecord = currentUserId && record.user_id === currentUserId;
      
      const checkboxCell = isOwnRecord 
        ? `<td class="tabulas_ieraksts"><input type="checkbox" class="record-checkbox" data-record-id="${record.id}" data-user-id="${record.user_id}"></td>`
        : `<td class="tabulas_ieraksts"></td>`;
      
      row.innerHTML = `
        ${checkboxCell}
        <td class="tabulas_ieraksts">${formattedDate} ${formattedTime}</td>
        <td class="tabulas_ieraksts" data-equipment-id="${record.equipment_id}">Loading...</td>
        <td class="tabulas_ieraksts">${record.litres}</td>
        <td class="tabulas_ieraksts" data-user-id="${record.user_id}">Loading...</td>
      `;
      
      tbody.appendChild(row);
    });
    
    // Ielādē tehniku un lietotāju vārdus, lai aizvietotu identifikatorus
    await loadEquipmentNames();
    await loadUserNames();
    
  } catch (error) {
    console.error('Error loading fuel data:', error);
    const tbody = document.querySelector('.degv_tabula tbody');
    if (tbody) {
      tbody.innerHTML = `
        <tr>
          <td colspan="5" class="text-center text-danger py-4">
            ❌ Failed to load fuel data. Make sure the server is running.
          </td>
        </tr>
      `;
    }
  }
}

/**
 * Ielādē tehnikas nosaukumus no servera un aizstāj tehnikas ID tabulā
 * Ja servera pieprasījums neizdodas, tiek izmantots noklusējuma tehnikas saraksts
 */
async function loadEquipmentNames() {
  try {
    const userData = localStorage.getItem("user");
    let farmId = null;
    
    if (userData) {
      const user = JSON.parse(userData);
      farmId = user.farm_id;
    }
    
    // Izveido API URL ar saimniecības filtru
    let apiUrl = "http://localhost:3001/api/equipment";
    if (farmId) {
      apiUrl += `?farm_id=${farmId}`;
    }
    
    const response = await fetch(apiUrl);
    
    if (!response.ok) {
      throw new Error('Failed to fetch equipment');
    }
    
    const equipment = await response.json();
    
    // Izveido karti no tehnikas ID uz nosaukumu
    const equipmentMap = {};
    equipment.forEach(eq => {
      equipmentMap[eq.id] = eq.name;
    });
    
    // Aizstāj tehnikas ID ar nosaukumiem tabulā
    document.querySelectorAll('[data-equipment-id]').forEach(cell => {
      const equipmentId = cell.getAttribute('data-equipment-id');
      cell.textContent = equipmentMap[equipmentId] || `Equipment #${equipmentId}`;
    });
  } catch (error) {
    console.error('Error loading equipment names:', error);
    // Atgriešanās uz noklusējuma tehnikas nosaukumiem
    const equipmentMap = {
      1: 'John Deere 6120M',
      2: 'Case IH Magnum 340',
      3: 'New Holland T7.315',
      4: 'Massey Ferguson 8S.265',
      5: 'Fendt 724 Vario'
    };
    
    document.querySelectorAll('[data-equipment-id]').forEach(cell => {
      const equipmentId = cell.getAttribute('data-equipment-id');
      cell.textContent = equipmentMap[equipmentId] || `Equipment #${equipmentId}`;
    });
  }
}

/**
 * Ielādē lietotāju vārdus no servera un aizstāj lietotāju ID tabulā
 * Ja lietotājs nav atrasts, parāda "User #ID"
 */
async function loadUserNames() {
  try {
    const response = await fetch("http://localhost:3001/api/employees");
    
    if (!response.ok) {
      throw new Error('Failed to fetch users');
    }
    
    const users = await response.json();
    
    // Izveido karti no lietotāja ID uz pilno vārdu
    const userMap = {};
    users.forEach(user => {
      userMap[user.id] = `${user.name} ${user.fname}`;
    });
    
    // Aizstāj lietotāju ID ar vārdiem tabulā
    document.querySelectorAll('[data-user-id]').forEach(cell => {
      const userId = cell.getAttribute('data-user-id');
      cell.textContent = userMap[userId] || `User #${userId}`;
    });
  } catch (error) {
    console.error('Error loading user names:', error);
    // Rezerves variants – parāda lietotāju ID
    document.querySelectorAll('[data-user-id]').forEach(cell => {
      const userId = cell.getAttribute('data-user-id');
      cell.textContent = `User #${userId}`;
    });
  }
}

/**
 * Pārbauda, vai lietotājs ir autentificēts
 * Ja lietotājs nav pieteicies, novirza uz index lapu
 */
function checkAuth() {
  const isLoggedIn = localStorage.getItem("isLoggedIn");
  const userData = localStorage.getItem("user");
  
  if (isLoggedIn !== "true" || !userData) {
    window.location.href = "index.html";
    return false;
  }
  
  return true;
}

/**
 * Ielādē tehnikas nolaižamo sarakstu degvielas formai
 * Aizpilda select elementu ar tehnikas nosaukumiem un degvielas tvertnes ietilpību
 */
async function loadEquipmentDropdown() {
  try {
    const userData = localStorage.getItem("user");
    if (!userData) return;
    
    const user = JSON.parse(userData);
    const farmId = user.farm_id;
    
    const response = await fetch(`http://localhost:3001/api/equipment?farm_id=${farmId}`);
    
    if (!response.ok) {
      throw new Error('Failed to fetch equipment');
    }
    
    const equipment = await response.json();
    
    // Saglabā tehnikas datus validācijai
    equipmentData = equipment;
    
    const dropdown = document.getElementById('fuelEquipment');
    dropdown.innerHTML = '<option value="">Select equipment...</option>';
    
    // Aizpilda nolaižamo sarakstu ar tehniku un tvertnes ietilpības informāciju
    equipment.forEach(eq => {
      const option = document.createElement('option');
      option.value = eq.id;
      option.textContent = `${eq.name} (${eq.fuel_tank}L tank)`;
      option.setAttribute('data-tank-capacity', eq.fuel_tank);
      dropdown.appendChild(option);
    });
    
  } catch (error) {
    console.error('Error loading equipment:', error);
    const dropdown = document.getElementById('fuelEquipment');
    dropdown.innerHTML = '<option value="">Error loading equipment</option>';
  }
}

/**
 * Iesniedz jaunu degvielas uzskaites ierakstu
 * Pārbauda tvertnes ietilpību un nosūta POST pieprasījumu serverim
 */
async function submitFuelRecord() {
  try {
    const dateTime = document.getElementById('fuelDateTime').value;
    const equipmentId = document.getElementById('fuelEquipment').value;
    const litres = parseFloat(document.getElementById('fuelLitres').value);
    
    if (!dateTime || !equipmentId || !litres) {
      alert('Please fill in all fields');
      return;
    }
    
    // Pārbauda, vai degvielas daudzums nepārsniedz tvertnes ietilpību
    const selectedEquipment = equipmentData.find(eq => eq.id === parseInt(equipmentId));
    if (selectedEquipment) {
      if (litres > selectedEquipment.fuel_tank) {
        alert(`❌ Error: Amount (${litres}L) exceeds tank capacity!\n\n${selectedEquipment.name} has a maximum capacity of ${selectedEquipment.fuel_tank}L.\n\nPlease enter a value less than or equal to ${selectedEquipment.fuel_tank}L.`);
        return;
      }
    }
    
    const userData = localStorage.getItem("user");
    if (!userData) {
      alert('User not logged in');
      return;
    }
    
    const user = JSON.parse(userData);
    
    // Sagatavo degvielas ieraksta datus
    const fuelData = {
      time: dateTime,
      equipment_id: parseInt(equipmentId),
      litres: parseFloat(litres),
      user_id: user.id
      // farm_id serverī tiek noteikts automātiski no lietotāja datiem
    };
    
    const response = await fetch('http://localhost:3001/api/fuel', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(fuelData)
    });
    
    const result = await response.json();
    
    if (result.success) {
      // Aizver modālo logu un atiestata formu
      const modal = bootstrap.Modal.getInstance(document.getElementById('addFuelModal'));
      modal.hide();
      
      document.getElementById('addFuelForm').reset();
      
      // Pārlādē degvielas datus, lai parādītu jauno ierakstu
      await loadFuelData();
      
      alert('✅ Fuel record added successfully!');
    } else {
      alert('❌ Failed to add fuel record: ' + (result.error || 'Unknown error'));
    }
    
  } catch (error) {
    console.error('Error submitting fuel record:', error);
    alert('❌ Failed to add fuel record. Please try again.');
  }
}

/**
 * Dzēš atlasītos degvielas uzskaites ierakstus
 * Atļauj dzēst tikai lietotāja paša ierakstus
 * Pirms dzēšanas pieprasa apstiprinājumu
 */
async function deleteSelectedRecords() {
  try {
    const checkboxes = document.querySelectorAll('.record-checkbox:checked');
    
    if (checkboxes.length === 0) {
      alert('Please select at least one record to delete');
      return;
    }
    
    const confirmDelete = confirm(`Are you sure you want to delete ${checkboxes.length} record(s)?\n\nThis action cannot be undone.`);
    
    if (!confirmDelete) {
      return;
    }
    
    const userData = localStorage.getItem("user");
    if (!userData) {
      alert('User not logged in');
      return;
    }
    
    const user = JSON.parse(userData);
    let successCount = 0;
    let errorCount = 0;
    
    // Dzēš katru atlasīto ierakstu
    for (const checkbox of checkboxes) {
      const recordId = checkbox.getAttribute('data-record-id');
      const recordUserId = parseInt(checkbox.getAttribute('data-user-id'));
      
      // Pārbauda, vai ieraksts pieder lietotājam
      if (recordUserId !== user.id) {
        console.error(`Attempted to delete record ${recordId} that doesn't belong to user`);
        errorCount++;
        continue;
      }
      
      try {
        const response = await fetch(`http://localhost:3001/api/fuel/${recordId}?user_id=${user.id}`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        
        if (result.success) {
          successCount++;
        } else {
          errorCount++;
          console.error(`Failed to delete record ${recordId}:`, result.error);
        }
      } catch (error) {
        errorCount++;
        console.error(`Error deleting record ${recordId}:`, error);
      }
    }
    
    if (successCount > 0) {
      // Pārlādē degvielas datus, lai atspoguļotu dzēšanu
      await loadFuelData();
      
      if (errorCount > 0) {
        alert(`✅ Deleted ${successCount} record(s)\n❌ Failed to delete ${errorCount} record(s)`);
      } else {
        alert(`✅ Successfully deleted ${successCount} record(s)`);
      }
    } else {
      alert('❌ Failed to delete records. Please try again.');
    }
    
  } catch (error) {
    console.error('Error deleting records:', error);
    alert('❌ Failed to delete records. Please try again.');
  }
}

// Eksportē funkcijas HTML onclick apstrādātājiem
window.submitFuelRecord = submitFuelRecord;
window.deleteSelectedRecords = deleteSelectedRecords;

/**
 * Inicializē lapu, kad DOM ir gatavs
 * Iestata notikumu klausītājus un ielādē sākotnējos datus
 */
document.addEventListener('DOMContentLoaded', () => {
  if (!checkAuth()) {
    return;
  }
  
  // Ielādē sākotnējos degvielas datus
  loadFuelData();
  
  // Automātiski pārlādē degvielas datus ik pēc 30 sekundēm
  setInterval(loadFuelData, 30000);
  
  // Iestata modālā loga notikumu klausītāju
  const addFuelModal = document.getElementById('addFuelModal');
  if (addFuelModal) {
    addFuelModal.addEventListener('show.bs.modal', () => {
      // Iestata pašreizējo datumu/laiku kā noklusējuma vērtību
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const dateTimeString = `${year}-${month}-${day}T${hours}:${minutes}`;
      
      document.getElementById('fuelDateTime').value = dateTimeString;
      
      // Ielādē tehnikas nolaižamo sarakstu
      loadEquipmentDropdown();
    });
  }
  
  // Iestata “atzīmēt visu” izvēles rūtiņu
  const selectAllCheckbox = document.getElementById('selectAll');
  if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', (e) => {
      const checkboxes = document.querySelectorAll('.record-checkbox');
      checkboxes.forEach(checkbox => {
        checkbox.checked = e.target.checked;
      });
    });
  }
  
  // Iestata degvielas daudzuma validāciju
  const fuelLitresInput = document.getElementById('fuelLitres');
  const fuelEquipmentSelect = document.getElementById('fuelEquipment');
  const tankCapacityHint = document.getElementById('tankCapacityHint');
  
  if (fuelLitresInput && fuelEquipmentSelect) {
    const validateFuelAmount = () => {
      const equipmentId = fuelEquipmentSelect.value;
      const litres = parseFloat(fuelLitresInput.value);
      
      // Parāda tvertnes ietilpības norādi
      if (equipmentId && equipmentData.length > 0) {
        const selectedEquipment = equipmentData.find(eq => eq.id === parseInt(equipmentId));
        if (selectedEquipment && tankCapacityHint) {
          tankCapacityHint.textContent = `Maximum capacity: ${selectedEquipment.fuel_tank}L`;
          tankCapacityHint.style.display = 'block';
        }
      } else if (tankCapacityHint) {
        tankCapacityHint.style.display = 'none';
      }
      
      // Pārbauda, vai degvielas daudzums nepārsniedz tvertnes ietilpību
      if (equipmentId && litres && equipmentData.length > 0) {
        const selectedEquipment = equipmentData.find(eq => eq.id === parseInt(equipmentId));
        
        if (selectedEquipment && litres > selectedEquipment.fuel_tank) {
          fuelLitresInput.setCustomValidity(`Amount exceeds tank capacity of ${selectedEquipment.fuel_tank}L`);
          fuelLitresInput.classList.add('is-invalid');
        } else {
          fuelLitresInput.setCustomValidity('');
          fuelLitresInput.classList.remove('is-invalid');
        }
      }
    };
    
    fuelLitresInput.addEventListener('input', validateFuelAmount);
    fuelEquipmentSelect.addEventListener('change', validateFuelAmount);
  }
});