import { jsx as _jsx } from "react/jsx-runtime";
import { useRef, useEffect, useState } from "react";
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, } from "chart.js";
import { Bar } from "react-chartjs-2";
import styles from "./styles.module.scss";
import { formatToK } from "../../utils";
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);
const CreditBarChart = ({ revenues }) => {
    const chartContainerRef = useRef(null);
    const [containerDimensions, setContainerDimensions] = useState({
        width: 0,
        height: 0,
    });
    useEffect(() => {
        const updateDimensions = () => {
            if (chartContainerRef.current) {
                const { offsetWidth, offsetHeight } = chartContainerRef.current;
                setContainerDimensions({
                    width: offsetWidth,
                    height: offsetHeight,
                });
            }
        };
        updateDimensions();
        const resizeObserver = new ResizeObserver(updateDimensions);
        if (chartContainerRef.current) {
            resizeObserver.observe(chartContainerRef.current);
        }
        window.addEventListener("resize", updateDimensions);
        return () => {
            resizeObserver.disconnect();
            window.removeEventListener("resize", updateDimensions);
        };
    }, []);
    const calculateResponsiveValues = () => {
        const width = containerDimensions.width;
        const numBars = revenues.length;
        if (width === 0)
            return {
                barThickness: 31,
                maxRotation: 0,
                fontSize: 14,
            };
        const availableWidth = width * 0.8;
        const maxBarThickness = Math.floor(availableWidth / (numBars * 2.5));
        const barThickness = Math.max(8, Math.min(maxBarThickness, 31));
        let maxRotation = 0;
        let fontSize = 14;
        const estimatedLabelWidth = fontSize * 4;
        const totalLabelsWidth = estimatedLabelWidth * numBars;
        const availableLabelSpace = width * 0.9;
        if (totalLabelsWidth > availableLabelSpace) {
            if (totalLabelsWidth > availableLabelSpace * 1.5) {
                fontSize = 10;
                maxRotation = 45;
            }
            else if (totalLabelsWidth > availableLabelSpace * 1.2) {
                fontSize = 12;
                maxRotation = 45;
            }
            else {
                maxRotation = 30;
            }
        }
        return {
            barThickness,
            maxRotation,
            fontSize,
        };
    };
    const responsiveValues = calculateResponsiveValues();
    const labels = revenues.map((data) => data.label);
    const personalEmailValues = revenues.map((data) => data.personalEmailCount);
    const personalPhoneValues = revenues.map((data) => data.personalPhoneCount);
    const workPhoneValues = revenues.map((data) => data.workPhoneCount);
    const personalEmailData = personalEmailValues.filter((value) => value !== undefined);
    const personalPhoneData = personalPhoneValues.filter((value) => value !== undefined);
    const workPhoneData = workPhoneValues.filter((value) => value !== undefined);
    const allDefinedValues = [
        ...personalEmailData,
        ...personalPhoneData,
        ...workPhoneData,
    ];
    const maxValue = allDefinedValues.length > 0 ? Math.max(...allDefinedValues) : 0;
    const fixedMax = maxValue + Math.max(maxValue * 0.1, 2);
    const data = {
        labels,
        datasets: [
            {
                label: "Personal Email",
                data: personalEmailValues,
                backgroundColor: "#0794A2",
                categoryPercentage: 0.6,
                barPercentage: 0.7,
                borderRadius: {
                    topLeft: 4,
                    topRight: 4,
                    bottomLeft: 4,
                    bottomRight: 4,
                },
                borderSkipped: false,
            },
            {
                label: "Mobile Number",
                data: personalPhoneValues,
                backgroundColor: "#6456A9",
                categoryPercentage: 0.6,
                barPercentage: 0.7,
                borderRadius: {
                    topLeft: 4,
                    topRight: 4,
                    bottomLeft: 4,
                    bottomRight: 4,
                },
                borderSkipped: false,
            },
            {
                label: "Work Phone",
                data: workPhoneValues,
                backgroundColor: "#99552F",
                categoryPercentage: 0.6,
                barPercentage: 0.7,
                borderRadius: {
                    topLeft: 4,
                    topRight: 4,
                    bottomLeft: 4,
                    bottomRight: 4,
                },
                borderSkipped: false,
            },
        ],
    };
    const options = {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                min: 0,
                max: fixedMax,
                border: {
                    color: "transparent",
                },
                grid: {
                    color: "#232323",
                    borderColor: "grey",
                    tickColor: "transparent",
                },
                ticks: {
                    callback: function (value) {
                        return value > 1000
                            ? `${Math.round(value / 1000).toFixed(0)}K`
                            : Math.round(value).toFixed(0);
                    },
                    stepSize: Math.ceil(fixedMax / 5),
                    count: 5,
                    font: {
                        family: "Inter",
                        size: responsiveValues.fontSize,
                        weight: 400,
                        lineHeight: "21px",
                    },
                    padding: 10,
                    align: "start",
                    color: "#ADADAD",
                },
            },
            x: {
                grid: {
                    display: false,
                    color: "transparent",
                    borderColor: "grey",
                    tickColor: "transparent",
                },
                ticks: {
                    color: "#868686",
                    font: {
                        family: "Inter",
                        size: responsiveValues.fontSize,
                        weight: 400,
                        lineHeight: "21px",
                    },
                    maxRotation: responsiveValues.maxRotation,
                    minRotation: 0,
                    autoSkip: false,
                    autoSkipPadding: 0,
                    labelOffset: 0,
                },
            },
        },
        plugins: {
            legend: {
                display: false,
            },
            tooltip: {
                callbacks: {
                    label: (tooltipItem) => formatToK(tooltipItem.raw),
                    title: function () {
                        return "";
                    },
                },
                bodyColor: "#FF8D4E",
                bodyFont: {
                    family: "Inter",
                    size: 14,
                    weight: 500,
                    lineHeight: "20px",
                },
                displayColors: false,
                enabled: true,
                backgroundColor: "transparent",
                titleColor: "white",
                position: "nearest",
                xAlign: "center",
                yAlign: "bottom",
            },
            title: {
                display: false,
            },
        },
    };
    return (_jsx("div", { className: styles.CreditBarChart, ref: chartContainerRef, children: _jsx(Bar, { options: options, data: data }) }));
};
export default CreditBarChart;
