import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
import { ConfigContext } from "../../Context/ConfigContext";
import ReactECharts from 'echarts-for-react';
import { useNavigate } from "react-router-dom";
import Swal from "sweetalert2";

const TaskManagement = () => {
    const { apiURL, apiHeaderJson } = useContext(ConfigContext);
    const [counts, setCounts] = useState({ pending: 0, completed: 0, total: 0 });
    const [statusData, setStatusData] = useState([]);
    const [loading, setLoading] = useState(true);
    const navigate = useNavigate();

    useEffect(() => {
        getDashboard();
    }, []);

    const getDashboard = async () => {
        try {
            setLoading(true);
            const headers = apiHeaderJson;
            const response = await axios.get(`${apiURL}api/GetDashboard`, { headers });
            const { inprocess_tasks, completed_tasks } = response.data.data;

            const total = inprocess_tasks + completed_tasks;

            setCounts({
                pending: inprocess_tasks,
                completed: completed_tasks,
                total: total
            });

            const statusArray = [
                { name: "Pending", value: inprocess_tasks },
                { name: "Completed", value: completed_tasks }
            ];
            setStatusData(statusArray);

        } catch (error) {
            console.log(error);
            Swal.fire({
                icon: "error",
                title: "Error",
                text: "Failed to load dashboard data.",
            });
        } finally {
            setLoading(false);
        }
    };

    const getOption = () => {
        return {
            tooltip: { trigger: "item" },
            legend: {
                orient: "horizontal",
                bottom: 0,
                textStyle: { fontSize: 12 }
            },
            series: [
                {
                    name: "Task Status",
                    type: "pie",
                    radius: "60%",
                    data: statusData,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: "rgba(0, 0, 0, 0.3)"
                        }
                    },
                    label: {
                        formatter: "{b}: {c}",
                        fontSize: 12
                    }
                }
            ],
            // Bootstrap warning + success
            color: ["#FFC107", "#93C47D"]
        };
    };

    const handleNavigate = (statusValue) => {
        navigate(`/TaskList/${statusValue}`);
    };

    const onChartClick = (params) => {
        if (params.name === "Pending") handleNavigate("1");
        if (params.name === "Completed") handleNavigate("2");
    };

    const onEvents = { click: onChartClick };

    return (
        <div className="col-xl-12">
            <div className="card shadow-sm">
                <div className="card-header d-flex justify-content-between align-items-center">
                    <h5 className="card-title mb-0">Task Status Overview</h5>
                    <small className="text-muted">Total: {counts.total}</small>
                </div>

                <div className="card-body">
                    {loading ? (
                        <div className="text-center py-5">
                            <div className="spinner-border text-primary" role="status">
                                <span className="visually-hidden">Loading...</span>
                            </div>
                            <p className="mt-3 text-muted">Loading task status...</p>
                        </div>
                    ) : (
                        <div className="row align-items-center">

                            <div className="col-12 col-md-5 mb-4 mb-md-0 d-flex justify-content-center">
                                <ReactECharts
                                    option={getOption()}
                                    style={{ height: '280px', width: '100%' }}
                                    onEvents={onEvents}
                                />
                            </div>

                            <div className="col-12 col-md-7">
                                <div className="row g-3">

                                    <div className="col-6">
                                        <div
                                            className="p-3 rounded shadow-sm text-center cursor-pointer h-100"
                                            onClick={() => handleNavigate("1")}
                                            style={{
                                                background: "#FFF3CD",
                                                border: "1px solid #FFEEA8"
                                            }}
                                        >
                                            <div className="fw-bold text-warning">Pending</div>
                                            <div className="fs-3">{counts.pending}</div>
                                        </div>
                                    </div>

                                    <div className="col-6">
                                        <div
                                            className="p-3 rounded shadow-sm text-center cursor-pointer h-100"
                                            onClick={() => handleNavigate("2")}
                                            style={{
                                                background: "#E9F6EA",
                                                border: "1px solid #B7E1C1"
                                            }}
                                        >
                                            <div className="fw-bold text-success">Completed</div>
                                            <div className="fs-3">{counts.completed}</div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                        </div>
                    )}
                </div>

                <div className="card-footer text-muted small">
                    Click on a status card or chart segment to view tasks
                </div>
            </div>
        </div>
    );
};

export default TaskManagement;
