'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { CsvExportDialog } from '@/components/shared/csv-export-dialog'

export type ExportEvaluationsDialogProps = {
  roundId: string
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function ExportEvaluationsDialog({
  roundId,
  open,
  onOpenChange,
}: ExportEvaluationsDialogProps) {
  const [exportData, setExportData] = useState<any>(undefined)
  const [isLoadingExport, setIsLoadingExport] = useState(false)
  const utils = trpc.useUtils()

  const handleRequestData = async () => {
    setIsLoadingExport(true)
    try {
      const data = await utils.export.evaluations.fetch({ roundId, includeDetails: true })
      setExportData(data)
      return data
    } finally {
      setIsLoadingExport(false)
    }
  }

  return (
    <CsvExportDialog
      open={open}
      onOpenChange={onOpenChange}
      exportData={exportData}
      isLoading={isLoadingExport}
      filename={`evaluations-${roundId}`}
      onRequestData={handleRequestData}
    />
  )
}
