'use client';

import React from 'react';
import { Area, AreaChart, CartesianGrid, XAxis } from 'recharts';
import type { OverviewMonthlyTrendPoint } 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 = {
  approvedHours: {
    label: 'ชั่วโมงอนุมัติ',
    color: 'var(--chart-1)'
  },
  approvedRecords: {
    label: 'จำนวนรายการอนุมัติ',
    color: 'var(--chart-2)'
  }
} satisfies ChartConfig;

export function AreaGraph({ data }: { data: OverviewMonthlyTrendPoint[] }) {
  const totalHours = data.reduce((sum, item) => sum + item.approvedHours, 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}>
          <AreaChart accessibilityLayer data={data}>
            <CartesianGrid vertical={false} strokeDasharray='3 3' />
            <XAxis
              dataKey='month'
              tickLine={false}
              axisLine={false}
              tickMargin={8}
              tickFormatter={(value) => value.slice(0, 3)}
            />
            <ChartTooltip cursor={false} content={<ChartTooltipContent />} />
            <defs>
              <DottedBackgroundPattern config={chartConfig} />
            </defs>
            <Area
              dataKey='approvedRecords'
              type='natural'
              fill='url(#dotted-background-pattern-approvedRecords)'
              fillOpacity={0.4}
              stroke='var(--color-approvedRecords)'
              stackId='a'
              strokeWidth={0.8}
            />
            <Area
              dataKey='approvedHours'
              type='natural'
              fill='url(#dotted-background-pattern-approvedHours)'
              fillOpacity={0.4}
              stroke='var(--color-approvedHours)'
              stackId='a'
              strokeWidth={0.8}
            />
          </AreaChart>
        </ChartContainer>
      </CardContent>
    </Card>
  );
}

const DottedBackgroundPattern = ({ config }: { config: ChartConfig }) => {
  const items = Object.fromEntries(Object.entries(config).map(([key, value]) => [key, value.color]));
  return (
    <>
      {Object.entries(items).map(([key, value]) => (
        <pattern
          key={key}
          id={`dotted-background-pattern-${key}`}
          x='0'
          y='0'
          width='7'
          height='7'
          patternUnits='userSpaceOnUse'
        >
          <circle cx='5' cy='5' r='1.5' fill={value} opacity={0.5}></circle>
        </pattern>
      ))}
    </>
  );
};
