'use client'

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'

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

interface CriteriaScoresProps {
  data: CriteriaScoreData[]
}

// Color scale from red to green based on score
const getScoreColor = (score: number): string => {
  if (score >= 8) return '#0bd90f' // Excellent - green
  if (score >= 6) return '#82ca9d' // Good - light green
  if (score >= 4) return '#ffc658' // Average - yellow
  if (score >= 2) return '#ff7300' // Poor - orange
  return '#de0f1e' // Very poor - red
}

export function CriteriaScoresChart({ data }: CriteriaScoresProps) {
  const formattedData = data.map((d) => ({
    ...d,
    displayName:
      d.name.length > 20 ? d.name.substring(0, 20) + '...' : d.name,
  }))

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

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center 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>
        <div className="h-[300px]">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={formattedData}
              margin={{ top: 20, right: 30, bottom: 60, left: 20 }}
            >
              <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
              <XAxis
                dataKey="displayName"
                tick={{ fontSize: 11 }}
                angle={-45}
                textAnchor="end"
                interval={0}
                height={60}
              />
              <YAxis domain={[0, 10]} />
              <Tooltip
                contentStyle={{
                  backgroundColor: 'hsl(var(--card))',
                  border: '1px solid hsl(var(--border))',
                  borderRadius: '6px',
                }}
                formatter={(value: number | undefined) => [
                  (value ?? 0).toFixed(2),
                  'Average Score',
                ]}
                labelFormatter={(_, payload) => {
                  if (payload && payload[0]) {
                    const item = payload[0].payload as CriteriaScoreData
                    return `${item.name} (${item.count} ratings)`
                  }
                  return ''
                }}
              />
              <Bar dataKey="averageScore" radius={[4, 4, 0, 0]}>
                {formattedData.map((entry, index) => (
                  <Cell
                    key={`cell-${index}`}
                    fill={getScoreColor(entry.averageScore)}
                  />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </div>
      </CardContent>
    </Card>
  )
}
