<script lang="ts" setup>
import MarkdownIt from 'markdown-it'
import {computed, onMounted, ref, watch} from 'vue';
import {useRoute} from 'vue-router';
import {storeToRefs} from 'pinia'; // Import crucial
import {useMessageStore} from '@/stores/message';

const props = defineProps<{
  serverId: string
  channelId: string
}>();

const channelId = computed(() => props.channelId);

const route = useRoute();
const messageStore = useMessageStore();

// "messages" ici est une référence réactive liée au store
const {messages, loading} = storeToRefs(messageStore);

const newMessage = ref('');

const md = new MarkdownIt({
  html: false,        // Désactive le HTML pur pour la sécurité
  linkify: true,      // Convertit automatiquement les URLs en liens
  typographer: true,
  breaks: true        // Convertit les retours à la ligne en <br> (comportement type chat)
})
const renderMarkdown = (content: string) => {
  return md.render(content);
};

const sendMessage = async () => {
  if (!newMessage.value.trim()) return;

  const content = newMessage.value;

  try {
    await messageStore.sendMessage(channelId.value, content);
    newMessage.value = ''; // On vide le champ après succès
  } catch (e) {
    // Gérer l'erreur (ex: notification toast)
  }
};

onMounted(() => {
  if (channelId) {
    messageStore.fetchMessages(channelId.value);
  }
});
watch(channelId, (newChannelId) => {
  if (newChannelId) {
    messageStore.fetchMessages(newChannelId);
  }
}, {immediate: true})
</script>

<template>
  <!-- Conteneur principal prenant toute la hauteur -->
  <v-container class="pa-0 fill-height d-flex flex-column" fluid>

    <!-- Zone des messages (scrollable) -->
    <v-responsive class="flex-grow-1 overflow-y-auto">
      <v-list bg-color="transparent" lines="three">
        <v-list-item
          v-for="msg in messages"
          :key="msg.id"
          class="px-4 py-1"
        >
          <template v-slot:prepend>
            <v-avatar color="grey-lighten-2" size="40">
              <!--              <v-img v-if="msg.user.avatar" :src="msg.user.avatar"></v-img>-->
              <v-icon icon="mdi-account"></v-icon>
            </v-avatar>
          </template>

          <v-list-item-title class="d-flex align-center">
            <span class="font-weight-bold text-subtitle-1 mr-2">{{ msg.user_id }}</span>
            <span class="text-caption text-grey">{{ msg.created_at }}</span>
          </v-list-item-title>

          <v-list-item-subtitle class="text-body-1 text-high-emphasis opacity-100">
            <div class="markdown-content" v-html="renderMarkdown(msg.content)"></div>
          </v-list-item-subtitle>
        </v-list-item>
      </v-list>
    </v-responsive>

    <!-- Zone de saisie fixe en bas -->
    <v-sheet class="pa-4" width="100%">
      <v-textarea
        v-model="newMessage"
        auto-grow
        bg-color="grey-lighten-4"
        density="compact"
        flat
        hide-details
        max-rows="5"
        placeholder="Envoyer un message..."
        rounded="lg"
        rows="1"
        variant="solo-filled"
        @keydown.enter.exact.prevent="sendMessage"
      >
        <template v-slot:prepend-inner>
          <v-btn color="grey-darken-1" density="compact" icon="mdi-plus-circle" variant="text"></v-btn>
        </template>
        <template v-slot:append-inner>
          <v-btn color="grey-darken-1" density="compact" icon="mdi-gift" variant="text"></v-btn>
          <v-btn color="grey-darken-1" density="compact" icon="mdi-sticker-emoji" variant="text"></v-btn>
          <v-btn color="grey-darken-1" density="compact" icon="mdi-emoticon" variant="text"></v-btn>
        </template>
      </v-textarea>
    </v-sheet>

  </v-container>
</template>

<style scoped>
.markdown-content :deep(p) {
  margin-bottom: 0; /* Évite les marges inutiles dans le chat */
}

.markdown-content :deep(code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 4px;
  font-family: monospace;
}

.markdown-content :deep(pre) {
  background-color: #2d2d2d;
  color: #ccc;
  padding: 10px;
  border-radius: 4px;
  margin: 8px 0;
  overflow-x: auto;
}
</style>
