'use client';

import { LabelList, Pie, PieChart } from 'recharts';
import type { OverviewDistributionPoint } 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: 'ชั่วโมงอนุมัติ'
  }
} satisfies ChartConfig;

export function PieGraph({
  data,
  total
}: {
  data: OverviewDistributionPoint[];
  total: number;
}) {
  return (
    <Card className='flex h-full flex-col'>
      <CardHeader className='items-center pb-0'>
        <CardTitle className='flex flex-col items-center gap-2 text-center sm:flex-row sm:justify-center'>
          <span>สัดส่วน K / S / A</span>
          <Badge variant='outline' className='max-w-full whitespace-normal'>
            <Icons.trendingUp />
            {total.toFixed(total % 1 === 0 ? 0 : 1)} ชั่วโมง
          </Badge>
        </CardTitle>
        <CardDescription>ชั่วโมงที่อนุมัติแล้ว แยกตามหมวด K / S / A</CardDescription>
      </CardHeader>
      <CardContent className='flex flex-1 items-center justify-center pb-0'>
        {data.length === 0 ? (
          <div className='text-muted-foreground flex min-h-[250px] items-center text-sm'>
            ยังไม่มีชั่วโมงอนุมัติสำหรับปีที่เลือก
          </div>
        ) : (
          <ChartContainer
            config={chartConfig}
            className='[&_.recharts-text]:fill-background mx-auto aspect-square max-h-[300px] min-h-[250px]'
          >
            <PieChart>
              <ChartTooltip content={<ChartTooltipContent nameKey='value' hideLabel />} />
              <Pie
                data={data}
                innerRadius={30}
                dataKey='value'
                nameKey='label'
                radius={10}
                cornerRadius={8}
                paddingAngle={4}
              >
                <LabelList
                  dataKey='value'
                  stroke='none'
                  fontSize={12}
                  fontWeight={500}
                  fill='currentColor'
                  formatter={(value: number) => value.toString()}
                />
              </Pie>
            </PieChart>
          </ChartContainer>
        )}
      </CardContent>
    </Card>
  );
}
