import LoaderIcon from '@/components/icons/loader-icon';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import { ArrowsLeftRightIcon } from '@phosphor-icons/react';
import { Suspense } from 'react';
import Chart from 'react-apexcharts';
import { useTranslation } from 'react-i18next';
import DashboardCard from './dashboard-card';

type TransactionsChartData = {
  categories: string[];
  deposits: number[];
  withdrawals: number[];
  investments: number[];
};

export function TransactionsChart() {
  const { t } = useTranslation();
  const { format } = useCurrency();
  const { data, isLoading } = useApiSWR<TransactionsChartData>(
    '/admin/dashboard/transactions-chart',
  );

  const series = [
    { name: t('Deposits'), data: data?.deposits ?? [] },
    { name: t('Withdraw'), data: data?.withdrawals ?? [] },
    { name: t('Investment'), data: data?.investments ?? [] },
  ];

  const options: ApexCharts.ApexOptions = {
    chart: {
      id: 'basic-bar',
      stacked: false,
      offsetY: 0,
      toolbar: { show: false },
    },
    xaxis: {
      categories: data?.categories ?? [],
      labels: {
        style: { cssClass: 'text-[11px] font-bold fill-black/50' },
      },
      axisBorder: { show: false },
      axisTicks: { show: false },
    },
    dataLabels: { enabled: false },
    legend: {
      show: true,
      fontSize: '11px',
      markers: { size: 8, shape: undefined, strokeWidth: 1 },
    },
    plotOptions: {
      bar: {
        horizontal: false,
        borderRadius: 10,
        borderRadiusApplication: 'around',
      },
    },
    colors: ['#81C522', '#AC222A', '#5494FF'],
    forecastDataPoints: { count: 1, fillOpacity: 1 },
    stroke: { show: true, width: 4, colors: ['transparent'] },
    yaxis: {
      labels: {
        formatter(value) {
          return format(value);
        },
        style: {
          cssClass: 'text-[11px] font-normal leading-4 fill-secondary-text',
        },
      },
    },
    grid: {
      borderColor: '#E0E0E0',
      padding: { bottom: 0 },
    },
  };

  return (
    <DashboardCard
      icon={ArrowsLeftRightIcon}
      title={t('Transactions Overview')}
      className="col-span-1 md:col-span-4"
      link="/admin/transactions/history"
    >
      {isLoading ? (
        <div className="flex h-[300px] items-center justify-center">
          <LoaderIcon />
        </div>
      ) : (
        <Suspense fallback={<LoaderIcon />}>
          <Chart
            options={options}
            series={series}
            type="bar"
            width="100%"
            height="300px"
          />
        </Suspense>
      )}
    </DashboardCard>
  );
}
