import React from 'react';
import { Box, Typography, styled } from '@mui/material';

interface GaugeCardMUIProps {
  title: string;
  subtitle: string;
  value: string | number;
  subValue: string;
  percentage: number;
  maxPercentage?: number;
  color: string;
  gradientColors: {
    start: string;
    middle?: string;
    end: string;
  };
}

const StyledCard = styled(Box)(({ theme }) => ({
  position: 'relative',
  background: 'linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(15, 23, 42, 0.98) 100%)',
  borderRadius: '20px',
  padding: '24px',
  border: '1px solid rgba(71, 85, 105, 0.5)',
  boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.05)',
  backdropFilter: 'blur(8px)',
  minWidth: '240px',
  transition: 'all 0.3s ease',
  '&:hover': {
    transform: 'translateY(-4px)',
    boxShadow: '0 12px 48px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.08)',
  },
}));

const GaugeCardMUI: React.FC<GaugeCardMUIProps> = ({
  title,
  subtitle,
  value,
  subValue,
  percentage,
  maxPercentage = 100,
  color,
  gradientColors,
}) => {
  // 게이지는 -135도에서 시작해서 135도까지 (총 270도)
  const startAngle = -135;
  const endAngle = 135;
  const totalAngle = endAngle - startAngle;
  
  // 현재 값에 따른 각도 계산
  const currentAngle = startAngle + (percentage / maxPercentage) * totalAngle;
  
  // SVG 경로 생성 함수
  const polarToCartesian = (centerX: number, centerY: number, radius: number, angleInDegrees: number) => {
    const angleInRadians = (angleInDegrees * Math.PI) / 180.0;
    return {
      x: centerX + radius * Math.cos(angleInRadians),
      y: centerY + radius * Math.sin(angleInRadians),
    };
  };

  const describeArc = (x: number, y: number, radius: number, startAngle: number, endAngle: number) => {
    const start = polarToCartesian(x, y, radius, endAngle);
    const end = polarToCartesian(x, y, radius, startAngle);
    const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';
    return [
      'M', start.x, start.y,
      'A', radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(' ');
  };

  const centerX = 100;
  const centerY = 100;
  const radius = 75;
  const trackRadius = 75;

  // 바늘 끝점 계산
  const needleLength = 60;
  const needleAngleRad = (currentAngle * Math.PI) / 180;
  const needleEndX = centerX + needleLength * Math.cos(needleAngleRad);
  const needleEndY = centerY + needleLength * Math.sin(needleAngleRad);

  const gradientId = `gradient-${title.replace(/\s+/g, '-')}`;
  const glowId = `glow-${title.replace(/\s+/g, '-')}`;

  return (
    <StyledCard>
      {/* SVG 게이지 */}
      <Box sx={{ display: 'flex', justifyContent: 'center', mb: 1, position: 'relative' }}>
        <svg width="180" height="180" viewBox="0 0 200 200" style={{ overflow: 'visible' }}>
          <defs>
            {/* 게이지 그라데이션 */}
            <linearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" style={{ stopColor: gradientColors.start, stopOpacity: 1 }} />
              {gradientColors.middle && (
                <stop offset="50%" style={{ stopColor: gradientColors.middle, stopOpacity: 1 }} />
              )}
              <stop offset="100%" style={{ stopColor: gradientColors.end, stopOpacity: 1 }} />
            </linearGradient>
            
            {/* 글로우 효과 */}
            <filter id={glowId}>
              <feGaussianBlur stdDeviation="4" result="coloredBlur"/>
              <feMerge>
                <feMergeNode in="coloredBlur"/>
                <feMergeNode in="SourceGraphic"/>
              </feMerge>
            </filter>
            
            {/* 배경 그라데이션 */}
            <radialGradient id="radial-bg">
              <stop offset="0%" stopColor="rgba(30, 41, 59, 0.8)" />
              <stop offset="100%" stopColor="rgba(15, 23, 42, 0.9)" />
            </radialGradient>
          </defs>

          {/* 외부 원 테두리 */}
          <circle
            cx={centerX}
            cy={centerY}
            r={85}
            fill="none"
            stroke="rgba(71, 85, 105, 0.3)"
            strokeWidth="1"
          />

          {/* 내부 배경 원 */}
          <circle
            cx={centerX}
            cy={centerY}
            r={78}
            fill="url(#radial-bg)"
            opacity="0.4"
          />

          {/* 게이지 트랙 (배경) */}
          <path
            d={describeArc(centerX, centerY, trackRadius, startAngle, endAngle)}
            fill="none"
            stroke="rgba(71, 85, 105, 0.2)"
            strokeWidth="12"
            strokeLinecap="round"
          />

          {/* 게이지 진행 바 - 배경 글로우 (가장 바깥쪽) */}
          <path
            d={describeArc(centerX, centerY, radius, startAngle, currentAngle)}
            fill="none"
            stroke={color}
            strokeWidth="16"
            strokeLinecap="round"
            opacity="0.15"
            style={{
              transition: 'all 1s ease-out',
              filter: 'blur(8px)',
            }}
          />

          {/* 게이지 진행 바 - 중간 글로우 */}
          <path
            d={describeArc(centerX, centerY, radius, startAngle, currentAngle)}
            fill="none"
            stroke={color}
            strokeWidth="14"
            strokeLinecap="round"
            opacity="0.3"
            style={{
              transition: 'all 1s ease-out',
              filter: 'blur(4px)',
            }}
          />

          {/* 게이지 진행 바 - 메인 */}
          <path
            d={describeArc(centerX, centerY, radius, startAngle, currentAngle)}
            fill="none"
            stroke={`url(#${gradientId})`}
            strokeWidth="12"
            strokeLinecap="round"
            style={{
              transition: 'all 1s ease-out',
            }}
          />

          {/* 바늘 그림자 */}
          <line
            x1={centerX}
            y1={centerY}
            x2={needleEndX + 1}
            y2={needleEndY + 1}
            stroke="rgba(0, 0, 0, 0.4)"
            strokeWidth="3"
            strokeLinecap="round"
            style={{
              transition: 'all 1s ease-out',
            }}
          />

          {/* 바늘 */}
          <line
            x1={centerX}
            y1={centerY}
            x2={needleEndX}
            y2={needleEndY}
            stroke="rgba(255, 255, 255, 0.95)"
            strokeWidth="2.5"
            strokeLinecap="round"
            filter={`url(#${glowId})`}
            style={{
              transition: 'all 1s ease-out',
            }}
          />

          {/* 바늘 중심점 외곽 그림자 */}
          <circle
            cx={centerX}
            cy={centerY}
            r="7"
            fill="rgba(0, 0, 0, 0.3)"
          />

          {/* 바늘 중심점 */}
          <circle
            cx={centerX}
            cy={centerY}
            r="6"
            fill={color}
            stroke="rgba(255, 255, 255, 0.9)"
            strokeWidth="1.5"
            filter={`url(#${glowId})`}
          />

          {/* 바늘 중심점 하이라이트 */}
          <circle
            cx={centerX - 1.5}
            cy={centerY - 1.5}
            r="2.5"
            fill="rgba(255, 255, 255, 0.6)"
          />

          {/* 내부 어두운 원 */}
          <circle
            cx={centerX}
            cy={centerY}
            r={62}
            fill="rgba(15, 23, 42, 0.95)"
            stroke="rgba(71, 85, 105, 0.2)"
            strokeWidth="0.5"
          />
        </svg>
        
        {/* 중앙 값 표시 - SVG 위에 오버레이 */}
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            textAlign: 'center',
            pointerEvents: 'none',
            zIndex: 10,
          }}
        >
          <Typography
            sx={{
              fontSize: '2rem',
              fontWeight: 700,
              color: '#fff',
              lineHeight: 1,
              letterSpacing: '-0.5px',
              textShadow: `0 0 20px ${color}, 0 0 40px ${color}40`,
              fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
            }}
          >
            {value}
          </Typography>
          <Typography
            sx={{
              fontSize: '0.8rem',
              fontWeight: 600,
              color: color,
              mt: 0.75,
              textShadow: `0 0 10px ${color}`,
            }}
          >
            {percentage.toFixed(percentage < 10 ? 2 : 1)}%
          </Typography>
        </Box>
      </Box>

      {/* 하단 라벨 */}
      <Box sx={{ textAlign: 'center', mt: 1 }}>
        <Typography
          sx={{
            fontSize: '0.95rem',
            fontWeight: 600,
            color: '#fff',
            mb: 0.5,
            lineHeight: 1.3,
          }}
        >
          {title}
        </Typography>
        <Typography
          sx={{
            fontSize: '0.7rem',
            color: 'rgba(148, 163, 184, 0.8)',
          }}
        >
          {subtitle}
        </Typography>
      </Box>
    </StyledCard>
  );
};

export default GaugeCardMUI;
