import { useEffect, useState, useRef } from 'react';

interface Props {
  isSpeaking: boolean;
  isListening: boolean;
  outfit: string;
  accessory: string | null;
  onTalkToggle: () => void;
}

export default function AnimatedAvatar({ isSpeaking, isListening, outfit, accessory, onTalkToggle }: Props) {
  const [blink, setBlink] = useState(false);
  const [wave, setWave] = useState(false);
  const [lookX, setLookX] = useState(0);
  const [lookY, setLookY] = useState(0);
  const idleRef = useRef<ReturnType<typeof setInterval> | null>(null);

  // Blink cycle
  useEffect(() => {
    const blinkCycle = () => {
      setBlink(true);
      setTimeout(() => setBlink(false), 150);
    };
    const id = setInterval(blinkCycle, 2500 + Math.random() * 2000);
    return () => clearInterval(id);
  }, []);

  // Gentle idle eye movement
  useEffect(() => {
    idleRef.current = setInterval(() => {
      setLookX(Math.sin(Date.now() / 3000) * 3);
      setLookY(Math.sin(Date.now() / 4000) * 2);
    }, 100);
    return () => clearInterval(idleRef.current ?? undefined);
  }, []);

  // Wave gesture on toggle
  const handleTalk = () => {
    setWave(true);
    setTimeout(() => setWave(false), 600);
    onTalkToggle();
  };

  // Outfit colors
  const outfitColors: Record<string, { top: string; accent: string; skirt: string }> = {
    'cozy-hoodie': { top: '#FFB6C1', accent: '#FF69B4', skirt: '#FFB6C1' },
    'girly-dress': { top: '#D8B4FE', accent: '#A855F7', skirt: '#E9D5FF' },
    'pajama-set':  { top: '#A7F3D0', accent: '#34D399', skirt: '#6EE7B7' },
    'study-sweater': { top: '#FED7AA', accent: '#F97316', skirt: '#FED7AA' },
    'going-out':   { top: '#FBCFE8', accent: '#EC4899', skirt: '#FBCFE8' },
  };
  const colors = outfitColors[outfit] || outfitColors['cozy-hoodie'];

  return (
    <div className="flex flex-col items-center">
      {/* Avatar canvas area */}
      <div className="relative w-36 h-44">
        <svg viewBox="0 0 120 160" className="w-full h-full">
          {/* Hair back layer */}
          <ellipse cx="60" cy="55" rx="32" ry="38" fill="#2D1B69" />

          {/* Body / Outfit */}
          <ellipse cx="60" cy="110" rx="28" ry="35" fill={colors.top} />
          <path d="M32 110 Q60 135 88 110" fill={colors.skirt} opacity={0.7} />
          {/* Collar */}
          <path d="M48 85 Q60 92 72 85" fill={colors.accent} opacity={0.6} />

          {/* Arms */}
          <g className={wave ? 'arm-wave' : ''}>
            {/* Left arm */}
            <ellipse cx="28" cy="98" rx="8" ry="20" fill="#FDBCB4" transform="rotate(10, 28, 98)" />
            {/* Right arm */}
            <ellipse cx="92" cy="98" rx="8" ry="20" fill="#FDBCB4" transform="rotate(-10, 92, 98)" className={wave ? 'wave-arm' : ''} />
          </g>

          {/* Neck */}
          <rect x="54" y="78" width="12" height="12" rx="6" fill="#FDBCB4" />

          {/* Head */}
          <ellipse cx="60" cy="52" rx="30" ry="32" fill="#FDBCB4" />

          {/* Cheeks */}
          <ellipse cx="38" cy="60" rx="6" ry="4" fill="#FFB6C1" opacity={0.5} />
          <ellipse cx="82" cy="60" rx="6" ry="4" fill="#FFB6C1" opacity={0.5} />

          {/* Hair front */}
          <path d="M30 45 Q30 25 45 18 Q55 14 60 15 Q65 14 75 18 Q90 25 90 45 Q90 30 82 22 Q70 14 60 12 Q50 14 38 22 Q30 30 30 45Z" fill="#3D1F8A" />
          {/* Hair bangs */}
          <path d="M30 42 Q35 30 50 28 Q60 27 70 28 Q85 30 90 42 Q88 35 78 32 Q65 28 60 28 Q55 28 42 32 Q32 35 30 42Z" fill="#4B2C9B" />

          {/* Hair side strands */}
          <path d="M30 45 Q28 60 26 80 Q24 88 28 90" fill="none" stroke="#2D1B69" strokeWidth="3" strokeLinecap="round" />
          <path d="M90 45 Q92 60 94 80 Q96 88 92 90" fill="none" stroke="#2D1B69" strokeWidth="3" strokeLinecap="round" />

          {/* Eyes */}
          <g transform={`translate(${lookX}, ${lookY})`}>
            {/* Left eye */}
            <ellipse cx="46" cy="50" rx="6" ry="7" fill="white" />
            {/* Right eye */}
            <ellipse cx="74" cy="50" rx="6" ry="7" fill="white" />

            {blink ? (
              <>
                <line x1="40" y1="50" x2="52" y2="50" stroke="#4A1942" strokeWidth="2.5" strokeLinecap="round" />
                <line x1="68" y1="50" x2="80" y2="50" stroke="#4A1942" strokeWidth="2.5" strokeLinecap="round" />
              </>
            ) : (
              <>
                {/* Pupils */}
                <circle cx="47" cy="50" r="3.5" fill="#4A1942" />
                <circle cx="75" cy="50" r="3.5" fill="#4A1942" />
                {/* Highlights */}
                <circle cx="48.5" cy="48.5" r="1.5" fill="white" />
                <circle cx="76.5" cy="48.5" r="1.5" fill="white" />
              </>
            )}
          </g>

          {/* Eyebrows */}
          <path d="M38 42 Q46 39 54 42" fill="none" stroke="#2D1B69" strokeWidth="1.5" strokeLinecap="round" />
          <path d="M66 42 Q74 39 82 42" fill="none" stroke="#2D1B69" strokeWidth="1.5" strokeLinecap="round" />

          {/* Mouth */}
          {isSpeaking ? (
            <ellipse cx="60" cy="65" rx="5" ry="4" fill="#E75480" className="mouth-talk" />
          ) : (
            <path d="M55 65 Q60 69 65 65" fill="none" stroke="#E75480" strokeWidth="2" strokeLinecap="round" />
          )}

          {/* Accessory */}
          {accessory === 'bow' && (
            <g>
              <path d="M52 28 Q48 22 52 18 Q56 22 52 28Z" fill="#FF69B4" />
              <path d="M52 28 Q56 22 52 18 Q48 22 52 28Z" fill="#FF69B4" />
              <circle cx="52" cy="23" r="2" fill="#FF1493" />
            </g>
          )}
          {accessory === 'flower-crown' && (
            <g>
              {[48, 54, 60, 66, 72].map((x, i) => (
                <circle key={i} cx={x} cy="20" r="3" fill={i % 2 === 0 ? '#FFB6C1' : '#D8B4FE'} />
              ))}
            </g>
          )}
          {accessory === 'star-earrings' && (
            <>
              <polygon points="28,58 29,55 30,58 33,58 31,60 32,63 29,61 26,63 27,60 25,58" fill="#FDE68A" />
              <polygon points="92,58 93,55 94,58 97,58 95,60 96,63 93,61 90,63 91,60 89,58" fill="#FDE68A" />
            </>
          )}
          {accessory === 'glasses' && (
            <g stroke="#D8B4FE" strokeWidth="1.5" fill="none" opacity={0.7}>
              <circle cx="46" cy="50" r="8" />
              <circle cx="74" cy="50" r="8" />
              <line x1="54" y1="50" x2="66" y2="50" />
              <line x1="38" y1="50" x2="34" y2="48" />
              <line x1="82" y1="50" x2="86" y2="48" />
            </g>
          )}
          {accessory === 'scarf' && (
            <path d="M44 78 Q60 84 76 78 Q74 86 60 90 Q46 86 44 78Z" fill="#FBCFE8" stroke="#F9A8D4" strokeWidth="1" />
          )}

          {/* Speaking indicator - thought dots */}
          {isSpeaking && (
            <g opacity={0.4}>
              <circle cx="30" cy="40" r="2" fill="#D8B4FE">
                <animate attributeName="opacity" values="0.3;1;0.3" dur="1s" repeatCount="indefinite" />
              </circle>
              <circle cx="25" cy="35" r="1.5" fill="#D8B4FE">
                <animate attributeName="opacity" values="1;0.3;1" dur="1s" repeatCount="indefinite" />
              </circle>
            </g>
          )}

          {/* Listening glow */}
          {isListening && (
            <circle cx="60" cy="52" r="40" fill="none" stroke="#D8B4FE" strokeWidth="1" opacity={0.4}>
              <animate attributeName="r" values="40;44;40" dur="1.5s" repeatCount="indefinite" />
              <animate attributeName="opacity" values="0.4;0.1;0.4" dur="1.5s" repeatCount="indefinite" />
            </circle>
          )}
        </svg>
      </div>

      {/* Talk button */}
      <button
        onClick={handleTalk}
        className={`mt-2 flex items-center gap-2 px-5 py-2 rounded-full text-sm font-bold transition-all ${
          isListening
            ? 'bg-red-400 text-white shadow-lg scale-105 animate-listening-pulse'
            : 'bg-gradient-to-r from-kira-pink to-kira-lav text-white hover:shadow-lg hover:scale-105'
        }`}
      >
        <span className="text-base">{isListening ? '⏹️' : '🎤'}</span>
        {isListening ? 'Listening...' : 'Talk to Kira'}
      </button>

      <style>{`
        .arm-wave {
          animation: armWave 0.6s ease-in-out;
        }
        .wave-arm {
          animation: waveArm 0.6s ease-in-out;
          transform-origin: 92px 88px;
        }
        @keyframes armWave {
          0%, 100% { transform: rotate(-10deg); }
          25% { transform: rotate(-30deg); }
          75% { transform: rotate(5deg); }
        }
        @keyframes waveArm {
          0%, 100% { transform: rotate(-10deg); }
          25% { transform: rotate(-40deg); }
          75% { transform: rotate(10deg); }
        }
        @keyframes listening-pulse {
          0%, 100% { box-shadow: 0 0 0 0 rgba(248, 113, 113, 0.4); }
          50% { box-shadow: 0 0 0 12px rgba(248, 113, 113, 0); }
        }
        .animate-listening-pulse {
          animation: listening-pulse 1.5s infinite;
        }
        .mouth-talk {
          animation: mouthOpen 0.3s ease-in-out;
        }
        @keyframes mouthOpen {
          0%, 100% { rx: 5; ry: 4; }
          50% { rx: 6; ry: 5; }
        }
      `}</style>
    </div>
  );
}
