<template>
  <div>
    <!-- Заголовок маршрута -->
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-gray-900 mb-4">Варианты доставки</h1>
      <div class="flex items-center space-x-2 text-lg">
        <div class="flex items-center">
          <svg class="w-4 h-4 text-blue-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"/>
          </svg>
          <span class="text-lg font-semibold text-gray-900">Кения</span>
        </div>
        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
        </svg>
        <div class="flex items-center">
          <svg class="w-4 h-4 text-green-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"/>
          </svg>
          <span class="text-lg font-semibold text-gray-900">Россия</span>
        </div>
      </div>
      <p class="text-gray-600 mt-2">
        Кофе, 45т
      </p>
    </div>

    <!-- Варианты маршрутов -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
      <!-- Вариант 1: Авто+Море+Авто -->
      <label class="relative bg-white rounded-lg shadow-lg p-6 cursor-pointer border-2 transition-colors" :class="selectedRoute === 'multimodal' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'">
        <input type="radio" v-model="selectedRoute" value="multimodal" class="sr-only">
        <div class="text-center">
          <div class="text-lg font-bold text-gray-900 mb-2">Авто+Море+Авто</div>
          <h3 class="text-lg font-semibold text-gray-900 mb-2">Мультимодальный</h3>
          <p class="text-green-600 font-semibold text-xl mb-1">$16,000</p>
          <p class="text-gray-500 text-sm mb-2">25 дней</p>
          <div class="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm">
            50т
          </div>
        </div>
      </label>

      <!-- Вариант 2: Ж/д прямой -->
      <label class="relative bg-white rounded-lg shadow-lg p-6 cursor-pointer border-2 transition-colors" :class="selectedRoute === 'rail' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'">
        <input type="radio" v-model="selectedRoute" value="rail" class="sr-only">
        <div class="text-center">
          <div class="text-lg font-bold text-gray-900 mb-2">Ж/д прямой</div>
          <h3 class="text-lg font-semibold text-gray-900 mb-2">Железная дорога</h3>
          <p class="text-green-600 font-semibold text-xl mb-1">$22,400</p>
          <p class="text-gray-500 text-sm mb-2">18 дней</p>
          <div class="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm">
            80т
          </div>
        </div>
      </label>

      <!-- Вариант 3: Авиа экспресс -->
      <label class="relative bg-white rounded-lg shadow-lg p-6 cursor-pointer border-2 transition-colors" :class="selectedRoute === 'air' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'">
        <input type="radio" v-model="selectedRoute" value="air" class="sr-only">
        <div class="text-center">
          <div class="text-lg font-bold text-gray-900 mb-2">Авиа экспресс</div>
          <h3 class="text-lg font-semibold text-gray-900 mb-2">Авиаперевозка</h3>
          <p class="text-green-600 font-semibold text-xl mb-1">$54,000</p>
          <p class="text-gray-500 text-sm mb-2">3 дня</p>
          <div class="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm">
            45т
          </div>
        </div>
      </label>
    </div>

    <!-- Этапы выбранного маршрута -->
    <div v-if="currentRouteData" class="bg-white rounded-lg shadow p-6 mb-6">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">Этапы маршрута: {{ currentRouteData.name }}</h2>
      <div class="space-y-6">
        <div 
          v-for="(stage, index) in currentRouteData.stages" 
          :key="index"
          class="border border-gray-200 rounded-lg p-4"
        >
          <!-- Заголовок этапа -->
          <div class="flex items-center justify-between mb-4">
            <h3 class="font-medium text-gray-900">{{ stage.name }}</h3>
            <span class="text-sm text-gray-500">{{ getStageIcon(stage.type) }}</span>
          </div>
          
          <!-- Layout этапа: 2/3 + 1/3 -->
          <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
            <!-- Левая часть (2/3): Поставщики -->
            <div class="lg:col-span-2">
              <h4 class="font-medium text-sm text-gray-700 mb-3">Доступные поставщики</h4>
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                <div 
                  v-for="(supplier, index) in stage.supplierCards" 
                  :key="supplier.name"
                  class="bg-gray-50 rounded p-3 border border-gray-100 text-center"
                >
                  <!-- Множественные аватарки поставщиков -->
                  <div class="flex justify-center mb-2 relative">
                    <div class="w-12 h-12 rounded-full overflow-hidden border-2 border-white">
                      <div v-if="getSupplierAvatarSvg(supplier.name, 0)" v-html="getSupplierAvatarSvg(supplier.name, 0)" class="w-full h-full" />
                      <div v-else class="w-full h-full bg-blue-500 flex items-center justify-center text-white font-bold text-sm">
                        {{ getSupplierInitials(supplier.name, 0) }}
                      </div>
                    </div>
                    <div class="w-12 h-12 rounded-full overflow-hidden border-2 border-white -ml-3">
                      <div v-if="getSupplierAvatarSvg(supplier.name, 1)" v-html="getSupplierAvatarSvg(supplier.name, 1)" class="w-full h-full" />
                      <div v-else class="w-full h-full bg-green-500 flex items-center justify-center text-white font-bold text-sm">
                        {{ getSupplierInitials(supplier.name, 1) }}
                      </div>
                    </div>
                    <div class="w-12 h-12 rounded-full overflow-hidden border-2 border-white -ml-3">
                      <div v-if="getSupplierAvatarSvg(supplier.name, 2)" v-html="getSupplierAvatarSvg(supplier.name, 2)" class="w-full h-full" />
                      <div v-else class="w-full h-full bg-purple-500 flex items-center justify-center text-white font-bold text-sm">
                        {{ getSupplierInitials(supplier.name, 2) }}
                      </div>
                    </div>
                    <div v-if="supplier.count.includes('5') || supplier.count.includes('6') || supplier.count.includes('7')" class="w-12 h-12 bg-orange-500 rounded-full flex items-center justify-center text-white font-bold text-sm border-2 border-white -ml-3">
                      +
                    </div>
                  </div>
                  <!-- Название -->
                  <div class="font-medium text-sm text-gray-900 mb-1">{{ supplier.name }}</div>
                  <!-- Количество -->
                  <div class="text-xs text-gray-600">{{ supplier.count }}</div>
                  <!-- Рейтинг -->
                  <div class="text-xs text-green-600 font-medium">до {{ supplier.rating }}</div>
                </div>
              </div>
            </div>

            <!-- Правая часть (1/3): Мини-карта этапа -->
            <div>
              <h4 class="font-medium text-sm text-gray-700 mb-3">Маршрут</h4>
              <RouteMap 
                :stages="[stage]" 
                :height="200"
                class="rounded border"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Финансовый блок -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">Финансовые услуги</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <!-- Страхование -->
        <div class="bg-purple-50 rounded p-4 text-center">
          <div class="font-medium text-sm">4 страховые</div>
          <div class="text-xs text-gray-600">от 1.2% до 2.8%</div>
          <div class="text-xs text-gray-500">карго, транзит, мультириск</div>
        </div>

        <!-- Факторинг -->
        <div class="bg-green-50 rounded p-4 text-center">
          <div class="font-medium text-sm">6 финансовых</div>
          <div class="text-xs text-gray-600">ставки 8-15% годовых</div>
          <div class="text-xs text-gray-500">факторинг, кредиты</div>
        </div>

        <!-- ВЭД -->
        <div class="bg-blue-50 rounded p-4 text-center">
          <div class="font-medium text-sm">3 ВЭД сервиса</div>
          <div class="text-xs text-gray-600">от $500 за партию</div>
          <div class="text-xs text-gray-500">документооборот</div>
        </div>

        <!-- Валютное -->
        <div class="bg-yellow-50 rounded p-4 text-center">
          <div class="font-medium text-sm">5 банков</div>
          <div class="text-xs text-gray-600">комиссия 0.5-1.5%</div>
          <div class="text-xs text-gray-500">валютное регулирование</div>
        </div>
      </div>
    </div>

    <!-- Итоговый расчет -->
    <div class="bg-gradient-to-r from-green-500 to-blue-500 rounded-lg shadow-xl p-6 text-white mb-6">
      <h2 class="text-xl font-bold mb-4 text-center">Итоговый расчет</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Breakdown стоимости -->
        <div>
          <div class="space-y-2">
            <div class="flex justify-between">
              <span>Товар ({{ getOptimizedWeight() }}т):</span>
              <span class="font-bold">${{ getProductCost() }}</span>
            </div>
            <div class="flex justify-between">
              <span>Логистика:</span>
              <span class="font-bold">${{ getLogisticsCost() }}</span>
            </div>
            <div class="flex justify-between">
              <span>Доп. услуги:</span>
              <span class="font-bold">${{ getAdditionalCost() }}</span>
            </div>
            <hr class="border-white/30">
            <div class="flex justify-between text-lg">
              <span>Итого:</span>
              <span class="font-bold">${{ getTotalCost() }}</span>
            </div>
          </div>
        </div>

        <!-- Сроки и детали -->
        <div>
          <div class="space-y-2">
            <div class="flex justify-between">
              <span>Срок доставки:</span>
              <span class="font-bold">{{ getDeliveryTime() }} дней</span>
            </div>
            <div class="flex justify-between">
              <span>Оптимизация веса:</span>
              <span class="font-bold">+{{ getWeightIncrease() }}т</span>
            </div>
            <div class="flex justify-between">
              <span>Экономия на тонне:</span>
              <span class="font-bold">${{ getSavingsPerTon() }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Timeline деталей -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">Timeline доставки</h2>
      <GanttTimeline 
        v-if="currentRouteData?.stages"
        :stages="currentRouteData.stages"
      />
    </div>

    <!-- Кнопка заказать -->
    <div class="text-center">
      <button 
        @click="proceedNext"
        class="px-8 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium text-lg"
      >
        Заказать маршрут: {{ currentRouteData?.name }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { GetRequestsDocument } from '~/composables/graphql/team/exchange-generated'

const route = useRoute()
const localePath = useLocalePath()
const { execute } = useGraphQL()

// Выбранный маршрут
const selectedRoute = ref('multimodal')

// Получаем calculation по ID из URL
const calculationId = route.params.id

// Загружаем данные request
const { data: requests, pending, error } = await useLazyAsyncData(
  `request-${calculationId}`,
  async () => {
    const result = await execute(GetRequestsDocument, { userId: 'anonymous-user' }, 'team', 'exchange')
    return result.getRequests
  }
)

// Находим конкретный request по UUID
const currentRequest = computed(() => {
  if (!requests.value) return null
  return requests.value.find(req => req.uuid === calculationId)
})

// Получаем данные поиска из request
const searchQuery = computed(() => {
  if (!currentRequest.value) {
    return {
      product: 'Загрузка...',
      quantity: 0,
      unit: '',
      source: 'Загрузка...',
      destination: 'Загрузка...'
    }
  }

  return {
    product: currentRequest.value.product || 'Кофе',
    quantity: currentRequest.value.quantity || 45,
    unit: currentRequest.value.unit || 'т',
    source: currentRequest.value.source || 'Кения',
    destination: currentRequest.value.destination || 'Россия'
  }
})

// Данные маршрутов
const routeData = {
  multimodal: {
    name: 'Мультимодальный',
    cost: 320,
    days: 25,
    originalWeight: 45,
    optimizedWeight: 50,
    stages: [
      {
        uuid: 'stage-1',
        name: 'Автоперевозка до порта',
        stageType: 'transport',
        transportType: 'auto',
        sourceLocationName: 'Найроби',
        destinationLocationName: 'Момбаса',
        sourceLatitude: -1.2921,
        sourceLongitude: 36.8219,
        destinationLatitude: -4.0435,
        destinationLongitude: 39.6682,
        supplierCards: [
          {name: 'Поставщики кофе', count: '5 компаний', rating: '9.2'},
          {name: 'Автоперевозчики', count: '12 компаний', rating: '8.8'}
        ],
        trips: [
          {
            uuid: 'trip-1',
            name: 'Автоперевозка Найроби-Момбаса',
            plannedLoadingDate: '2025-09-25T08:00:00',
            plannedUnloadingDate: '2025-09-26T16:00:00'
          }
        ]
      },
      {
        uuid: 'stage-2',
        name: 'Морская перевозка',
        stageType: 'transport',
        transportType: 'sea',
        sourceLocationName: 'Момбаса',
        destinationLocationName: 'СПб',
        sourceLatitude: -4.0435,
        sourceLongitude: 39.6682,
        destinationLatitude: 59.9311,
        destinationLongitude: 30.3609,
        supplierCards: [
          {name: 'Морские линии', count: '3 компании', rating: '9.1'},
          {name: 'Экспедиторы', count: '8 компаний', rating: '8.9'}
        ],
        trips: [
          {
            uuid: 'trip-2',
            name: 'Морская перевозка Момбаса-СПб',
            plannedLoadingDate: '2025-09-27T10:00:00',
            plannedUnloadingDate: '2025-10-15T14:00:00'
          }
        ]
      },
      {
        uuid: 'stage-3',
        name: 'Автоперевозка до склада',
        stageType: 'transport',
        transportType: 'auto',
        sourceLocationName: 'СПб',
        destinationLocationName: 'Москва',
        sourceLatitude: 59.9311,
        sourceLongitude: 30.3609,
        destinationLatitude: 55.7558,
        destinationLongitude: 37.6176,
        supplierCards: [
          {name: 'Автоперевозчики РФ', count: '15 компаний', rating: '8.7'}
        ],
        trips: [
          {
            uuid: 'trip-3',
            name: 'Автоперевозка СПб-Москва',
            plannedLoadingDate: '2025-10-16T09:00:00',
            plannedUnloadingDate: '2025-10-17T18:00:00'
          }
        ]
      }
    ]
  },
  rail: {
    name: 'Ж/д прямой',
    cost: 280,
    days: 18,
    originalWeight: 45,
    optimizedWeight: 80,
    stages: [
      {
        uuid: 'stage-rail',
        name: 'Ж/д перевозка',
        stageType: 'transport',
        transportType: 'rail',
        sourceLocationName: 'Найроби',
        destinationLocationName: 'Москва',
        sourceLatitude: -1.2921,
        sourceLongitude: 36.8219,
        destinationLatitude: 55.7558,
        destinationLongitude: 37.6176,
        supplierCards: [
          {name: 'Ж/д операторы', count: '2 компании', rating: '9.4'},
          {name: 'Вагонные парки', count: '5 компаний', rating: '9.0'}
        ],
        trips: [
          {
            uuid: 'trip-rail',
            name: 'Ж/д перевозка Найроби-Москва',
            plannedLoadingDate: '2025-09-25T10:00:00',
            plannedUnloadingDate: '2025-10-12T15:00:00'
          }
        ]
      }
    ]
  },
  air: {
    name: 'Авиа экспресс',
    cost: 1200,
    days: 3,
    originalWeight: 45,
    optimizedWeight: 45,
    stages: [
      {
        uuid: 'stage-air',
        name: 'Авиаперевозка',
        stageType: 'transport',
        transportType: 'air',
        sourceLocationName: 'Найроби',
        destinationLocationName: 'Москва',
        sourceLatitude: -1.2921,
        sourceLongitude: 36.8219,
        destinationLatitude: 55.7558,
        destinationLongitude: 37.6176,
        supplierCards: [
          {name: 'Авиакомпании', count: '4 компании', rating: '9.6'},
          {name: 'Карго агенты', count: '7 компаний', rating: '9.3'}
        ],
        trips: [
          {
            uuid: 'trip-air',
            name: 'Авиаперевозка Найроби-Москва',
            plannedLoadingDate: '2025-09-25T12:00:00',
            plannedUnloadingDate: '2025-09-28T08:00:00'
          }
        ]
      }
    ]
  }
}

// Текущий выбранный маршрут
const currentRouteData = computed(() => routeData[selectedRoute.value])

// Helper функции
const getStageIcon = (type) => {
  const icons = {
    auto: 'АВТО',
    sea: 'МОРЕ', 
    rail: 'Ж/Д',
    air: 'АВИА'
  }
  return icons[type] || 'ЭТАП'
}

const getSupplierInitials = (name, index = 0) => {
  if (!name) return '??'
  
  // Генерируем разные инициалы для множественных аватарок
  const variants = [
    name.substring(0, 2).toUpperCase(),
    name.substring(1, 3).toUpperCase(),
    name.substring(0, 1).toUpperCase() + name.substring(2, 3).toUpperCase(),
    (name.charAt(0) + name.charAt(name.length - 1)).toUpperCase()
  ]
  
  return variants[index] || variants[0]
}

// Расчетные функции
const getOptimizedWeight = () => {
  return currentRouteData.value?.optimizedWeight || 45
}

const getProductCost = () => {
  const weight = getOptimizedWeight()
  return (weight * 600).toLocaleString() // $600/т за кофе
}

const getLogisticsCost = () => {
  const weight = getOptimizedWeight()
  const costPerTon = currentRouteData.value?.cost || 320
  return (weight * costPerTon).toLocaleString()
}

const getAdditionalCost = () => {
  const base = getOptimizedWeight() * 50 // Примерно $50/т на доп.услуги
  return base.toLocaleString()
}

const getTotalCost = () => {
  const product = getOptimizedWeight() * 600
  const logistics = getOptimizedWeight() * (currentRouteData.value?.cost || 320)
  const additional = getOptimizedWeight() * 50
  return (product + logistics + additional).toLocaleString()
}

const getDeliveryTime = () => {
  return currentRouteData.value?.days || 25
}

const getWeightIncrease = () => {
  const original = currentRouteData.value?.originalWeight || 45
  const optimized = currentRouteData.value?.optimizedWeight || 45
  return optimized - original
}

const getSavingsPerTon = () => {
  const increase = getWeightIncrease()
  if (increase > 0) {
    // Экономия за счет оптимизации
    return (increase * 50).toLocaleString()
  }
  return '0'
}

// Кэш аватаров поставщиков
const supplierAvatars = ref(new Map())

const getSupplierAvatarSvg = (name, index) => {
  const key = `${name}-${index}`
  return supplierAvatars.value.get(key) || null
}

// Генерация аватаров поставщиков
const generateSupplierAvatars = async (name) => {
  const variants = [`${name}-1`, `${name}-2`, `${name}-3`]
  
  for (let i = 0; i < 3; i++) {
    const key = `${name}-${i}`
    if (supplierAvatars.value.has(key)) continue
    
    try {
      const seed = variants[i]
      const response = await fetch(`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}&backgroundColor=3b82f6,10b981,8b5cf6`)
      if (response.ok) {
        const svg = await response.text()
        supplierAvatars.value.set(key, svg)
      }
    } catch (error) {
      console.error('Error generating supplier avatar:', error)
    }
  }
}

// Генерируем аватары при загрузке
onMounted(async () => {
  // Генерируем аватары для всех поставщиков во всех маршрутах
  Object.values(routeData).forEach(route => {
    route.stages.forEach(stage => {
      stage.supplierCards.forEach(supplier => {
        generateSupplierAvatars(supplier.name)
      })
    })
  })
})

// Методы
const proceedNext = () => {
  alert('Заказ маршрута: ' + currentRouteData.value?.name)
}
</script>