<template>
  <div class="calendar-container">
    <div class="mb-4 flex items-center justify-between">
      <h3 class="text-lg font-semibold text-gray-900">Календарь рейсов</h3>
      <div class="flex items-center space-x-4">
        <!-- Фильтры -->
        <div class="flex items-center space-x-2">
          <input 
            id="show-loading" 
            v-model="showLoading" 
            type="checkbox" 
            class="rounded"
          >
          <label for="show-loading" class="text-sm text-gray-600">Погрузки</label>
        </div>
        <div class="flex items-center space-x-2">
          <input 
            id="show-unloading" 
            v-model="showUnloading" 
            type="checkbox" 
            class="rounded"
          >
          <label for="show-unloading" class="text-sm text-gray-600">Выгрузки</label>
        </div>
      </div>
    </div>
    
    <!-- Simplified calendar view -->
    <div class="bg-white rounded-lg border p-4">
      <div class="grid grid-cols-7 gap-2 mb-4">
        <div v-for="month in months" :key="month.name" class="text-center">
          <h4 class="font-medium text-sm text-gray-700">{{ month.name }}</h4>
          <div class="mt-2 space-y-1">
            <div 
              v-for="week in month.weeks" 
              :key="week.start"
              class="text-xs"
            >
              <div class="flex items-center justify-between">
                <span class="text-gray-500">{{ formatWeek(week.start) }}</span>
                <div class="flex space-x-1">
                  <div 
                    v-for="event in week.events" 
                    :key="event.id"
                    class="w-2 h-2 rounded-full"
                    :style="{ backgroundColor: event.color }"
                    :title="event.title"
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Event summary -->
      <div class="border-t pt-4">
        <h4 class="font-medium text-sm text-gray-700 mb-3">Статистика по периодам:</h4>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div v-for="period in periodStats" :key="period.name" class="bg-gray-50 rounded-lg p-3">
            <h5 class="font-medium text-sm text-gray-800">{{ period.name }}</h5>
            <p class="text-xs text-gray-600 mt-1">{{ period.description }}</p>
            <div class="mt-2 space-y-1">
              <div class="flex justify-between text-xs">
                <span>Рейсы:</span>
                <span class="font-medium">{{ period.tripCount }}</span>
              </div>
              <div class="flex justify-between text-xs">
                <span>Компании:</span>
                <span class="font-medium">{{ period.companyCount }}</span>
              </div>
              <div class="flex justify-between text-xs">
                <span>Вес:</span>
                <span class="font-medium">{{ period.totalWeight }}т</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  stages: {
    type: Array,
    default: () => []
  }
})

const showLoading = ref(true)
const showUnloading = ref(true)

const allTrips = computed(() => {
  const trips = []
  props.stages.forEach(stage => {
    if (stage.trips?.length) {
      stage.trips.forEach(trip => {
        trips.push({
          ...trip,
          stageName: stage.name,
          stageType: stage.stageType
        })
      })
    }
  })
  return trips
})

const calendarEvents = computed(() => {
  const events = []
  
  allTrips.value.forEach(trip => {
    const companyColor = getCompanyColor(trip.company?.name)
    
    if (showLoading.value && trip.plannedLoadingDate) {
      events.push({
        id: `loading-${trip.uuid}`,
        title: `${trip.name} - Погрузка`,
        date: new Date(trip.plannedLoadingDate),
        color: companyColor,
        type: 'loading',
        trip: trip
      })
    }
    
    if (showUnloading.value && trip.plannedUnloadingDate) {
      events.push({
        id: `unloading-${trip.uuid}`,
        title: `${trip.name} - Выгрузка`,
        date: new Date(trip.plannedUnloadingDate),
        color: companyColor,
        type: 'unloading',
        trip: trip
      })
    }
  })
  
  return events
})

const months = computed(() => {
  const monthsData = []
  const startDate = new Date('2024-08-01')
  const endDate = new Date('2024-10-31')
  
  const monthNames = ['Авг 2024', 'Сен 2024', 'Окт 2024']
  
  monthNames.forEach((name, index) => {
    const monthStart = new Date(2024, 7 + index, 1) // Август = 7
    const monthEnd = new Date(2024, 8 + index, 0)
    
    const weeks = []
    let weekStart = new Date(monthStart)
    
    while (weekStart <= monthEnd) {
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekEnd.getDate() + 6)
      
      const weekEvents = calendarEvents.value.filter(event => {
        const eventDate = event.date
        return eventDate >= weekStart && eventDate <= weekEnd
      })
      
      weeks.push({
        start: new Date(weekStart),
        events: weekEvents.slice(0, 5) // Показываем максимум 5 событий
      })
      
      weekStart.setDate(weekStart.getDate() + 7)
    }
    
    monthsData.push({
      name,
      weeks
    })
  })
  
  return monthsData
})

const periodStats = computed(() => {
  const stats = []
  
  // Статистика по этапам
  props.stages.forEach(stage => {
    if (stage.trips?.length) {
      const companies = new Set(stage.trips.map(trip => trip.company?.name).filter(Boolean))
      const totalWeight = stage.trips.reduce((sum, trip) => sum + (trip.plannedWeight || 0), 0)
      
      stats.push({
        name: stage.name,
        description: stage.stageType === 'transport' ? getTransportTypeText(stage.transportType) : 'Услуга',
        tripCount: stage.trips.length,
        companyCount: companies.size,
        totalWeight: totalWeight
      })
    } else {
      stats.push({
        name: stage.name,
        description: 'Сервисный этап',
        tripCount: 0,
        companyCount: stage.selectedCompany ? 1 : 0,
        totalWeight: 0
      })
    }
  })
  
  return stats
})

const getCompanyColor = (companyName) => {
  const colors = {
    'Kenya Coffee Logistics Ltd': '#ef4444',
    'Kenya Highland Transport': '#f97316', 
    'Mombasa Express Cargo': '#eab308',
    'East Africa Shipping Lines': '#3b82f6',
    'ООО "Грузовичок"': '#10b981',
    'ИП Автобаза №1': '#8b5cf6',
    'ООО "ЖДТранс"': '#ec4899'
  }
  return colors[companyName] || '#6b7280'
}

const getTransportTypeText = (transportType) => {
  const texts = {
    auto: 'Автоперевозка',
    rail: 'Ж/д перевозка', 
    sea: 'Морская перевозка',
    air: 'Авиаперевозка'
  }
  return texts[transportType] || transportType
}

const formatWeek = (date) => {
  return `${date.getDate()}-${date.getDate() + 6}`
}
</script>

<style scoped>
.calendar-container {
  @apply w-full;
}
</style>