<template>
  <div class="flex flex-col h-full bg-white">
    <div class="p-5 border-b border-gray-100">
      <h2 class="text-xl font-semibold">
        Уточняем детали маршрута
      </h2>
    </div>

    <div class="flex-1 overflow-y-auto p-5" ref="messagesContainer">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="[
          'mb-4 p-3 rounded-lg max-w-[80%]',
          msg.role === 'user'
            ? 'ml-auto bg-cyan-500 text-white'
            : 'mr-auto bg-gray-100 text-gray-800'
        ]"
      >
        <p class="text-sm whitespace-pre-wrap">{{ msg.content }}</p>
      </div>

      <div v-if="loading" class="mb-4 p-3 rounded-lg max-w-[80%] mr-auto bg-gray-100 text-gray-800">
        <p class="text-sm">Думаю...</p>
      </div>

      <div ref="bottomRef"></div>
    </div>

    <div class="p-4 border-t border-gray-100">
      <div class="flex gap-2">
        <input
            v-model="userInput"
            @keyup.enter="sendMessage"
            :disabled="loading || routeBuilt"
            class="flex-1 border rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-cyan-500 disabled:bg-gray-100"
            placeholder="Напишите сообщение..."
        />
        <button
            @click="sendMessage"
            :disabled="!userInput.trim() || loading || routeBuilt"
            :class="{
            'opacity-50 cursor-not-allowed': !userInput.trim() || loading || routeBuilt
          }"
            class="bg-cyan-500 hover:bg-cyan-600 text-white px-6 rounded-lg font-semibold transition"
        >
          Отправить
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick} from 'vue';
import {useMainStore} from '../store/main';
import axios from 'axios';

const store = useMainStore();

const messages = ref([]);
const conversationHistory = ref([]);
const userInput = ref('');
const loading = ref(false);
const routeBuilt = ref(false);
const messagesContainer = ref(null);
const bottomRef = ref(null);

onMounted(async () => {
  // Отправляем первое сообщение
  const initialMessage = `Я нахожусь: ${store.address}. Мне интересно: ${store.interests}. У меня есть время: ${store.duration}`;

  messages.value.push({
    role: 'user',
    content: initialMessage
  });

  await scrollToBottom();
  await sendToServer(initialMessage);
});

async function sendMessage() {
  if (!userInput.value.trim() || loading.value || routeBuilt.value) return;

  const message = userInput.value.trim();
  userInput.value = '';

  messages.value.push({
    role: 'user',
    content: message
  });

  await scrollToBottom();
  await sendToServer(message);
}

async function sendToServer(userMessage) {
  loading.value = true;

  try {
    const response = await axios.post(import.meta.env.VITE_API_BASE_URL+'/chat', {
      user_input: userMessage,
      conversation_history: conversationHistory.value
    }, {
      timeout: 60000  // 60 секунд
    });

    const data = response.data;

    // Обновляем историю разговора
    conversationHistory.value = data.conversation_history || [];

    if (data.success && !data.need_more_info) {
      messages.value.push({
        role: 'assistant',
        content: data.result.description
      });

      store.route = {
        coordinates: data.result.route,
        places: data.result.places,
        description: data.result.description,
      };

      routeBuilt.value = true;
      await scrollToBottom();

      setTimeout(() => {
        store.screen = 6;
      }, 2000);

    } else if (data.need_more_info) {
      const lastMessage = data.conversation_history[data.conversation_history.length - 1];
      const assistantMessage = lastMessage?.content || 'Пожалуйста, уточните детали.';

      messages.value.push({
        role: 'assistant',
        content: assistantMessage
      });

      await scrollToBottom();

    } else if (data.error) {
      messages.value.push({
        role: 'assistant',
        content: data.error
      });

      await scrollToBottom();
    }

  } catch (error) {
    console.error('Chat error:', error);

    // Проверка на таймаут
    if (error.code === 'ECONNABORTED') {
      messages.value.push({
        role: 'assistant',
        content: 'Время ожидания истекло. Попробуйте еще раз.'
      });
    } else {
      messages.value.push({
        role: 'assistant',
        content: 'Произошла ошибка. Попробуйте еще раз.'
      });
    }

    await scrollToBottom();
  } finally {
    loading.value = false;
  }
}


async function scrollToBottom() {
  await nextTick();
  if (bottomRef.value) {
    bottomRef.value.scrollIntoView({behavior: 'smooth'});
  }
}
</script>
