"use client";
import { useRef, useEffect, useState } from 'react';
import styles from "./style.module.scss";

const Lottery = () => {
  const canvasRef = useRef<any>(null);
  const [isSpinning, setIsSpinning] = useState(false);
  const [prize, setPrize] = useState('');
  const segments = ['一等奖', '二等奖', '三等奖', '四等奖', '五等奖', '六等奖', '七等奖', '八等奖'];
  const segmentAngle = (2 * Math.PI) / segments.length;

  const drawWheel = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const radius = canvas.width / 2;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(radius, radius);

    segments.forEach((segment, index) => {
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.arc(0, 0, radius, index * segmentAngle, (index + 1) * segmentAngle);
      ctx.closePath();
      // ctx.fillStyle = `hsl(${index * 360 / segments.length}, 70%, 50%)`;
      ctx.fill();
      ctx.stroke();

      ctx.save();
      ctx.rotate((index + 0.5) * segmentAngle);
      ctx.fillStyle = '#fff';
      ctx.fillText(segment, radius / 2, 0);
      ctx.restore();
    });

    ctx.restore();
  };

  const spinWheel = () => {
    if (isSpinning) return;

    setIsSpinning(true);
    let rotation = 0;
    const spinDuration = 5000; // 旋转持续时间
    const stopAngle = Math.floor(Math.random() * segments.length) * (360 / segments.length) + 360 * 5; // 随机停下的角度
    const startAngle = rotation;

    const spinAnimation = (timestamp:any) => {
      rotation += 10; // 每次增加的角度
      canvasRef.current.style.transform = `rotate(${rotation}deg)`;

      if (rotation < stopAngle) {
        requestAnimationFrame(spinAnimation);
      } else {
        setIsSpinning(false);
        const winningSegment = Math.floor(((stopAngle % 360) / (360 / segments.length)));
        setPrize(segments[winningSegment]);
      }
    };

    requestAnimationFrame(spinAnimation);
  };

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

  return (
    <>
      <img src="/wheel/draw.png" className={`${styles.drawImg} ${styles.position}`} onClick={spinWheel}/>
      <div className={styles.drawContents}>
        <canvas ref={canvasRef} id={styles.draw} width={306} height={306} />
      </div>
      
      {/* <button onClick={spinWheel} disabled={isSpinning}>
        {isSpinning ? '正在抽奖...' : '抽奖'}
      </button> */}
      {/* {prize && <h2>恭喜您，中奖：{prize}</h2>} */}
    </>
  );
};

export default Lottery;
