File size: 11,898 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
'use client'

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Textarea } from "@/components/ui/textarea"
import { ArrowLeft, Star, Eye, ChevronLeft, ChevronRight } from "lucide-react"
import { useState, useRef, useCallback, useEffect } from "react"
import type { TemplateResult } from './TemplateManager'

interface TemplateResultsStepProps {
  templateResult: TemplateResult | null
  onEvaluate: (evaluatedData: any[], skipEvaluation: boolean) => void
  onBackToConfigure: () => void
}

export default function TemplateResultsStep({
  templateResult,
  onEvaluate,
  onBackToConfigure
}: TemplateResultsStepProps) {
  const [currentPage, setCurrentPage] = useState(1)
  const [columnWidths, setColumnWidths] = useState<Record<string, number>>({})
  const [isResizing, setIsResizing] = useState(false)
  const [resizingColumn, setResizingColumn] = useState<string | null>(null)
  const [ratings, setRatings] = useState<Record<string, number>>({})
  const [comments, setComments] = useState<Record<string, string>>({})
  const tableRef = useRef<HTMLTableElement>(null)
  const recordsPerPage = 10
  
  const totalRecords = templateResult?.data.length || 0
  const totalPages = Math.ceil(totalRecords / recordsPerPage)
  const startIndex = (currentPage - 1) * recordsPerPage
  const endIndex = startIndex + recordsPerPage
  const currentRecords = templateResult?.data.slice(startIndex, endIndex) || []

  const dataColumns = templateResult?.data && templateResult.data.length > 0 
    ? Object.keys(templateResult.data[0]).filter(key => key !== 'id').slice(0, 5)
    : []
  
  const columns = [...dataColumns, 'rating', 'comments']

  // Initialize ratings and comments from existing data
  useEffect(() => {
    if (templateResult?.data) {
      const initialRatings: Record<string, number> = {}
      const initialComments: Record<string, string> = {}
      
      templateResult.data.forEach(record => {
        if (record.rating) initialRatings[record.id] = record.rating
        if (record.comments) initialComments[record.id] = record.comments
      })
      
      setRatings(initialRatings)
      setComments(initialComments)
    }
  }, [templateResult])

  const goToPage = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)))
  }

  const handleMouseDown = useCallback((e: React.MouseEvent, columnKey: string) => {
    e.preventDefault()
    setIsResizing(true)
    setResizingColumn(columnKey)
    
    const startX = e.clientX
    const startWidth = columnWidths[columnKey] || (columnKey === 'id' ? 80 : 192) // default widths
    
    const handleMouseMove = (e: MouseEvent) => {
      const diff = e.clientX - startX
      const newWidth = Math.max(60, startWidth + diff) // minimum width of 60px
      setColumnWidths(prev => ({
        ...prev,
        [columnKey]: newWidth
      }))
    }
    
    const handleMouseUp = () => {
      setIsResizing(false)
      setResizingColumn(null)
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
    
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
  }, [columnWidths])

  const getColumnWidth = (columnKey: string) => {
    if (columnKey === 'rating') return columnWidths[columnKey] || 120
    if (columnKey === 'comments') return columnWidths[columnKey] || 200
    return columnWidths[columnKey] || 192
  }

  const handleRatingClick = (recordId: string, rating: number) => {
    setRatings(prev => ({
      ...prev,
      [recordId]: rating
    }))
  }

  const handleCommentChange = (recordId: string, comment: string) => {
    setComments(prev => ({
      ...prev,
      [recordId]: comment
    }))
  }

  const StarRating = ({ recordId, currentRating }: { recordId: string, currentRating: number }) => {
    const [hoveredRating, setHoveredRating] = useState(0)
    
    return (
      <div className="flex items-center gap-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <Star
            key={star}
            className={`h-4 w-4 cursor-pointer transition-colors ${
              star <= (hoveredRating || currentRating)
                ? 'fill-yellow-400 text-yellow-400'
                : 'text-gray-300 hover:text-yellow-400'
            }`}
            onClick={() => handleRatingClick(recordId, star)}
            onMouseEnter={() => setHoveredRating(star)}
            onMouseLeave={() => setHoveredRating(0)}
          />
        ))}
      </div>
    )
  }

  const handleEvaluate = () => {
    if (!templateResult?.data) return

    // Update existing records with ratings and comments, don't add new columns
    const evaluatedData = templateResult.data.map(record => ({
      ...record,
      rating: ratings[record.id] || record.rating || 0,
      comments: comments[record.id] || record.comments || ''
    }))

    onEvaluate(evaluatedData, false)
  }

  const handleSkipEvaluation = () => {
    onEvaluate([], true)
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">Template Results</h2>
          <p className="text-gray-600 mt-1">
            Generated {templateResult?.data.length} records • 
            Execution time: {templateResult?.metadata?.execution_time}s
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button 
            onClick={handleEvaluate}
            className="bg-pink-600 hover:bg-pink-700 text-white flex items-center gap-2"
          >
            Evaluate Results
          </Button>
          <Button 
            onClick={handleSkipEvaluation}
            className="bg-pink-600 hover:bg-pink-700 text-white flex items-center gap-2"
          >
            Skip Evaluation
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Eye className="h-5 w-5" />
            Dataset Preview
          </CardTitle>
          <CardDescription>
            Review the generated data before evaluation. Rate each record and add comments.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {templateResult?.data && templateResult.data.length > 0 ? (
            <div className="space-y-4">
              <div className="overflow-x-auto">
                <Table ref={tableRef} className="table-fixed">
                  <TableHeader>
                    <TableRow>
                      {columns.map((columnKey) => (
                        <TableHead 
                          key={columnKey} 
                          className="capitalize relative border-r border-gray-200 last:border-r-0"
                          style={{ width: `${getColumnWidth(columnKey)}px` }}
                        >
                          <div className="flex items-center justify-between">
                            <span>
                              {columnKey === 'rating' ? 'Rating' : 
                               columnKey === 'comments' ? 'Comments' : 
                               columnKey.replace(/_/g, ' ')}
                            </span>
                            <div
                              className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-blue-500 hover:opacity-50 transition-colors"
                              onMouseDown={(e) => handleMouseDown(e, columnKey)}
                              style={{
                                backgroundColor: resizingColumn === columnKey ? '#3b82f6' : 'transparent'
                              }}
                            />
                          </div>
                        </TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {currentRecords.map((record) => (
                      <TableRow key={record.id}>
                        {dataColumns.map((columnKey) => (
                          <TableCell 
                            key={columnKey} 
                            className="border-r border-gray-200"
                            style={{ width: `${getColumnWidth(columnKey)}px` }}
                          >
                            <div className="whitespace-pre-wrap break-words max-h-32 overflow-y-auto">
                              {typeof record[columnKey] === 'object' 
                                ? JSON.stringify(record[columnKey], null, 2) 
                                : String(record[columnKey] || '')
                              }
                            </div>
                          </TableCell>
                        ))}
                        <TableCell 
                          className="border-r border-gray-200"
                          style={{ width: `${getColumnWidth('rating')}px` }}
                        >
                          <StarRating 
                            recordId={record.id} 
                            currentRating={ratings[record.id] || 0} 
                          />
                        </TableCell>
                        <TableCell 
                          className="last:border-r-0"
                          style={{ width: `${getColumnWidth('comments')}px` }}
                        >
                          <Textarea
                            placeholder="Add comments..."
                            value={comments[record.id] || ''}
                            onChange={(e) => handleCommentChange(record.id, e.target.value)}
                            className="min-h-[60px] resize-none text-sm"
                          />
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              
              {totalPages > 1 && (
                <div className="flex items-center justify-between">
                  <p className="text-sm text-gray-500">
                    Showing {startIndex + 1}-{Math.min(endIndex, totalRecords)} of {totalRecords} records
                  </p>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => goToPage(currentPage - 1)}
                      disabled={currentPage === 1}
                    >
                      <ChevronLeft className="h-4 w-4" />
                      Previous
                    </Button>
                    <span className="text-sm">
                      Page {currentPage} of {totalPages}
                    </span>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => goToPage(currentPage + 1)}
                      disabled={currentPage === totalPages}
                    >
                      Next
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="text-center py-8">
              <p className="text-gray-500">No data generated</p>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="flex justify-between">
        <Button 
          variant="outline"
          onClick={onBackToConfigure}
          className="flex items-center gap-2"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Configure
        </Button>
      </div>
    </div>
  )
}