import { useState, useRef } from 'react';
import { useTheme } from '../../context/ThemeContext';
import { Icons } from '../icons/Icons';

const particles = (n = 16) =>
  Array.from({ length: n }, (_, i) => {
    const angle = (i / n) * Math.PI * 2 + Math.random() * 0.25;
    const dist = 100 + Math.random() * 160;
    return {
      dx: Math.cos(angle) * dist,
      dy: Math.sin(angle) * dist,
      delay: Math.random() * 80,
      size: 3 + Math.random() * 5,
    };
  });

export default function ThemeToggle({ collapsed = false }) {
  const { theme, toggle } = useTheme();
  const [animating, setAnimating] = useState(false);
  const [stage, setStage] = useState(null); // { from: {x,y}, to: {x,y}, nextTheme, parts }
  const btnRef = useRef(null);

  const handleClick = () => {
    if (animating) return;
    const btn = btnRef.current;
    if (!btn) { toggle(); return; }
    const rect = btn.getBoundingClientRect();
    const from = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
    const to = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
    const nextTheme = theme === 'dark' ? 'light' : 'dark';
    const radius = Math.hypot(window.innerWidth, window.innerHeight) / 2 + 100;

    setStage({ from, to, nextTheme, radius, parts: particles(18) });
    setAnimating(true);

    // Timing (smooth cinematic):
    // 0-850ms    — icon travels smoothly to center (simple translate + scale)
    // 850-1150ms — icon holds & pulses at center (the "slow moment")
    // 1150ms     — explosion begins
    // 1250ms     — theme flips (mid-explosion)
    // 3000ms     — all done
    setTimeout(() => toggle(), 1250);
    setTimeout(() => { setAnimating(false); setStage(null); }, 3000);
  };

  const isDark = theme === 'dark';
  const nextIsDark = stage?.nextTheme === 'dark';
  const nextBg = nextIsDark ? '#0b0e13' : '#eef2f8';
  const nextAccent = nextIsDark ? '#a78bfa' : '#fbbf24';

  // Flying icon represents the DESTINATION theme:
  //   going to dark  → Moon flies
  //   going to light → Sun flies
  const FlyingIcon = nextIsDark ? Icons.Moon : Icons.Sun;
  const flyingColor = nextIsDark ? '#7c3aed' : '#fbbf24';

  return (
    <>
      {stage && (
        <>
          {/* Flying icon — travels smoothly from button to center, pulses, then dissolves */}
          <div
            className="fixed pointer-events-none"
            style={{
              left: 0,
              top: 0,
              zIndex: 10001,
              transform: `translate(${stage.from.x}px, ${stage.from.y}px) translate(-50%, -50%)`,
              animation: `tt-fly 1200ms cubic-bezier(0.22, 1, 0.36, 1) forwards`,
              '--to-x': `${stage.to.x}px`,
              '--to-y': `${stage.to.y}px`,
              '--from-x': `${stage.from.x}px`,
              '--from-y': `${stage.from.y}px`,
            }}
          >
            <div
              className="flex items-center justify-center"
              style={{
                color: flyingColor,
                filter: `drop-shadow(0 0 20px ${flyingColor}) drop-shadow(0 0 40px ${flyingColor}aa)`,
              }}
            >
              <div style={{ transform: 'scale(2.5)' }}>
                <FlyingIcon />
              </div>
            </div>
          </div>

          {/* Leading ripple from center */}
          <div
            className="fixed pointer-events-none rounded-full"
            style={{
              left: stage.to.x,
              top: stage.to.y,
              width: stage.radius * 2,
              height: stage.radius * 2,
              zIndex: 9997,
              background: `radial-gradient(circle, ${nextAccent}55 0%, transparent 65%)`,
              transform: 'translate(-50%, -50%) scale(0)',
              animation: 'tt-ripple-lead 1700ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 1150ms forwards',
            }}
          />

          {/* Main color reveal from center */}
          <div
            className="fixed pointer-events-none rounded-full"
            style={{
              left: stage.to.x,
              top: stage.to.y,
              width: stage.radius * 2,
              height: stage.radius * 2,
              zIndex: 9998,
              background: nextBg,
              transform: 'translate(-50%, -50%) scale(0)',
              animation: 'tt-ripple-main 1600ms cubic-bezier(0.33, 0, 0.2, 1) 1250ms forwards',
            }}
          />

          {/* Trailing glow ring from center */}
          <div
            className="fixed pointer-events-none rounded-full border-2"
            style={{
              left: stage.to.x,
              top: stage.to.y,
              width: stage.radius * 2,
              height: stage.radius * 2,
              zIndex: 9999,
              borderColor: nextAccent,
              transform: 'translate(-50%, -50%) scale(0)',
              animation: 'tt-ripple-trail 1700ms cubic-bezier(0.25, 0.46, 0.45, 0.94) 1270ms forwards',
            }}
          />

          {/* Particle starburst from center */}
          {stage.parts.map((p, i) => (
            <div
              key={i}
              className="fixed pointer-events-none rounded-full"
              style={{
                left: stage.to.x,
                top: stage.to.y,
                width: p.size,
                height: p.size,
                zIndex: 10000,
                background: nextAccent,
                boxShadow: `0 0 10px ${nextAccent}, 0 0 20px ${nextAccent}aa, 0 0 30px ${nextAccent}77`,
                transform: 'translate(-50%, -50%)',
                opacity: 0,
                '--dx': `${p.dx}px`,
                '--dy': `${p.dy}px`,
                animation: `tt-particle 1700ms cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards`,
                animationDelay: `${1150 + p.delay}ms`,
              }}
            />
          ))}
        </>
      )}

      <style>{`
        @keyframes tt-fly {
          0% {
            transform: translate(var(--from-x), var(--from-y)) translate(-50%, -50%) scale(1);
            opacity: 1;
          }
          70% {
            transform: translate(var(--to-x), var(--to-y)) translate(-50%, -50%) scale(2.2);
            opacity: 1;
          }
          85% {
            transform: translate(var(--to-x), var(--to-y)) translate(-50%, -50%) scale(2.5);
            opacity: 1;
          }
          100% {
            transform: translate(var(--to-x), var(--to-y)) translate(-50%, -50%) scale(3.5);
            opacity: 0;
          }
        }
        @keyframes tt-ripple-lead {
          0%   { transform: translate(-50%, -50%) scale(0); opacity: 0.9; }
          70%  { opacity: 0.5; }
          100% { transform: translate(-50%, -50%) scale(1); opacity: 0; }
        }
        @keyframes tt-ripple-main {
          0%   { transform: translate(-50%, -50%) scale(0); opacity: 1; }
          88%  { opacity: 1; }
          100% { transform: translate(-50%, -50%) scale(1); opacity: 0; }
        }
        @keyframes tt-ripple-trail {
          0%   { transform: translate(-50%, -50%) scale(0); opacity: 1; border-width: 4px; }
          100% { transform: translate(-50%, -50%) scale(1); opacity: 0; border-width: 0; }
        }
        @keyframes tt-particle {
          0%   { transform: translate(-50%, -50%) scale(1); opacity: 1; }
          70%  { opacity: 0.9; }
          100% { transform: translate(calc(-50% + var(--dx)), calc(-50% + var(--dy))) scale(0); opacity: 0; }
        }
        @keyframes tt-icon-idle-pulse {
          0%, 100% { transform: scale(1); }
          50%      { transform: scale(0.85); opacity: 0.6; }
        }
      `}</style>

      {/* Sidebar inline button — displays DESTINATION icon (what you'll switch to) */}
      <button
        ref={btnRef}
        onClick={handleClick}
        aria-label={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
        title={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
        disabled={animating}
        className={`relative group flex items-center gap-2.5 rounded-md mx-1.5 my-0.5 transition-colors ${
          collapsed ? 'px-2.5 py-2.5 justify-center' : 'px-4 py-2'
        } text-t2 hover:bg-s2 hover:text-t1 w-[calc(100%-12px)] disabled:opacity-50`}
      >
        <span
          className={`flex-shrink-0 ${isDark ? 'text-or' : 'text-pr'}`}
          style={{ animation: animating ? 'tt-icon-idle-pulse 600ms ease-in-out' : 'none' }}
        >
          {isDark ? <Icons.Sun /> : <Icons.Moon />}
        </span>
        {!collapsed && (
          <span className="text-[13px]">{isDark ? 'Light Mode' : 'Dark Mode'}</span>
        )}
      </button>
    </>
  );
}
