"use client";
import React, { useEffect, useState } from "react";
import classNames from "classnames";
import styles from "./MetricGraph.module.css";

export interface MetricGraphProps {
    value: number;
    maxValue?: number;
    title: string;
}

export default function MetricGraph(props: MetricGraphProps) {
    const { maxValue = 100 } = props;
    const [animatedWidth, setAnimatedWidth] = useState(0);

    const isInfinite = maxValue === -1;
    const formatValueMax = (value: number) => {
        if (value === -1) {
            return "∞";
        }
        return value;
    };

    const percentage = isInfinite ? 100 : Math.min(100, (props.value / maxValue) * 100);

    let statusClass = styles.safe;
    if (isInfinite) {
        statusClass = styles.infinite;
    } else {
        if (percentage >= 100) {
            statusClass = styles.danger;
        } else if (percentage >= 80) {
            statusClass = styles.warning;
        }
    }

    useEffect(() => {
        // Trigger animation after mount
        const timer = setTimeout(() => {
            setAnimatedWidth(percentage);
        }, 100);
        return () => clearTimeout(timer);
    }, [percentage]);

    return (
        <div className={styles.card}>
            <div className={styles.header}>
                <h4 className={styles.title}>{props.title}</h4>
            </div>
            
            <div>
                <div className={styles.valueContainer}>
                    <p className={styles.value}>{props.value}</p>
                    <p className={styles.maxValue}>/ {formatValueMax(maxValue)}</p>
                </div>
                
                <div className={styles.progressContainer}>
                    <div 
                        className={classNames(styles.progressBar, statusClass)} 
                        style={{ width: `${animatedWidth}%` }}
                    />
                </div>
            </div>
        </div>
    );
}
