import React from 'react';
import ReactApexChart from 'react-apexcharts';
import type { ApexOptions } from 'apexcharts';
import { CardTitle } from '../ui/Typography';
import { englishToPersian, formatWithThousands } from '@/utils/numberUtils';

interface ApexBarChartCardProps {
    data: { name: string; value: number }[];
    title?: string;
    color?: string;
}

const formatNumber = (value: number | string) => {
    const formatted = formatWithThousands(value);
    return englishToPersian(formatted);
};

export const ApexBarChartCard = ({ data, title, color = '#3b82f6' }: ApexBarChartCardProps) => {
    const categories = data.map((item) => item.name);
    const series = [
        {
            name: title || '',
            data: data.map((item) => item.value),
        },
    ];

    const options: ApexOptions = {
        chart: {
            type: 'bar',
            height: 250,
            toolbar: { show: false },
            fontFamily: 'inherit',
        },
        colors: [color],
        plotOptions: {
            bar: {
                borderRadius: 6,
                columnWidth: '40%',
            },
        },
        dataLabels: { enabled: false },
        grid: {
            strokeDashArray: 4,
            padding: { left: 12, right: 12 },
        },
        xaxis: {
            categories,
            labels: {
                style: { fontSize: '11px' },
                formatter: (value) => englishToPersian(value),
            },
        },
        yaxis: {
            labels: {
                style: { fontSize: '11px' },
                formatter: (value) => formatNumber(value),
                minWidth: 70,
                align: 'right',
                offsetX: 0,
            },
        },
        tooltip: {
            y: {
                formatter: (value) => formatNumber(value),
            },
            x: {
                formatter: (value) => englishToPersian(value),
            },
        },
    };

    return (
        <div className="card p-3 sm:p-4 lg:p-6">
            {title && (
                <CardTitle className="mb-3 sm:mb-4">
                    {title}
                </CardTitle>
            )}
            <ReactApexChart options={options} series={series} type="bar" height={250} />
        </div>
    );
};
