import type { Column } from 'element-plus';

import type { VbenFormSchema } from '#/adapter/form';

import { $t } from '@vben/locales';

import { getWorkflowListApi } from '#/api/ai-platform/ai-platform';
import { useAppContextStore } from '#/store/app-context';

type TagType = 'danger' | 'info' | 'primary' | 'success' | 'warning';

export function getStatusOptions() {
  return [
    { label: $t('ai-platform.workflowRuns.status.pending'), value: 'pending', type: 'info' as TagType },
    { label: $t('ai-platform.workflowRuns.status.running'), value: 'running', type: 'primary' as TagType },
    { label: $t('ai-platform.workflowRuns.status.waiting'), value: 'waiting', type: 'warning' as TagType },
    { label: $t('ai-platform.workflowRuns.status.completed'), value: 'completed', type: 'success' as TagType },
    { label: $t('ai-platform.workflowRuns.status.failed'), value: 'failed', type: 'danger' as TagType },
    { label: $t('ai-platform.workflowRuns.status.stopped'), value: 'stopped', type: 'info' as TagType },
  ];
}

export function getTriggerOptions() {
  return [
    { label: $t('ai-platform.workflowRuns.trigger.editor_draft'), value: 'editor_draft', type: 'warning' as TagType },
    { label: $t('ai-platform.workflowRuns.trigger.editor_published'), value: 'editor_published', type: 'primary' as TagType },
    { label: $t('ai-platform.workflowRuns.trigger.agent'), value: 'agent', type: 'success' as TagType },
    { label: $t('ai-platform.workflowRuns.trigger.api'), value: 'api', type: 'info' as TagType },
    { label: $t('ai-platform.workflowRuns.trigger.form_button'), value: 'form_button', type: 'info' as TagType },
  ];
}

export function getTagType(value: string, options: Array<{ type?: TagType; value: string }>): TagType {
  const option = options.find((item) => item.value === value);
  return option?.type || 'info';
}

export function getTagLabel(value: string, options: Array<{ label: string; value: string }>): string {
  const option = options.find((item) => item.value === value);
  return option?.label || value;
}

export function formatDuration(ms?: number) {
  if (!ms && ms !== 0) return '-';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(2)}s`;
}

export function formatTime(value?: string) {
  if (!value) return '-';
  return new Date(value).toLocaleString();
}

export function useSearchFormSchema(): VbenFormSchema[] {
  const appContextStore = useAppContextStore();

  return [
    {
      component: 'ApiSelect',
      fieldName: 'workflowId',
      label: $t('ai-platform.workflowRuns.filters.workflow'),
      componentProps: {
        api: async () => {
          const res = await getWorkflowListApi({
            page: 1,
            pageSize: 200,
            applicationId: appContextStore.currentApp?.id,
          });
          return (res.items || []).map((item) => ({
            label: item.name,
            value: item.id,
          }));
        },
        placeholder: $t('ai-platform.workflowRuns.filters.allWorkflows'),
        clearable: true,
        filterable: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: $t('ai-platform.workflowRuns.filters.status'),
      componentProps: {
        placeholder: $t('ai-platform.workflowRuns.filters.allStatus'),
        options: getStatusOptions(),
        clearable: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'triggerType',
      label: $t('ai-platform.workflowRuns.filters.trigger'),
      componentProps: {
        placeholder: $t('ai-platform.workflowRuns.filters.allTriggers'),
        options: getTriggerOptions(),
        clearable: true,
      },
    },
  ];
}

export function useZqTableColumns(): Column[] {
  return [
    {
      key: 'workflow_name',
      dataKey: 'workflow_name',
      title: $t('ai-platform.workflowRuns.columns.workflow'),
      minWidth: 160,
    },
    {
      key: 'status',
      title: $t('ai-platform.workflowRuns.columns.status'),
      width: 110,
      align: 'center' as const,
      slots: { default: 'cell-status' },
    },
    {
      key: 'trigger_type',
      title: $t('ai-platform.workflowRuns.columns.trigger'),
      width: 140,
      align: 'center' as const,
      slots: { default: 'cell-trigger_type' },
    },
    {
      key: 'total_steps',
      dataKey: 'total_steps',
      title: $t('ai-platform.workflowRuns.columns.steps'),
      width: 80,
      align: 'center' as const,
    },
    {
      key: 'total_tokens',
      dataKey: 'total_tokens',
      title: $t('ai-platform.workflowRuns.columns.tokens'),
      width: 90,
      align: 'center' as const,
    },
    {
      key: 'elapsed_time',
      title: $t('ai-platform.workflowRuns.columns.duration'),
      width: 100,
      align: 'center' as const,
      slots: { default: 'cell-elapsed_time' },
    },
    {
      key: 'started_at',
      title: $t('ai-platform.workflowRuns.columns.startedAt'),
      width: 180,
      slots: { default: 'cell-started_at' },
    },
    {
      key: 'error_message',
      dataKey: 'error_message',
      title: $t('ai-platform.workflowRuns.columns.error'),
      minWidth: 180,
      showOverflowTooltip: true,
    },
    {
      key: 'actions',
      title: $t('ai-platform.workflowRuns.columns.actions'),
      width: 120,
      fixed: true,
      align: 'center' as const,
      slots: { default: 'cell-actions' },
    },
  ];
}
