'use client';

/**
 * Canvas burndown — chunk lazy (ssr: false) via `next/dynamic` no pai.
 * chart.js carregado só no mount do canvas.
 */

import React, { useEffect, useRef } from 'react';

export type BurndownSprintChartProps = {
    burndown: Array<{
        data: string;
        dia: number;
        trabalho_ideal: number;
        trabalho_real: number;
    }>;
    unidade: string;
};

type ChartInstance = { destroy(): void };

export default function BurndownSprintChart({ burndown, unidade }: BurndownSprintChartProps) {
    const chartRef = useRef<HTMLCanvasElement>(null);
    const chartInstanceRef = useRef<ChartInstance | null>(null);

    useEffect(() => {
        if (burndown.length === 0 || !chartRef.current) {
            chartInstanceRef.current?.destroy();
            chartInstanceRef.current = null;
            return;
        }

        let cancelled = false;

        const run = async () => {
            const { default: Chart } = await import('chart.js/auto');
            if (cancelled || !chartRef.current) return;

            const ctx = chartRef.current.getContext('2d');
            if (!ctx) return;

            chartInstanceRef.current?.destroy();

            const labels = burndown.map((item) => {
                const date = new Date(item.data);
                return date.toLocaleDateString('pt-BR', {
                    day: '2-digit',
                    month: '2-digit',
                });
            });

            chartInstanceRef.current = new Chart(ctx, {
                type: 'line',
                data: {
                    labels,
                    datasets: [
                        {
                            label: 'Ideal',
                            data: burndown.map((item) => item.trabalho_ideal),
                            borderColor: '#95a5a6',
                            backgroundColor: 'rgba(149, 165, 166, 0.1)',
                            borderWidth: 2,
                            borderDash: [5, 5],
                            fill: false,
                            tension: 0.4,
                        },
                        {
                            label: 'Real',
                            data: burndown.map((item) => item.trabalho_real),
                            borderColor: '#3498db',
                            backgroundColor: 'rgba(52, 152, 219, 0.1)',
                            borderWidth: 2,
                            fill: false,
                            tension: 0.4,
                        },
                    ],
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                        },
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: `Trabalho Restante (${unidade})`,
                            },
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Dias da Sprint',
                            },
                        },
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false,
                    },
                },
            }) as unknown as ChartInstance;
        };

        void run();

        return () => {
            cancelled = true;
            chartInstanceRef.current?.destroy();
            chartInstanceRef.current = null;
        };
    }, [burndown, unidade]);

    return (
        <div style={{ position: 'relative', height: 400 }}>
            <canvas ref={chartRef} />
        </div>
    );
}
