'use client'

import { ResponsiveBar, type ComputedDatum } from '@nivo/bar'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { nivoTheme } from './chart-theme'

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

interface JurorWorkloadProps {
  data: JurorWorkloadData[]
}

type WorkloadBarDatum = {
  juror: string
  completed: number
  remaining: number
  completionRate: number
  fullName: string
}

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: WorkloadBarDatum[] = sortedData.map((d) => ({
    juror: d.name.length > 25 ? d.name.substring(0, 25) + '...' : d.name,
    completed: d.completed,
    remaining: d.assigned - d.completed,
    completionRate: d.completionRate,
    fullName: d.name,
  }))

  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>
        <div
          style={{ height: `${Math.max(300, data.length * 35)}px` }}
        >
          <ResponsiveBar
            data={chartData}
            keys={['completed', 'remaining']}
            indexBy="juror"
            layout="horizontal"
            theme={nivoTheme}
            colors={['#053d57', '#e5e7eb']}
            borderRadius={2}
            enableLabel={true}
            label={(d: ComputedDatum<WorkloadBarDatum>) => {
              if (d.id === 'completed') {
                return `${d.data.completionRate}%`
              }
              return ''
            }}
            labelSkipWidth={40}
            labelTextColor={(d) => {
              const datum = d as unknown as { data: ComputedDatum<WorkloadBarDatum> }
              return datum.data.id === 'completed' ? '#ffffff' : '#374151'
            }}
            margin={{ top: 10, right: 30, bottom: 30, left: 160 }}
            padding={0.25}
            groupMode="stacked"
            tooltip={({ id, value, data: rowData }) => (
              <div
                style={{
                  background: '#ffffff',
                  padding: '8px 12px',
                  borderRadius: '8px',
                  boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                  border: '1px solid #e5e7eb',
                  fontSize: 12,
                }}
              >
                <strong>{rowData.fullName}</strong>
                <br />
                {id === 'completed' ? 'Completed' : 'Remaining'}: {value}
                <br />
                Completion: {rowData.completionRate}%
              </div>
            )}
            legends={[
              {
                dataFrom: 'keys',
                anchor: 'bottom',
                direction: 'row',
                translateY: 30,
                itemsSpacing: 20,
                itemWidth: 100,
                itemHeight: 18,
                symbolSize: 12,
                symbolShape: 'square',
              },
            ]}
            animate={true}
          />
        </div>
      </CardContent>
    </Card>
  )
}
