import React, { useState, useEffect } from 'react';
import SplunkVisualization from '@splunk/visualizations/common/SplunkVisualization';
import Table from '@splunk/react-ui/Table';
import Star from '@splunk/react-icons/Star';
import styled from 'styled-components';

// Extract data from the datasource a format usable by the table
const formatData = (dataSources, tableColumns) => {
    if (!dataSources.primary || !dataSources.primary.data) {
        return {
            fields: [],
            data: [{
                name: "haha"
            }],
        };
    }

    // Get the names of the fields
    const fields = dataSources.primary.data.fields.map((f) => f.name);
    const data = [];

    // Convert the data from column to row form
    dataSources.primary.data.columns.forEach((col, i) => {
        if (tableColumns.includes(fields[i])) {
            col.forEach((item, j) => {
                if (!data[j]) {
                    data.push({});
                }
                data[j][fields[i]] = item;
            });
        }
    });

    return { fields, data };
};

//different Formatter for table column, can be selected and configured in definition.json
const columnFormatter = (name, rowNumber) => {

    const formatter = {
        "subtextRenderer": (value) => {
            const [type, productId] = value.split(',');
            return (
                <>
                    <div className="type" style={{ fontWeight: "bolder" }}>{type}</div>
                    <div className="productId" style={{ opacity: '0.5' }}>{productId}</div>
                </>
            )
        },
        "progressIndicatorRenderer": (value) => {
            if (!value) return;
            const [current, full] = value.split('/');
            const inPercent = current * 100 / full;
            return (
                <div className="meter" style={{
                    height: "11px",
                    position: "relative",
                    background: "#555",
                    borderRadius: "25px",
                    padding: "3px",
                    boxShadow: "inset 0 -1px 1px rgba(255, 255, 255, 0.3)"
                }}>
                    <span style={{
                        width: inPercent + "%",
                        display: "block",
                        height: "100%",
                        borderTopRightRadius: "8px",
                        borderBottomRightRadius: "8px",
                        borderTopLeftRadius: "20px",
                        borderBottomLeftRadius: "20px",
                        backgroundColor: "#99E6F7",
                        backgroundImage: "linear-gradient(center bottom,rgb(43,194,83) 37%,rgb(84,240,84) 69%)",
                        boxShadow: "inset 0 2px 9px  rgba(255,255,255,0.3), inset 0 -2px 6px rgba(0,0,0,0.4)",
                        position: "relative",
                        overflow: "hidden"
                    }}></span>
                </div>

            )

        },
        "ratingRenderer": (value) => {
            if (!value) return;

            const splitted = value.split('/');
            const rating = parseFloat(splitted[0])
            const ratingTotal = parseFloat(splitted[1])

            const ColoredStar = (coloredValue) => {
                if (coloredValue === 0) {
                    console.log("in coloredValue = 0")
                    return styled(Star)`
                        color: rgb(85, 85, 85);
                        & path {
                            stroke: rgb(85, 85, 85);
                            stroke-width: 3px;
                            margin: "0 8px";
                        }                    
                `
                }
                if (coloredValue === 1) {
                    return styled(Star)`
                    color: #A86FEF;
                        & path {
                            stroke: rgb(85, 85, 85);
                            stroke-width: 3px;
                            margin: "0 8px";
                        }         
                `
                }
                return styled(Star)`
                    & path {
                        fill: url(#partial_${rowNumber});
                        stroke: rgb(85, 85, 85);
                        stroke-width: 3px;
                        margin: "0 8px";
                    }                       
                `
            };

            const stars = [];

            for (let i = 0; i < ratingTotal; i++) {
                let coloredValue = rating - i < 0 ? 0 : rating - i > 1 ? 1 : rating - i;
                let StarComponent = ColoredStar(coloredValue)
                stars.push(<StarComponent key={i}></StarComponent>)
            }

            const fill = (rating - Math.floor(rating)) * 100;
            return (
                <>
                    <div style={{ fontSize: '28px' }}>
                        {stars}
                    </div>
                    <svg class="linear-gradient-template" style={{ height: 0 }}>
                        <linearGradient id={"partial_" + rowNumber} x1="0%" y1="0%" x2="100%" y2="0%">
                            <stop offset={fill + "%"} style={{ stopColor: "#A86FEF" }}></stop>
                            <stop offset={fill + "%"} style={{ stopColor: "rgb(85, 85, 85)" }}></stop>
                        </linearGradient>
                    </svg>
                </>
            )
        },
    }

    return formatter[name];
}


const CustomTable = ({ title, options, dataSources }) => {

    const tableColumns = options.tableColumns.map((column) => column.name);
    const [tableData, setTableData] = useState(formatData(dataSources, tableColumns));
    
    useEffect(() => {
        setTableData(formatData(dataSources, tableColumns));
    }, [dataSources.primary]);

    return (
        <>
            <div data-test="viz-title-description-container" style={{ height: "32px", padding: "6px 10px", backgroundColor: "#0b0c0e", boxShadow: "0 1px 1px 0 #0b0c0e" }}>
                <div data-test="viz-title" style={{ fontSize: "14px", fontWeight: "600", lineHeight: "20px", color: "#fafafa" }}>
                    {title}
                </div>
            </div>
            <div className="header" style={{ height: "calc(100% - 52px)", position: "relative", overflowY:"scroll"}}>
                <Table stripeRows>
                    <Table.Head>
                        {tableColumns.map((column) => {
                            return <Table.HeadCell>{column}</Table.HeadCell>
                        })}
                    </Table.Head>
                    <Table.Body >
                        {
                            tableData.data.map((row, i) => {
                                return <Table.Row>
                                    {
                                        options.tableColumns.map((column) => {
                                            return (
                                                <Table.Cell>
                                                    {columnFormatter(column.renderer, i)(row[column.name])}
                                                </Table.Cell>
                                            )
                                        })
                                    }
                                </Table.Row>
                            })
                        }
                    </Table.Body>
                </Table>
            </div>
        </>
    );
};

CustomTable.config = {
    dataContract: {
        requiredDataSources: ["primary"],
        initialRequestParams: {
            primary: {
                offset: 0,
                count: 10
            },
        }
    },
    optionsSchema: {},
    key: 'splunk.costomTable',
    name: 'CustomTable',
};

CustomTable.propTypes = {
    ...SplunkVisualization.propTypes,
};

CustomTable.defaultProps = {
    ...SplunkVisualization.defaultProps,
};

export default CustomTable;