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 {CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis} from 'recharts';


export interface LineComponentProps {
    componentName: string,
    title?: string,
    titleFontColor?: string,
    titleFontSize?: string,
    titleFontWeight?: string,
    table_name: string,
    data_columns: string[],
    showLegend?: boolean,
    width: number,
    height: number,
    lineColor: string,
    strokeWidth?: number,
}


function LineChartComponent(props: LineComponentProps) {

    const {
        title,
        titleFontColor = "black",
        titleFontSize = "18px",
        titleFontWeight = "500",
        table_name = "",
        data_columns,
        showLegend = true,
        width,
        height,
        lineColor,
        strokeWidth = 1,
    } = props;

    const [lineContent, setBarContent] = 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)]];
            // sort array in descending order by value
            mData.sort((a, b) => (a.value < b.value) ? 1 : -1);
            setBarContent(mData);
        },
        onError: (error) => {
            console.log(error);
        }
    });

    return (
        <Stack alignItems={"center"} py={8} px={3} 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>
                        :
                        <LineChart
                            width={width}
                            height={height}
                            data={lineContent}
                            margin={{
                                top: 5,
                                right: 30,
                                left: 20,
                                bottom: 5,
                            }}
                        >
                            <CartesianGrid strokeDasharray="3 3" />
                            <XAxis dataKey="name" />
                            <YAxis />
                            <Tooltip />
                            {showLegend && <Legend />}
                            <Line strokeWidth={strokeWidth} type="monotone" dataKey="value" stroke={lineColor} activeDot={{ r: 8 }} />
                        </LineChart>
            }

        </Stack>
    );
}

export default LineChartComponent;