'use client'

import { BarChart } from '@tremor/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'

interface CriteriaScoreData {
  id: string
  name: string
  averageScore: number
  count: number
}

interface CriteriaScoresProps {
  data: CriteriaScoreData[]
}

export function CriteriaScoresChart({ data }: CriteriaScoresProps) {
  if (!data?.length) return null

  const overallAverage =
    data.length > 0
      ? data.reduce((sum, d) => sum + d.averageScore, 0) / data.length
      : 0

  const chartData = data.map((d) => ({
    criterion:
      d.name.length > 40 ? d.name.substring(0, 40) + '...' : d.name,
    'Avg Score': parseFloat(d.averageScore.toFixed(2)),
  }))

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
          <span>Score by Evaluation Criteria</span>
          <span className="text-sm font-normal text-muted-foreground">
            Overall Avg: {overallAverage.toFixed(2)}
          </span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <BarChart
          data={chartData}
          index="criterion"
          categories={['Avg Score']}
          colors={['indigo']}
          maxValue={10}
          layout="vertical"
          yAxisWidth={160}
          showLegend={false}
          className="h-[300px]"
        />
      </CardContent>
    </Card>
  )
}
