File size: 12,032 Bytes
5301c48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
'use client'

import { useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
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 { Loader2, Play } from "lucide-react"
import { useToast } from '@/hooks/use-toast'
import type { TemplateRegister } from '../types'
import type { WorkflowStep, TemplateResult, DatasetRecord } from './TemplateManager'

interface TemplateConfigureStepProps {
  selectedTemplate: TemplateRegister
  templateInputs: Record<string, string>
  setTemplateInputs: (inputs: Record<string, string>) => void
  parseTemplateExample: (inputExample: any) => any
  setTemplateResult: (result: TemplateResult | null) => void
  setCurrentStep: (step: WorkflowStep) => void
//   setEvaluatedData: (data: DatasetRecord[]) => void
}

export default function TemplateConfigureStep({
  selectedTemplate,
  templateInputs,
  setTemplateInputs,
  parseTemplateExample,
  setTemplateResult,
  setCurrentStep,
//   setEvaluatedData
}: TemplateConfigureStepProps) {
  const [isRunningTemplate, setIsRunningTemplate] = useState(false)
  const { toast } = useToast()

  const getInputType = (value: any): string => {
    if (typeof value === 'number') return 'number'
    if (typeof value === 'boolean') return 'checkbox'
    if (typeof value === 'object' && value !== null) return 'textarea'
    return 'text'
  }

  const getDefaultValue = (value: any): string => {
    if (typeof value === 'object' && value !== null) {
      return JSON.stringify(value, null, 2)
    }
    return String(value)
  }

  const handleInputChange = (key: string, value: string) => {
    setTemplateInputs({
      ...templateInputs,
      [key]: value
    })
  }

  const renderInputField = (key: string, value: any) => {
    const inputType = getInputType(value)
    const currentValue = templateInputs[key] || ''

    if (inputType === 'textarea') {
      return (
        <Textarea
          value={currentValue}
          onChange={(e) => handleInputChange(key, e.target.value)}
          placeholder={getDefaultValue(value)}
          className="min-h-[100px] font-mono text-sm"
        />
      )
    }

    if (inputType === 'number') {
      return (
        <Input
          type="number"
          value={currentValue}
          onChange={(e) => handleInputChange(key, e.target.value)}
          placeholder={String(value)}
        />
      )
    }

    if (inputType === 'checkbox') {
      return (
        <div className="flex items-center space-x-2">
          <input
            type="checkbox"
            checked={currentValue === 'true'}
            onChange={(e) => handleInputChange(key, e.target.checked ? 'true' : 'false')}
            className="rounded border-gray-300"
          />
          <span className="text-sm text-gray-600">
            Default: {String(value)}
          </span>
        </div>
      )
    }

    return (
      <Input
        type="text"
        value={currentValue}
        onChange={(e) => handleInputChange(key, e.target.value)}
        placeholder={String(value)}
      />
    )
  }

  const handleRunTemplate = async () => {
    setIsRunningTemplate(true)
    
    // First transition to running step
    setCurrentStep('running')
    
    try {
      const exampleData = parseTemplateExample(selectedTemplate.input_example)
      const finalInputs: Record<string, any> = {}
      
      if (exampleData) {
        Object.keys(exampleData).forEach(key => {
          const userValue = templateInputs[key]
          if (userValue && userValue.trim()) {
            const inputType = getInputType(exampleData[key])
            if (inputType === 'number') {
              finalInputs[key] = Number(userValue)
            } else if (inputType === 'checkbox') {
              finalInputs[key] = userValue === 'true'
            } else if (inputType === 'textarea') {
              try {
                finalInputs[key] = JSON.parse(userValue)
              } catch {
                finalInputs[key] = userValue
              }
            } else {
              finalInputs[key] = userValue
            }
          } else {
            finalInputs[key] = exampleData[key]
          }
        })
      }

      const response = await fetch('/api/template/run', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          templateName: selectedTemplate.name,
          inputs: finalInputs
        })
      })

      if (response.ok) {
        const result = await response.json()
        
        // Use actual API response data
        const templateResult: TemplateResult = {
          success: true,
          data: result || [],
          metadata: {
            total_records: result?.length || 0,
            execution_time: result.execution_time || 0,
            template_name: selectedTemplate.name
          }
        }

        setTemplateResult(templateResult)
        // setEvaluatedData(templateResult.data)
        
        toast({
          title: "Template executed successfully",
          description: `Generated ${templateResult.data.length} records`,
          duration: 3000,
        })

        // Transition to results step after execution completes
        setCurrentStep('results')

      } else {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Template execution failed')
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : 'An unknown error occurred'
      toast({
        title: "Template execution failed",
        description: message,
        variant: "destructive",
        duration: 5000,
      })
      // Go back to configure step on error
      setCurrentStep('configure')
    } finally {
      setIsRunningTemplate(false)
    }
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold">Template: {selectedTemplate.name}</h2>
        <p className="text-gray-600 mt-1">Configure and run your template</p>
      </div>

      <Card className="border-pink-200 bg-pink-50">
        <CardHeader>
          <CardTitle className="text-pink-800">{selectedTemplate.name}</CardTitle>
          <CardDescription>{selectedTemplate.description}</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div>
              <Label className="text-sm font-medium text-pink-700">Author:</Label>
              <p className="text-sm text-pink-600">{selectedTemplate.author}</p>
            </div>
            <div>
              <Label className="text-sm font-medium text-pink-700">Version:</Label>
              <p className="text-sm text-pink-600">v{selectedTemplate.starfish_version}</p>
            </div>
            {selectedTemplate.dependencies && selectedTemplate.dependencies.length > 0 && (
              <div>
                <Label className="text-sm font-medium text-pink-700">Dependencies:</Label>
                <div className="flex flex-wrap gap-1 mt-1">
                  {selectedTemplate.dependencies.map((dep, depIndex) => (
                    <Badge key={depIndex} variant="outline" className="text-xs">
                      {dep}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Template Inputs</CardTitle>
          <CardDescription>
            Fill out the required inputs for this template.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {selectedTemplate.input_example ? (
            <>
              {(() => {
                const exampleData = parseTemplateExample(selectedTemplate.input_example)
                if (!exampleData) {
                  return (
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <Label className="text-sm font-medium">Input Example:</Label>
                        <div className="bg-gray-100 p-4 rounded-lg border">
                          <pre className="text-sm whitespace-pre-wrap overflow-x-auto">
                            {typeof selectedTemplate.input_example === 'object'
                              ? JSON.stringify(selectedTemplate.input_example, null, 2)
                              : selectedTemplate.input_example}
                          </pre>
                        </div>
                      </div>
                      
                      <div className="space-y-4 pt-4 border-t">
                        <Label className="text-sm font-medium">Your Input (JSON format):</Label>
                        <Textarea
                          placeholder="Enter your input data in JSON format..."
                          value={templateInputs.jsonInput || ''}
                          onChange={(e) => handleInputChange('jsonInput', e.target.value)}
                          className="min-h-[200px] font-mono text-sm"
                        />
                      </div>
                    </div>
                  )
                }

                return (
                  <div className="space-y-6">
                    <div className="grid grid-cols-1 gap-4">
                      {Object.entries(exampleData).map(([key, value]) => (
                        <div key={key} className="space-y-2">
                          <Label className="text-sm font-medium capitalize">
                            {key.replace(/_/g, ' ')}
                          </Label>
                          <div className="space-y-1">
                            {renderInputField(key, value)}
                            <p className="text-xs text-gray-400">
                              Default: {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>

                    <div className="pt-4 border-t">
                      <details className="space-y-2">
                        <summary className="text-sm font-medium cursor-pointer text-gray-600 hover:text-gray-800">
                          View Raw Example
                        </summary>
                        <div className="bg-gray-100 p-4 rounded-lg border">
                          <pre className="text-sm whitespace-pre-wrap overflow-x-auto">
                            {typeof selectedTemplate.input_example === 'object'
                              ? JSON.stringify(selectedTemplate.input_example, null, 2)
                              : selectedTemplate.input_example}
                          </pre>
                        </div>
                      </details>
                    </div>
                  </div>
                )
              })()}
            </>
          ) : (
            <div className="text-center py-8">
              <p className="text-gray-500">No input example available for this template</p>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="flex justify-end">
        <Button 
          onClick={handleRunTemplate}
          disabled={isRunningTemplate}
          className="bg-pink-600 hover:bg-pink-700 text-white flex items-center gap-2 disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          {isRunningTemplate ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              Running Template...
            </>
          ) : (
            <>
              <Play className="h-4 w-4" />
              Run Template
            </>
          )}
        </Button>
      </div>
    </div>
  )
}