import {gql, useLazyQuery} from '@apollo/client';
import {Spinner, Stack, Text} from '@chakra-ui/react';
import {snakeCase} from 'change-case';
import React, {useEffect, useState} from 'react';
import {Cell, Pie, PieChart, Tooltip} from 'recharts';

interface PieComponentProps {
    componentName?: string,
    title?: string,
    titleFontColor?: string,
    titleFontSize?: string,
    titleFontWeight?: string,
    radius?: number,
    table_name: string,
    data_columns: string[]
}

const COLORS = [
    "#0d5ac1", "#fc7e41", "#1ec227", "#9685eb", "#f50422", "#c79ed2", "#0ec0ff",
    "#cb2582", "#63b598", "#ce7d78", "#51aed9", "#ea9e70", "#c9a941", "#a48a9e",
    "#648177", "#f205e6", "#1c0365", "#14a9ad", "#4ca2f9", "#a4e43f", "#d298e2",
    "#6119d0", "#d2737d", "#c0a43c", "#f2510e", "#651be6", "#79806e", "#61da5e"
];


function PieChartComponent(props: PieComponentProps) {

    const {
        title,
        titleFontColor = "black",
        titleFontSize = "18px",
        titleFontWeight = "500",
        radius = 100,
        table_name,
        data_columns,
    } = props;

    const [pieContent, setPieContent] = useState([
        {
            name: '',
            value: 0
        }
    ]);

    useEffect(() => {
        if (data_columns.length >= 2) {
            fetchData()
        } else {
            console.log("Not enough data columns");
        }
    }, [data_columns]);


    let q = gql`
    query {
        ${snakeCase(table_name)} {
            ${data_columns.map(col => `${col}`).join(',')}
        }
    }`;

    const [fetchData, { loading, error }] = useLazyQuery(q, {
        onCompleted: (res) => {
            let mData = [...res[snakeCase(table_name)]];
            setPieContent(mData);
        },
        onError: (error) => {
            console.log(error);
        }
    });

    function getBoundingBox(multiplier: number) {
        const boxSize = radius * multiplier;
        return boxSize;
    }

    return (

        <Stack alignItems={"center"} pt={8} w="fit-content" h="fit-content"
            border="1px solid #F2F2F2" borderRadius={"8px"} bg="white">
            <Text fontSize={titleFontSize} fontWeight={titleFontWeight}
                color={titleFontColor}>{title}</Text>
            {loading ? <Spinner m={12} />
                : error ? <Text color="red.400">{error.message}</Text>
                    : data_columns.length < 2 ?
                        <Text color="red.400">
                            Not enough data columns (required: 2)
                        </Text>
                        :
                        <PieChart width={getBoundingBox(4)} height={getBoundingBox(4)}>
                            <Pie
                                data={pieContent}
                                isAnimationActive={true}
                                cx={getBoundingBox(2)}
                                cy={getBoundingBox(2)}
                                label
                                outerRadius={radius}
                                dataKey="value">
                                {pieContent.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip />
                        </PieChart>
            }

        </Stack>
    );
}

export default PieChartComponent;