import { useContext, useEffect, useState } from 'react'
import { ConfigContext } from '../Context/ConfigContext'
import axios from 'axios'
import ReactECharts from 'echarts-for-react'

const ProgressPieChart = ({ project_id }) => {

    const { apiHeaderJson, apiURL } = useContext(ConfigContext)
    const headers = apiHeaderJson

    const [progress, setProgress] = useState({})
    const [loading, setLoading] = useState(false)

    const getProgressData = async () => {
        try {
            setLoading(true)
            const response = await axios.get(`${apiURL}api/project/information`, {
                headers,
                params: { project_id }
            })
            const { success, data } = response.data

            if (success) {
                setProgress(data?.progress)
            }
        } catch (error) {
            console.error("Error getting progress", error)
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        if (project_id) {
            getProgressData();
        }
    }, [project_id])

    const chartOption = {
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 800,

        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            bottom: '1%',
            left: 'center'
        },
        color: ['#6f42c1', '#20c997'],
        series: [
            {
                name: 'Project Progress',
                type: 'pie',
                radius: '70%',
                roseType: false,

                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: (idx) => idx * 100,

                label: {
                    show: true,
                    formatter: '{b}: {c}'
                },

                data: [
                    { value: progress?.TotalUsed || 0, name: 'Items Used' },
                    { value: progress?.TotalWork || 0, name: 'Work Remaining' }
                ]
            }
        ]
    }

    return (
        <div style={{ height: "312px", width: "100%" }}>
            {loading ? (
                <div className="text-center">Loading...</div>
            ) : (
                <ReactECharts option={chartOption} style={{ height: "100%", width: "100%" }} />
            )}
        </div>
    )
}

export default ProgressPieChart
