/**
 * Lauksaimniecību reģidēšanas modulis
 * 
 * Apstrādā lauksaimniecību pārvaldību administratoriem
 * Atļauj administratoriem:
 *  - Apskatīt visas lauksaimniecības
 *  - Pievienot lauksaimniecības
 *  - Iespejot/atspejot lauksaimniecības
 *  - Izdzēst lauksaimniecīabs
 * Veidoja: Edijs Dunavskis
 */

const EditFarm = (() => {
  let currentUser = null;

  /**
   * inicializē lauksaimniecību pārvaldības lapu
   * Ielādē lauksaimniecības
   */
  const init = async () => {
    await HeaderManager.loadHeader('header-container');
    
    // Pārbauda vai lietotājs ir pieslēdzies
    currentUser = JSON.parse(localStorage.getItem('user'));
    if (!currentUser) {
      window.location.href = 'login_lapa.html';
      return;
    }

    // Pārbauda vai lietotās ir administrators
    if (currentUser.status !== 3) {
      showError('You do not have permission to manage farms.');
      setTimeout(() => window.location.href = 'index.html', 2000);
      return;
    }
    
    // Ielādē visas lauksaimniecības
    await loadAllFarms();
    
    // Izveido formu pieteikšanu
    document.getElementById('addFarmForm').addEventListener('submit', handleFormSubmit);
  };


  // Nosūta visas lauksaimniecības no servera
  const loadAllFarms = async () => {
    try {
      const response = await fetch('http://localhost:3001/api/farms');
      if (!response.ok) throw new Error('Failed to load farms');
      
      const farms = await response.json();
      displayFarmsTable(farms);
      
    } catch (error) {
      console.error('Error loading farms:', error);
      showError('Failed to load farms.');
    }
  };

  /**
   * Izvada lauksaimniecības tabulas formātā
   * Parāda lauksaimniecības identifikatoru, nosaukumus, aktivitātes statusu un pogas
   */
  const displayFarmsTable = (farms) => {
    const tbody = document.getElementById('farmsTableBody');
    
    if (farms.length === 0) {
      tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">No farms found</td></tr>';
      return;
    }

    tbody.innerHTML = farms.map(farm => {
      const isActive = farm.active === 1;
      return `
      <tr>
        <td>${farm.id}</td>
        <td>${farm.name}</td>
        <td>
          <span class="badge ${isActive ? 'bg-success' : 'bg-danger'}">
            ${isActive ? 'Active' : 'Inactive'}
          </span>
        </td>
        <td>
          <button class="btn btn-sm ${isActive ? 'btn-warning' : 'btn-info'}" onclick="EditFarm.toggleFarmStatus(${farm.id}, ${isActive})">
            ${isActive ? 'Disable' : 'Enable'}
          </button>
          <button class="btn btn-sm btn-danger" onclick="EditFarm.deleteFarm(${farm.id})">
            Delete
          </button>
        </td>
      </tr>
    `;
    }).join('');
  };

  /**
   * Apstrādā jaunas lauksaimniecības pievienošanu
   * Pārbuda ievadi un nosūta POST pieprasījumu uz serveri
   */
  const handleFormSubmit = async (e) => {
    e.preventDefault();
    
    const farmName = document.getElementById('farmName').value.trim();

    if (!farmName) {
      showError('Farm name is required.');
      return;
    }

    try {
      const response = await fetch('http://localhost:3001/api/farms', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: farmName })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to add farm');
      }

      await response.json();
      showSuccess('Farm added successfully!');
      document.getElementById('farmName').value = '';
      
      // Pārlādē lauksaimniecības tabulu
      await loadAllFarms();

    } catch (error) {
      console.error('Error adding farm:', error);
      showError(error.message || 'Failed to add farm.');
    }
  };

  /**
   * Pārmaina lauksaimniecības aktivitātes statusu
   */
  const toggleFarmStatus = async (farmId, currentStatus) => {
    try {
      const newStatus = currentStatus ? 0 : 1;
      console.log(`Toggling farm ${farmId} from ${currentStatus} to ${newStatus}`);
      
      const response = await fetch(`http://localhost:3001/api/farms/${farmId}/toggle`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ active: newStatus })
      });

      console.log(`Response status: ${response.status}`);
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to toggle farm status');
      }

      const result = await response.json();
      console.log('Toggle result:', result);
      
      showSuccess(`Farm ${newStatus === 1 ? 'enabled' : 'disabled'} successfully!`);
      
      setTimeout(() => {
        loadAllFarms();
      }, 500);

    } catch (error) {
      console.error('Error toggling farm status:', error);
      showError(error.message || 'Failed to toggle farm status.');
    }
  };

  /**
   * Izdzēš lauksaimniecību
   */
  const deleteFarm = async (farmId) => {
    if (!confirm('Are you sure you want to delete this farm?')) {
      return;
    }

    try {
      const response = await fetch(`http://localhost:3001/api/farms/${farmId}`, {
        method: 'DELETE'
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to delete farm');
      }

      await response.json();
      showSuccess('Farm deleted successfully!');
      await loadAllFarms();

    } catch (error) {
      console.error('Error deleting farm:', error);
      showError(error.message || 'Failed to delete farm.');
    }
  };

  /**
   * Izvada veiksmes paziņojumu
   * Automātiski pazūd pēc 3 sekundēm
   */
  const showSuccess = (message) => {
    const successDiv = document.getElementById('successMessage');
    successDiv.textContent = '✅ ' + message;
    successDiv.style.display = 'block';
    document.getElementById('errorMessage').style.display = 'none';
    setTimeout(() => {
      successDiv.style.display = 'none';
    }, 3000);
  };

  /**
   * Izmet kļūdas paziņojumu
   */
  const showError = (message) => {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = '❌ ' + message;
    errorDiv.style.display = 'block';
    document.getElementById('successMessage').style.display = 'none';
  };

  // Publiskais API
  return {
    init,
    deleteFarm,
    toggleFarmStatus
  };
})();

// Inicializē, kad "DOM" ir gatavs
document.addEventListener('DOMContentLoaded', EditFarm.init);
