import React, { useContext, useEffect, useRef, useState }from 'react';
import {adjustCanvasScale, map, drawBackground} from '../function/canvasDefault';

interface Config {
    SRATE: number;
    fxmin: number;
    fxlow: number;
    fxhigh: number;
    fxmax: number;
}

interface PitchCanvasCustomProps {
    pitchValue: number | null;
    targetPitch: number[];
    ballHistory: number[];
    size: number[];
    config: Config;
    // jsonHistory: number[];
    isPlaying: boolean;
    inputValue: number,
}
// function map(value: number | null, in_min: number, in_max: number, out_min: number, out_max: number): number {
//     if (value === null) {
//         value = 0;
//     }
//     return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
// }

const PitchCanvasCustom: React.FC<PitchCanvasCustomProps> = ({ config, isPlaying, inputValue, size, pitchValue,targetPitch,ballHistory }) => {
    const { SRATE, fxmin, fxlow, fxhigh, fxmax } = config;
    const [ballY,setBallY] = useState<number>(size[0]);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const rectWidth = 5;
    const cornerRadius = 1;
    const desiredLength = Math.floor(size[1] / 5);
    // const newJsonHistory = jsonHistory.concat(Array(desiredLength - jsonHistory.length).fill(NaN));
    const newBallHistory = ballHistory.concat(Array(desiredLength - ballHistory.length).fill(NaN));
    const isPlayingRef = useRef(isPlaying);
    const [customHistory, setCustomHistory] = useState<number[]>(new Array(desiredLength).fill(NaN));
    const [colorChanges, setColorChanges] = useState<boolean[]>(new Array(desiredLength).fill(true));
    isPlayingRef.current = isPlaying; 
    const [showNotes, setShowNotes] = useState(false);

    function updateBallY(value: number | null): void {
        if (value === null) {
            value = 0;
        }
        if (value == 0) {
            setBallY(size[0]);
        } else {
            setBallY(map(value, fxmin, fxmax, size[0], -1));
        }
    }
    // function drawBackground():void {
    //     const canvas = canvasRef.current;
    //     if (canvas) {
    //         const ctx = canvas.getContext('2d');
    //         if (ctx) {
    //             var gridSpacing = 50;
    //             ctx.strokeStyle = "#e0e0e0";
    //             for (var y = gridSpacing; y < canvas.height; y += gridSpacing) {
    //                 ctx.beginPath();
    //                 ctx.moveTo(0, y);
    //                 ctx.lineTo(canvas.width, y);
    //                 ctx.stroke();
    //             }
        
    //             ctx.fillStyle = "#000";
    //             ctx.font = "12px Arial";
    //             for (var y = 0; y <= canvas.height; y += gridSpacing) {
    //                 var label = map(y, 0, canvas.height, fxmax, fxmin).toFixed(0);
    //                 ctx.fillText(label, 5, y + 12);
    //             }
    //         }
    //     }
    // }
    function roundedRect(
        ctx: CanvasRenderingContext2D, 
        x: number, 
        y: number, 
        width: number, 
        height: number, 
        radius: number
    ): void {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.arcTo(x + width, y, x + width, y + height, radius);
        ctx.arcTo(x + width, y + height, x, y + height, radius);
        ctx.arcTo(x, y + height, x, y, radius);
        ctx.arcTo(x, y, x + width, y, radius);
        ctx.closePath();
    }

    useEffect(() => { 
        if((isPlayingRef.current)) {
            
        const canvas = canvasRef.current;
        if (canvas) {
            const ctx = canvas.getContext('2d');
            if (ctx) {
                // Clear the canvas
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // Draw the background
                // drawBackground();
                drawBackground(canvasRef, fxmax, fxmin,showNotes);
    
                // Draw the ball's historical positions
                // for (var i = 0; i < newBallHistory.length; i++) {
                //     ctx.beginPath();
                //     ctx.arc(i * 5, newBallHistory[i], 5, 0, 2 * Math.PI);
                //     ctx.fillStyle = "rgba(255,0,0,0.5)";
                //     ctx.fill();
                //     ctx.closePath();
                // }
                updateBallY(pitchValue);
                ctx.beginPath();
                // ctx.arc(size[1]/2, ballY, 10, 0, 2 * Math.PI);
                // ctx.arc(ballHistory.length * 5, ballY, 10, 0, 2 * Math.PI);
                ctx.arc(size[1]/2, ballY, 10, 0, 2 * Math.PI);
                ctx.fillStyle = "black";
                ctx.fill();
                ctx.closePath();
    
                // Draw json data

                for (let i = 0; i < customHistory.length; i++) {
                    ctx.beginPath();
                    const mappedJsonValue = map(customHistory[i], fxmin, fxmax, size[0], 0);
                    if (colorChanges[i]) {
                        ctx.fillStyle = "green";
                    } else {
                        ctx.fillStyle = "rgba(0,255,255,0.5)";
                    }
                
                    ctx.fillRect(canvas.width - i * rectWidth, mappedJsonValue, rectWidth, rectWidth);
                    ctx.fill();
                    ctx.closePath();
                }
                ctx.stroke();
            }
        }
        }    
    }, [ballHistory, customHistory, isPlaying]);

    useEffect(() => {
        const intervalId = setInterval(() => {
            if(isPlaying) {
                let updatedHistory = [...customHistory];
                updatedHistory.pop();  // Remove the first element
                updatedHistory.unshift(inputValue);  // Add the new inputValue at the end
                setCustomHistory(updatedHistory);

                let updatedColor = [...colorChanges];
                const mappedJsonValue = map(customHistory[Math.floor(customHistory.length/2)], fxmin, fxmax, size[0], 0);
                const difference = Math.abs(mappedJsonValue - ballY);
                if (difference <= 30 && !isNaN(difference)) {
                    updatedColor[desiredLength/2] = true;
                } else {
                    updatedColor[desiredLength/2] = false;
                }
                updatedColor.pop();
                updatedColor.unshift(false);
                setColorChanges(updatedColor);

            }
        }, 15);
    
        return () => clearInterval(intervalId);
    }, [customHistory, inputValue, isPlaying]);
    

    // first
    useEffect(() => {
        drawBackground(canvasRef, fxmax, fxmin,showNotes);
    },[]);
    const toggleShowNotes = () => {
        setShowNotes(!showNotes); 
        const canvas = canvasRef.current;
        if (canvas && canvas.getContext) {
            const ctx = canvas.getContext('2d');
            if (ctx) {
              // 清除画布
              ctx.clearRect(0, 0, canvas.width, canvas.height);
              // 立即调用drawBackground来重绘背景和标签
              drawBackground(canvasRef, fxmax, fxmin, !showNotes);
            }
          }
    }
    useEffect(() => {
        drawBackground(canvasRef, fxmax, fxmin, showNotes); // 确保在状态变化时重新绘制背景
      }, [showNotes]); 

    return (
        <canvas ref={canvasRef}  onClick={toggleShowNotes} id="pitchCanvas" width="1000" height="500" style={{border: '1px solid #000'}}></canvas>
    );
}

export default PitchCanvasCustom;
