'use client';

import { Bar, BarChart, XAxis } from 'recharts';
import type { OverviewRankingPoint } from '@/features/overview/server/overview-data';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Icons } from '@/components/icons';
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent
} from '@/components/ui/chart';

const chartConfig = {
  value: {
    label: 'ชั่วโมงอนุมัติ',
    color: 'var(--chart-1)'
  }
} satisfies ChartConfig;

export function BarGraph({ data }: { data: OverviewRankingPoint[] }) {
  const totalHours = data.reduce((sum, item) => sum + item.value, 0);

  return (
    <Card>
      <CardHeader>
        <CardTitle className='flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between'>
          <span>อันดับแผนกตามชั่วโมงอบรม</span>
          <Badge variant='outline' className='max-w-full whitespace-normal'>
            <Icons.trendingUp />
            {totalHours.toFixed(totalHours % 1 === 0 ? 0 : 1)} ชั่วโมง
          </Badge>
        </CardTitle>
        <CardDescription>จัดอันดับจากผลรวมชั่วโมงที่อนุมัติแล้ว แยกตามแผนก</CardDescription>
      </CardHeader>
      <CardContent>
        <ChartContainer config={chartConfig} className='min-h-[280px] w-full'>
          <BarChart accessibilityLayer data={data}>
            <XAxis
              dataKey='label'
              tickLine={false}
              tickMargin={10}
              axisLine={false}
              tickFormatter={(value) => String(value).slice(0, 8)}
            />
            <ChartTooltip cursor={false} content={<ChartTooltipContent indicator='dashed' hideLabel />} />
            <Bar dataKey='value' fill='var(--color-value)' radius={4} />
          </BarChart>
        </ChartContainer>
      </CardContent>
    </Card>
  );
}
