'use client'

import axios from "axios";
import { useEffect, useState } from "react";
import { Bar, BarChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";

interface Props {
    filtros: any
}

interface UsoData {
    uso: string
    adscripcion: string
    total: number
}

const colores = [
    "#818CF8",
    "#34D399",
    "#FBBF24",
    "#F87171",
    "#67E8F9",
    "#C084FC"
]

const api_url = process.env.NEXT_PUBLIC_API_URL;

export default function Uso({ filtros }: Props) {
    const [data, setData] = useState<UsoData[]>([])

    useEffect(() => {
        const getUso = async () => {
            const response = await axios.post(
                `${api_url}/equipos/grafica/uso`, filtros
            )
            setData(response.data)
        }
        getUso()

    }, [filtros])

    const tieneAdscripciones = data.some(d => d.adscripcion)

    let dataTransformada = data
    let adscripciones: string[] = []

    if (tieneAdscripciones) {

        adscripciones = [...new Set(data.map(d => d.adscripcion))]

        dataTransformada = Object.values(
            data.reduce((acc: any, item: any) => {

                if (!acc[item.uso]) {
                    acc[item.uso] = { uso: item.uso }
                }

                acc[item.uso][item.adscripcion] = Number(item.total)

                return acc

            }, {})
        )
    }

    return (
        <div style={{ minWidth: "570px", background: "white", borderRadius: "10px", padding: "1rem" }}>
            <h1 style={{ margin: "0" }}>Uso por equipo</h1>
            <ResponsiveContainer width="100%" aspect={2.5} minHeight={220}>
                <BarChart data={dataTransformada}
                    width={500}
                    height={300}
                    margin={{
                        top: 20,
                    }}
                >
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="uso" fontSize={12} />
                    <YAxis />
                    <Tooltip
                        formatter={(value) => [`${value}`]}
                    />                    
                    <Legend />
                    {tieneAdscripciones ? (

                        adscripciones.map((ads, i) => (
                            <Bar
                                key={ads}
                                dataKey={ads}
                                fill={colores[i % colores.length]}
                            />
                        ))

                    ) : (

                        <Bar
                            dataKey="total"
                            fill="#095bd6"
                        />

                    )}
                </BarChart>
            </ResponsiveContainer>
        </div>
    )
}
//IO