"use client";

import { useEffect, useState } from "react";

export type GaugeCircularProps = {
  color?: string;
  bgColor?: string;
  percent: number;
};

const SIZE = 40;

const RADIUS = 15;
const STROKE_WIDTH = 6;
const CIRCUMFERENCE = RADIUS * 2 * Math.PI;

export const GaugeCircular: React.FC<GaugeCircularProps> = ({
  color,
  bgColor,
  percent,
}) => {
  // Use a useState to update the value after first display to always animate
  const [displayedValue, setDisplayedValue] = useState(0);

  useEffect(() => {
    setDisplayedValue(percent);
  }, [setDisplayedValue, percent]);

  return (
    <svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`}>
      <circle
        cx={SIZE / 2}
        cy={SIZE / 2}
        stroke={bgColor ?? "#13141c"}
        fill="none"
        r={RADIUS}
        strokeWidth={6}
      />
      <circle
        className="transition-[stroke-dasharray] duration-[2000ms]"
        cx={SIZE / 2}
        cy={SIZE / 2}
        stroke={color ?? "#12b981"}
        fill="none"
        transform="scale(-1 1) translate(-40 0) rotate(270, 20, 20)"
        r={RADIUS}
        strokeDasharray={`${(displayedValue / 100) * CIRCUMFERENCE} 1000`}
        strokeWidth={STROKE_WIDTH}
        strokeLinecap="round"
      />
    </svg>
  );
};
