<script setup lang="ts">
import type { WorkflowVersion } from '#/api/ai-platform/ai-platform';

import { ref, watch } from 'vue';

import { Clock, RotateCcw } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElDrawer,
  ElEmpty,
  ElMessage,
  ElMessageBox,
  ElScrollbar,
  ElTag,
  ElTimeline,
  ElTimelineItem,
} from 'element-plus';

import {
  getWorkflowVersionsApi,
  rollbackWorkflowApi,
} from '#/api/ai-platform/ai-platform';

const props = defineProps<{
  visible: boolean;
  workflowId: string;
}>();

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'rollback', workflow: any): void;
}>();

const loading = ref(false);
const versions = ref<WorkflowVersion[]>([]);

const loadVersions = async () => {
  if (!props.workflowId) return;

  loading.value = true;
  try {
    const result = await getWorkflowVersionsApi(props.workflowId, {
      pageSize: 50,
    });
    versions.value = result.items;
  } catch (error) {
    console.error('Failed to load version history:', error);
    ElMessage.error(
      $t('ai-platform.workflow.editor.versionHistory.loadFailed'),
    );
  } finally {
    loading.value = false;
  }
};

watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadVersions();
    }
  },
);

const handleClose = () => {
  emit('update:visible', false);
};

const handleRollback = async (version: WorkflowVersion) => {
  try {
    await ElMessageBox.confirm(
      $t('ai-platform.workflow.editor.versionHistory.rollbackConfirm', {
        version: version.version,
      }),
      $t('ai-platform.workflow.editor.versionHistory.rollbackTitle'),
      {
        confirmButtonText: $t(
          'ai-platform.workflow.editor.versionHistory.rollbackBtn',
        ),
        cancelButtonText: $t('ai-platform.workflow.editor.cancelBtn'),
        type: 'warning',
      },
    );

    const result = await rollbackWorkflowApi(props.workflowId, version.version);
    ElMessage.success(
      $t('ai-platform.workflow.editor.versionHistory.rollbackSuccess', {
        version: version.version,
      }),
    );
    emit('rollback', result);
    handleClose();
  } catch (error: any) {
    if (error === 'cancel') return;
    console.error('Rollback failed:', error);
    ElMessage.error(
      $t('ai-platform.workflow.editor.versionHistory.rollbackFailed'),
    );
  }
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
};
</script>

<template>
  <ElDrawer
    :model-value="visible"
    :title="$t('ai-platform.workflow.editor.versionHistory.title')"
    direction="rtl"
    size="400px"
    @close="handleClose"
  >
    <div v-loading="loading" class="h-full">
      <ElScrollbar v-if="versions.length > 0" class="h-full">
        <ElTimeline class="px-4">
          <ElTimelineItem
            v-for="version in versions"
            :key="version.id"
            :timestamp="formatDate(version.published_at)"
            placement="top"
          >
            <div class="border-border bg-card rounded-lg border p-4 shadow-sm">
              <div class="mb-2 flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <ElTag type="primary" size="small">
                    v{{ version.version }}
                  </ElTag>
                  <span
                    v-if="version.published_by"
                    class="text-muted-foreground text-xs"
                  >
                    {{ version.published_by }}
                  </span>
                </div>
                <ElButton
                  size="small"
                  :icon="RotateCcw"
                  @click="handleRollback(version)"
                >
                  {{
                    $t('ai-platform.workflow.editor.versionHistory.rollback')
                  }}
                </ElButton>
              </div>

              <p
                v-if="version.description"
                class="text-muted-foreground mb-2 text-sm"
              >
                {{ version.description }}
              </p>
              <p v-else class="text-muted-foreground/50 mb-2 text-sm italic">
                {{
                  $t('ai-platform.workflow.editor.versionHistory.noDescription')
                }}
              </p>

              <div
                class="text-muted-foreground flex items-center gap-4 text-xs"
              >
                <span>{{
                  $t('ai-platform.workflow.editor.versionHistory.runCount', {
                    count: version.run_count,
                  })
                }}</span>
                <span>{{
                  $t(
                    'ai-platform.workflow.editor.versionHistory.successCount',
                    { count: version.success_count },
                  )
                }}</span>
              </div>
            </div>
          </ElTimelineItem>
        </ElTimeline>
      </ElScrollbar>

      <ElEmpty
        v-else
        :description="$t('ai-platform.workflow.editor.versionHistory.empty')"
        class="mt-20"
      >
        <template #image>
          <Clock class="text-muted-foreground/30 size-16" />
        </template>
      </ElEmpty>
    </div>
  </ElDrawer>
</template>
