import React, { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";
import { Chart as ChartJS, LineElement, CategoryScale, LinearScale, PointElement } from "chart.js";
import { PowerIcon, ProductionCapacityIcon } from "../../icons/analysis";
import SkeletonUI from "../../templates/SkeletonUI";
import { useInputValues, useMachineUptime, useProductionCapacityData, useThroughPutData } from "../../../store/builder/store";

ChartJS.register(LineElement, CategoryScale, LinearScale, PointElement);

const ThroughputSummary: React.FC = () => {
    // Define all data internally within the component
    const timeRange = {
        startTime: "08:00 AM",
        endTime: "06:00 PM",
    };

    const { machineActiveTime } = useMachineUptime();
    const energyConsumption = {
        energyConsumed: 456,
        unit: "KWH",
    };

    // Dynamic shift data
    const shiftUtilization = [
        { shift: 1, percentage: 30, color: "#F3C64D" },
        { shift: 2, percentage: 40, color: "#67B3F4" },
        { shift: 3, percentage: 30, color: "#7981F5" },
    ];

    const { productionCapacityData } = useProductionCapacityData();
    const { throughputData: data } = useThroughPutData();

    const chartOptions = {
        responsive: true,
        scales: {
            x: {
                display: false, // hide X axis completely
            },
            y: {
                display: false, // hide Y axis completely
                min: 0, // force Y axis to start at 0
            },
        },
        plugins: {
            legend: {
                display: false,
            },
            tooltip: {
                enabled: true,
            },
        },
    };

    const assetUsage = 85;

    // machineActiveTime => Throughput
    // shiftUtilization.length => Shifts per day
    // 8 => Shift length
    // assetUsage => Yield rate

    const throughtputMachineData = machineActiveTime * shiftUtilization.length * 8;

    const throughputData = {
        labels: ["08:00", "08:10", "08:20", "08:30", "08:40", "08:50"],
        data: [5, 10, 8, 10, 12, 10],
        totalThroughput: (throughtputMachineData * assetUsage) / 100,
        assetUsage: assetUsage,
    };

    const { inputValues } = useInputValues();
    // Chart data configuration
    const chartData = {
        labels: throughputData.labels,
        datasets: [
            {
                label: "Units/hour",
                data: throughputData.data,
                borderColor: "#B392F0",
                tension: 0.4,
                pointRadius: 0, // Hide points
            },
        ],
    };

    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        //
        if (productionCapacityData > 0) {
            setTimeout(() => {
                setIsLoading(false);
            }, 3000);
        } else {
            setIsLoading(true);
        }
    }, [productionCapacityData]);

    return (
        <>
            {!isLoading && (
                <div className="production analysis-card">
                    <div className="production-wrapper analysis-card-wrapper">
                        <div className="card-header">
                            <div className="header">
                                <div className="main-header">Production Capacity</div>
                                <div className="sub-header">
                                    {timeRange.startTime} - {timeRange.endTime}
                                </div>
                            </div>
                            <div className="icon-wrapper">
                                <ProductionCapacityIcon />
                            </div>
                        </div>

                        {!isLoading ? (
                            <>
                                <div className="process-container">
                                    <div className="throughput-value">
                                        <span className="value">{productionCapacityData}</span> Units/Month
                                    </div>
                                    <div className="lineChart">
                                        <div className="assetUsage">
                                            <div className="key">Asset usage</div>
                                            <div className="value">{parseFloat(inputValues["Yield rate"])}%</div>
                                        </div>
                                        <Line data={chartData} options={chartOptions} />
                                    </div>
                                </div>

                                <div className="footer">
                                    <div className="energyConsumption footer-card">
                                        <div className="header">Energy Consumption</div>
                                        <div className="value-container">
                                            <div className="energy-icon">
                                                <PowerIcon />
                                            </div>
                                            <div className="value-wrapper">
                                                <div className="value">{energyConsumption.energyConsumed}</div>
                                                <div className="unit">{energyConsumption.unit}</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="shiftUtilization footer-card">
                                        <div className="header">Shift Utilization</div>
                                        <div className="value-container">
                                            <div className="value">{throughputData.assetUsage}%</div>

                                            <div className="progress-wrapper">
                                                {/* Dynamically create progress bars based on shiftUtilization array */}
                                                {shiftUtilization.map((shift, index) => (
                                                    <div
                                                        key={shift.shift}
                                                        className={`progress shift-${shift.shift}`}
                                                        style={{
                                                            width: `${shift.percentage}%`,
                                                            backgroundColor: shift.color,
                                                        }}
                                                    ></div>
                                                ))}
                                            </div>

                                            <div className="progress-indicator">
                                                {/* Dynamically create shift indicators with random colors */}
                                                {shiftUtilization.map((shift, index) => (
                                                    <div className="shift-wrapper" key={shift.shift}>
                                                        <span
                                                            className={`indicator shift-${shift.shift}`}
                                                            style={{ backgroundColor: shift.color }} // Random color for indicator
                                                        ></span>
                                                        <label>Shift {shift.shift}</label>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </>
                        ) : (
                            <SkeletonUI type={"default"} />
                        )}
                    </div>
                </div>
            )}
        </>
    );
};

export default ThroughputSummary;
