<script setup lang="ts">
import { Plus, Workflow, Play } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { useApi } from '@/composables/useApi'
import { useRouter } from 'vue-router'

interface Process {
  id: string
  name: string
  description?: string
  latestVersion: number
  createdAt: string
  versions?: any[]
}

const { api } = useApi()
const router = useRouter()
const processes = ref<Process[]>([])
const loading = ref(true)

const getTenantId = () => {
  if (!import.meta.client) return 'tenant1'
  return localStorage.getItem('tenantId') || 'tenant1'
}

const loadProcesses = async () => {
  loading.value = true
  try {
    const data = await api.get(`/tenants/${getTenantId()}/ai-processes`)
    processes.value = data || []
  } catch (error) {
    console.error('Failed to load processes:', error)
  } finally {
    loading.value = false
  }
}

const createNewProcess = () => {
  router.push('/ai-processes/new')
}

const editProcess = (processId: string) => {
  router.push(`/ai-processes/${processId}/edit`)
}

const testProcess = async (processId: string) => {
  try {
    const result = await api.post(`/tenants/${getTenantId()}/ai-processes/${processId}/runs`, {
      input: { test: true },
    })
    console.log('Test run result:', result)
    alert('Process test started! Check console for details.')
  } catch (error: any) {
    alert(`Test failed: ${error.message}`)
  }
}

onMounted(() => {
  loadProcesses()
})
</script>

<template>
  <div class="container mx-auto p-6 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-3xl font-bold tracking-tight">AI Process Builder</h1>
        <p class="text-muted-foreground mt-1">
          Create and manage intelligent business process workflows
        </p>
      </div>
      <Button @click="createNewProcess">
        <Plus class="mr-2 h-4 w-4" />
        New Process
      </Button>
    </div>

    <div v-if="loading" class="flex items-center justify-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="processes.length === 0" class="text-center py-12">
      <Workflow class="mx-auto h-12 w-12 text-muted-foreground/50" />
      <h3 class="mt-4 text-lg font-semibold">No processes yet</h3>
      <p class="text-muted-foreground mt-1">
        Get started by creating your first AI-powered business process
      </p>
      <Button @click="createNewProcess" class="mt-4">
        <Plus class="mr-2 h-4 w-4" />
        Create Process
      </Button>
    </div>

    <div v-else class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
      <Card 
        v-for="process in processes" 
        :key="process.id"
        class="hover:shadow-lg transition-shadow cursor-pointer"
        @click="editProcess(process.id)"
      >
        <CardHeader>
          <div class="flex items-start justify-between">
            <Workflow class="h-5 w-5 text-primary" />
            <Badge variant="secondary">v{{ process.latestVersion }}</Badge>
          </div>
          <CardTitle class="mt-2">{{ process.name }}</CardTitle>
          <CardDescription>{{ process.description || 'No description' }}</CardDescription>
        </CardHeader>
        <CardContent>
          <div class="flex gap-2">
            <Button 
              size="sm" 
              variant="outline" 
              @click.stop="editProcess(process.id)"
            >
              Edit
            </Button>
            <Button 
              size="sm" 
              variant="ghost"
              @click.stop="testProcess(process.id)"
            >
              <Play class="h-3 w-3 mr-1" />
              Test
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  </div>
</template>
