<script setup lang="ts">
import { Save, Play, ArrowLeft } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { useApi } from '@/composables/useApi'
import { useRouter, useRoute } from 'vue-router'

interface ProcessGraph {
  id: string
  name: string
  description?: string
  nodes: any[]
  edges: any[]
}

const { api } = useApi()
const router = useRouter()
const route = useRoute()
const processId = computed(() => route.params.id === 'new' ? null : String(route.params.id))

const processName = ref('')
const processDescription = ref('')
const graphDefinition = ref<ProcessGraph | null>(null)
const saving = ref(false)
const loading = ref(true)

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

const loadProcess = async () => {
  if (!processId.value) {
    loading.value = false
    return
  }

  loading.value = true
  try {
    const data = await api.get(`/tenants/${getTenantId()}/ai-processes/${processId.value}`)
    processName.value = data.name
    processDescription.value = data.description || ''
    
    if (data.versions && data.versions.length > 0) {
      const latestVersion = data.versions[data.versions.length - 1]
      graphDefinition.value = latestVersion.graphJson
      
      // Send graph to iframe
      sendGraphToEditor(latestVersion.graphJson)
    }
  } catch (error) {
    console.error('Failed to load process:', error)
    alert('Failed to load process')
  } finally {
    loading.value = false
  }
}

const sendGraphToEditor = (graph: any) => {
  const iframe = document.getElementById('process-editor-iframe') as HTMLIFrameElement
  if (iframe && iframe.contentWindow) {
    iframe.contentWindow.postMessage({
      type: 'LOAD_GRAPH',
      payload: graph
    }, '*')
  }
}

const saveProcess = async () => {
  if (!processName.value.trim()) {
    alert('Process name is required')
    return
  }

  if (!graphDefinition.value) {
    alert('Please design the process graph first')
    return
  }

  saving.value = true
  try {
    if (processId.value) {
      // Update existing process (create new version)
      await api.post(`/tenants/${getTenantId()}/ai-processes/${processId.value}/versions`, {
        graph: graphDefinition.value
      })
      alert('Process version saved successfully!')
    } else {
      // Create new process
      const result = await api.post(`/tenants/${getTenantId()}/ai-processes`, {
        name: processName.value,
        description: processDescription.value,
        graph: graphDefinition.value
      })
      alert('Process created successfully!')
      router.push(`/ai-processes/${result.id}/edit`)
    }
  } catch (error: any) {
    console.error('Failed to save process:', error)
    alert(`Save failed: ${error.message || 'Unknown error'}`)
  } finally {
    saving.value = false
  }
}

const testRun = async () => {
  if (!processId.value) {
    alert('Please save the process first')
    return
  }

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

const handleEditorMessage = (event: MessageEvent) => {
  if (event.data.type === 'GRAPH_UPDATED') {
    graphDefinition.value = event.data.payload
  }
}

onMounted(() => {
  loadProcess()
  window.addEventListener('message', handleEditorMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', handleEditorMessage)
})
</script>

<template>
  <div class="h-screen flex flex-col">
    <!-- Header -->
    <div class="border-b bg-background px-6 py-3 flex items-center justify-between">
      <div class="flex items-center gap-4 flex-1">
        <Button variant="ghost" size="icon" @click="router.push('/ai-processes')">
          <ArrowLeft class="h-4 w-4" />
        </Button>
        <div class="flex-1 max-w-md">
          <Input 
            v-model="processName" 
            placeholder="Process Name"
            class="font-semibold"
          />
        </div>
      </div>
      <div class="flex items-center gap-2">
        <Button variant="outline" @click="testRun" :disabled="!processId">
          <Play class="h-4 w-4 mr-2" />
          Test Run
        </Button>
        <Button @click="saveProcess" :disabled="saving">
          <Save class="h-4 w-4 mr-2" />
          {{ saving ? 'Saving...' : 'Save' }}
        </Button>
      </div>
    </div>

    <!-- Process Description -->
    <div class="border-b bg-background px-6 py-2">
      <Textarea 
        v-model="processDescription" 
        placeholder="Process description (optional)"
        class="resize-none text-sm"
        rows="2"
      />
    </div>

    <!-- Editor Iframe -->
    <div class="flex-1 relative">
      <div v-if="loading" class="absolute inset-0 flex items-center justify-center bg-background/80">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
      <iframe
        id="process-editor-iframe"
        src="/ai-processes-editor/index.html"
        class="w-full h-full border-0"
        title="Process Editor"
      />
    </div>
  </div>
</template>
