// API base URL
const API_BASE = '/api';

// Global state
let allShipments = [];
let riskChart = null;
let trendChart = null;

// Initialize dashboard
document.addEventListener('DOMContentLoaded', () => {
  loadRegions();
  loadDashboardStats();
  loadShipments();

  // Event listeners
  document.getElementById('region-filter').addEventListener('change', loadShipments);
  document.getElementById('risk-filter').addEventListener('change', loadShipments);
  document.getElementById('refresh-btn').addEventListener('click', refreshAll);
});

// Load regions for filter dropdown
async function loadRegions() {
  try {
    const response = await fetch(`${API_BASE}/regions`);
    const result = await response.json();

    const select = document.getElementById('region-filter');
    result.data.forEach(region => {
      const option = document.createElement('option');
      option.value = region;
      option.textContent = region;
      select.appendChild(option);
    });
  } catch (error) {
    console.error('Error loading regions:', error);
  }
}

// Load dashboard statistics
async function loadDashboardStats() {
  try {
    const response = await fetch(`${API_BASE}/dashboard/stats`);
    const result = await response.json();
    const stats = result.data;

    document.getElementById('total-in-transit').textContent = stats.totalInTransit;
    document.getElementById('on-time-rate').textContent = stats.historicalPerformance.onTimeRate + '%';

    // Update trend chart
    updateTrendChart(stats.recentTrend);
  } catch (error) {
    console.error('Error loading stats:', error);
  }
}

// Load at-risk shipments
async function loadShipments() {
  const region = document.getElementById('region-filter').value;
  const minRisk = document.getElementById('risk-filter').value;

  const tbody = document.querySelector('#shipments-table tbody');
  tbody.innerHTML = '<tr><td colspan="7" class="loading">Loading shipments...</td></tr>';

  try {
    let url = `${API_BASE}/shipments/at-risk?minRisk=${minRisk}`;
    if (region) url += `&region=${encodeURIComponent(region)}`;

    const response = await fetch(url);
    const result = await response.json();

    allShipments = result.data;
    renderShipmentsTable(allShipments);
    updateRiskCounts(allShipments);
    updateRiskChart(allShipments);
  } catch (error) {
    console.error('Error loading shipments:', error);
    tbody.innerHTML = '<tr><td colspan="7" class="loading">Error loading shipments</td></tr>';
  }
}

// Render shipments table
function renderShipmentsTable(shipments) {
  const tbody = document.querySelector('#shipments-table tbody');

  if (shipments.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" class="loading">No at-risk shipments found</td></tr>';
    return;
  }

  tbody.innerHTML = shipments.map(s => `
    <tr>
      <td>#${s.id}</td>
      <td>
        <span class="risk-badge ${s.risk_level.toLowerCase()}">
          ${s.risk_score} - ${s.risk_level}
        </span>
      </td>
      <td>${s.driver_name}</td>
      <td>${s.warehouse_name}</td>
      <td>${s.region}</td>
      <td>${formatDate(s.scheduled_arrival)}</td>
      <td>
        <button class="detail-btn" onclick="showDetails(${s.id})">View</button>
      </td>
    </tr>
  `).join('');
}

// Update risk counts in stat cards
function updateRiskCounts(shipments) {
  const highRisk = shipments.filter(s => s.risk_level === 'High').length;
  const moderateRisk = shipments.filter(s => s.risk_level === 'Moderate').length;

  document.getElementById('high-risk-count').textContent = highRisk;
  document.getElementById('moderate-risk-count').textContent = moderateRisk;
}

// Update risk distribution chart
function updateRiskChart(shipments) {
  const ctx = document.getElementById('risk-chart').getContext('2d');

  const highCount = shipments.filter(s => s.risk_level === 'High').length;
  const moderateCount = shipments.filter(s => s.risk_level === 'Moderate').length;
  const lowCount = shipments.filter(s => s.risk_level === 'Low').length;

  if (riskChart) {
    riskChart.destroy();
  }

  riskChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['High Risk', 'Moderate Risk', 'Low Risk'],
      datasets: [{
        data: [highCount, moderateCount, lowCount],
        backgroundColor: ['#e74c3c', '#f39c12', '#27ae60'],
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            color: '#a0a0a0',
            padding: 20
          }
        }
      }
    }
  });
}

// Update trend chart
function updateTrendChart(trendData) {
  const ctx = document.getElementById('trend-chart').getContext('2d');

  if (trendChart) {
    trendChart.destroy();
  }

  const labels = trendData.map(d => formatShortDate(d.report_date));
  const onTimeRates = trendData.map(d => d.total > 0 ? ((d.on_time / d.total) * 100).toFixed(1) : 0);

  trendChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: 'On-Time Rate %',
        data: onTimeRates,
        borderColor: '#e94560',
        backgroundColor: 'rgba(233, 69, 96, 0.1)',
        fill: true,
        tension: 0.3
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          max: 100,
          grid: { color: 'rgba(255,255,255,0.1)' },
          ticks: { color: '#a0a0a0' }
        },
        x: {
          grid: { display: false },
          ticks: {
            color: '#a0a0a0',
            maxTicksLimit: 10
          }
        }
      },
      plugins: {
        legend: {
          labels: { color: '#a0a0a0' }
        }
      }
    }
  });
}

// Show shipment details modal
async function showDetails(shipmentId) {
  const modal = document.getElementById('modal');
  const modalBody = document.getElementById('modal-body');

  modalBody.innerHTML = '<p class="loading">Loading details...</p>';
  modal.classList.remove('hidden');

  try {
    const response = await fetch(`${API_BASE}/shipments/${shipmentId}`);
    const result = await response.json();
    const s = result.data;

    modalBody.innerHTML = `
      <div class="info-grid">
        <div class="info-item">
          <div class="info-label">Shipment ID</div>
          <div class="info-value">#${s.id}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Risk Score</div>
          <div class="info-value">
            <span class="risk-badge ${s.risk_level.toLowerCase()}">${s.risk_score} - ${s.risk_level}</span>
          </div>
        </div>
        <div class="info-item">
          <div class="info-label">Driver</div>
          <div class="info-value">${s.driver_name}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Vehicle</div>
          <div class="info-value">${s.vehicle_type}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Warehouse</div>
          <div class="info-value">${s.warehouse_name}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Region</div>
          <div class="info-value">${s.region}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Scheduled Arrival</div>
          <div class="info-value">${formatDate(s.scheduled_arrival)}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Cargo Condition</div>
          <div class="info-value">${s.cargo_condition || 'N/A'}</div>
        </div>
      </div>

      <h3 style="margin-bottom: 15px; color: #a0a0a0;">Risk Factor Breakdown</h3>
      <div class="risk-breakdown">
        ${renderRiskFactor('Traffic', s.risk_breakdown.traffic)}
        ${renderRiskFactor('Weather', s.risk_breakdown.weather)}
        ${renderRiskFactor('Driver Behavior', s.risk_breakdown.driverBehavior)}
        ${renderRiskFactor('Driver Fatigue', s.risk_breakdown.driverFatigue)}
        ${renderRiskFactor('Route Risk', s.risk_breakdown.routeRisk)}
        ${renderRiskFactor('Time Buffer', s.risk_breakdown.timeBuffer)}
      </div>
    `;
  } catch (error) {
    console.error('Error loading shipment details:', error);
    modalBody.innerHTML = '<p class="loading">Error loading details</p>';
  }
}

// Render a single risk factor bar
function renderRiskFactor(label, value) {
  return `
    <div class="risk-factor">
      <div class="risk-factor-label">${label}</div>
      <div class="risk-factor-bar">
        <div class="risk-factor-fill" style="width: ${value}%"></div>
      </div>
      <div class="risk-factor-value">${value}</div>
    </div>
  `;
}

// Close modal
function closeModal() {
  document.getElementById('modal').classList.add('hidden');
}

// Close modal when clicking outside
document.getElementById('modal').addEventListener('click', (e) => {
  if (e.target.id === 'modal') {
    closeModal();
  }
});

// Refresh all data
function refreshAll() {
  loadDashboardStats();
  loadShipments();
}

// Format date helper
function formatDate(dateStr) {
  if (!dateStr) return 'N/A';
  const date = new Date(dateStr);
  return date.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// Format short date helper
function formatShortDate(dateStr) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
