<script setup lang="ts">
import type { BotInfo } from '@easyflow/types';

import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { tryit } from 'radash';

import { getBotDetails } from '#/api';
import { hasPermission } from '#/api/common/hasPermission';

import Config from './config.vue';
import Preview from './preview.vue';
import Prompt from './prompt.vue';

const route = useRoute();
const router = useRouter();
const hasSavePermission = computed(() =>
  hasPermission(['/api/v1/bot/save', '/api/v1/bot/updateLlmId']),
);
const bot = ref<BotInfo>();

function syncNavTitle(title: string) {
  if (!title) {
    return;
  }
  const query = route.query as Record<string, any>;
  const navTitle = Array.isArray(query.navTitle)
    ? query.navTitle[0]
    : query.navTitle;
  if (typeof navTitle === 'string' && navTitle.trim()) {
    return;
  }
  router.replace({
    path: route.path,
    query: {
      ...query,
      pageKey: query.pageKey || '/ai/bots',
      navTitle: title,
    },
  });
}

onMounted(() => {
  if (route.params.id) {
    fetchBotDetail(route.params.id as string);
  }
});

const fetchBotDetail = async (id: string) => {
  const [, res] = await tryit(getBotDetails)(id);

  if (res?.errorCode === 0) {
    bot.value = res.data;
    syncNavTitle((res.data?.title || res.data?.name || '') as string);
  }
};
</script>

<template>
  <div class="settings-container">
    <div class="row-container">
      <div class="row-item">
        <Prompt :bot="bot" :has-save-permission="hasSavePermission" />
      </div>
      <div class="row-item">
        <Config :bot="bot" :has-save-permission="hasSavePermission" />
      </div>
      <div class="row-item">
        <Preview :bot="bot" />
      </div>
    </div>
  </div>
</template>
<style scoped>
.settings-container {
  height: calc(100vh - 90px);
  padding: 20px;
}

.row-container {
  display: flex;
  gap: 20px;
  height: 100%;
}

.row-item {
  flex: 1;
  min-width: 0;
  height: 100%;
}
</style>
