"use client";

import { useEffect, useState } from "react";

export type GaugeHorizontalProps = {
  className?: string;
  color?: string;
  bgColor?: string;
  strokeWidth?: number;
  length?: number;
  percent: number;
};

const LENGTH = 40;

const STROKE_WIDTH = 6;

export const GaugeHorizontal: React.FC<GaugeHorizontalProps> = ({
  className,
  color,
  bgColor,
  strokeWidth = STROKE_WIDTH,
  length = LENGTH,
  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 (
    <div className={`${className ?? ""} w-[${length + strokeWidth}px]`}>
      <svg
        className="relative z-0"
        width={length + strokeWidth}
        height={strokeWidth}
        viewBox={`0 0 ${length} ${strokeWidth}`}
      >
        <line
          className={`${bgColor?.includes("#") ? "" : bgColor ?? "stroke-neutral-200"}`}
          x1={0}
          y1={strokeWidth / 2}
          x2={length}
          y2={strokeWidth / 2}
          fill="none"
          stroke={`${bgColor?.includes("#") ? bgColor : ""}`}
          strokeWidth={strokeWidth}
          strokeLinecap="round"
        />
        {percent && (
          <line
            className={`${color?.includes("#") ? "" : color ?? "stroke-primary-500"}`}
            x1={0}
            y1={strokeWidth / 2}
            x2={
              displayedValue - 1
                ? strokeWidth / 2 +
                  ((displayedValue - 1) / 99) * (length - strokeWidth / 2)
                : 0
            }
            y2={strokeWidth / 2}
            fill="none"
            stroke={`${color?.includes("#") ? color : ""}`}
            strokeWidth={strokeWidth}
            strokeLinecap="round"
          />
        )}
      </svg>
    </div>
  );
};
