'use client'

import { BarChart } from '@tremor/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { BRAND_DARK_BLUE } from './chart-theme'

interface JurorWorkloadData {
  id: string
  name: string
  assigned: number
  completed: number
  completionRate: number
}

interface JurorWorkloadProps {
  data: JurorWorkloadData[]
}

export function JurorWorkloadChart({ data }: JurorWorkloadProps) {
  if (!data?.length) return null

  const totalAssigned = data.reduce((sum, d) => sum + d.assigned, 0)
  const totalCompleted = data.reduce((sum, d) => sum + d.completed, 0)
  const overallRate =
    totalAssigned > 0 ? Math.round((totalCompleted / totalAssigned) * 100) : 0

  const sortedData = [...data].sort(
    (a, b) => b.completionRate - a.completionRate,
  )

  const chartData = sortedData.map((d) => ({
    juror: d.name.length > 25 ? d.name.substring(0, 25) + '...' : d.name,
    Completed: d.completed,
    Remaining: d.assigned - d.completed,
  }))

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>Juror Workload</span>
          <span className="text-sm font-normal text-muted-foreground">
            {overallRate}% overall completion
          </span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <BarChart
          data={chartData}
          index="juror"
          categories={['Completed', 'Remaining']}
          colors={[BRAND_DARK_BLUE, '#e5e7eb'] as string[]}
          layout="horizontal"
          stack={true}
          yAxisWidth={160}
          className={`h-[${Math.max(300, data.length * 35)}px]`}
          style={{ height: `${Math.max(300, data.length * 35)}px` }}
        />
      </CardContent>
    </Card>
  )
}
