/**
 * LoadingAmount Component
 *
 * Displays amount with skeleton loading state during currency switch.
 * Only shows skeleton when isRateLoading is true (currency switch scenario).
 */

import { Skeleton, Typography } from '@mui/material';
import type { SxProps, Theme } from '@mui/material';
import { useEffect, useRef, useState } from 'react';

export interface LoadingAmountProps {
  value: string;
  loading?: boolean;
  skeletonWidth?: number;
  height?: number;
  sx?: SxProps<Theme>;
  animateValueChange?: boolean;
  transitionDuration?: number;
}

export default function LoadingAmount({
  value,
  loading = false,
  skeletonWidth = 80,
  height = 24,
  sx = {},
  animateValueChange = false,
  transitionDuration = 300,
}: LoadingAmountProps) {
  const [displayValue, setDisplayValue] = useState(value);
  const [isTransitioning, setIsTransitioning] = useState(false);
  const prevValueRef = useRef(value);

  useEffect(() => {
    if (value !== prevValueRef.current) {
      prevValueRef.current = value;
      if (animateValueChange && !loading) {
        setIsTransitioning(true);
        const timer = setTimeout(() => {
          setDisplayValue(value);
          setIsTransitioning(false);
        }, transitionDuration / 2);
        return () => clearTimeout(timer);
      }
      setDisplayValue(value);
    }
    return undefined;
  }, [value, loading, animateValueChange, transitionDuration]);

  if (loading) {
    return <Skeleton variant="text" width={skeletonWidth} height={height} />;
  }

  return (
    <Typography
      component="span"
      sx={{
        ...sx,
        opacity: isTransitioning ? 0 : 1,
        transition: animateValueChange ? `opacity ${transitionDuration / 2}ms ease-in-out` : undefined,
      }}>
      {displayValue}
    </Typography>
  );
}
