import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ArrowRight, Play } from 'lucide-react';
import GlowButton from '../components/GlowButton';

const Hero = () => {
  const heroRef = useRef<HTMLDivElement>(null);
  const titleRef = useRef<HTMLHeadingElement>(null);
  const subtitleRef = useRef<HTMLParagraphElement>(null);
  const ctaRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });

  // Animated background
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const resizeCanvas = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    // Particles
    const particles: Array<{
      x: number;
      y: number;
      vx: number;
      vy: number;
      radius: number;
      opacity: number;
    }> = [];

    for (let i = 0; i < 50; i++) {
      particles.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        vx: (Math.random() - 0.5) * 0.5,
        vy: (Math.random() - 0.5) * 0.5,
        radius: Math.random() * 2 + 1,
        opacity: Math.random() * 0.5 + 0.2,
      });
    }

    let animationId: number;
    const animate = () => {
      ctx.fillStyle = 'rgba(14, 14, 14, 0.05)';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      particles.forEach((particle, i) => {
        particle.x += particle.vx;
        particle.y += particle.vy;

        if (particle.x < 0 || particle.x > canvas.width) particle.vx *= -1;
        if (particle.y < 0 || particle.y > canvas.height) particle.vy *= -1;

        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(203, 244, 0, ${particle.opacity})`;
        ctx.fill();

        // Connect particles
        particles.slice(i + 1).forEach((other) => {
          const dx = particle.x - other.x;
          const dy = particle.y - other.y;
          const distance = Math.sqrt(dx * dx + dy * dy);

          if (distance < 150) {
            ctx.beginPath();
            ctx.moveTo(particle.x, particle.y);
            ctx.lineTo(other.x, other.y);
            ctx.strokeStyle = `rgba(203, 244, 0, ${0.1 * (1 - distance / 150)})`;
            ctx.stroke();
          }
        });
      });

      animationId = requestAnimationFrame(animate);
    };

    animate();

    return () => {
      window.removeEventListener('resize', resizeCanvas);
      cancelAnimationFrame(animationId);
    };
  }, []);

  // GSAP animations
  useEffect(() => {
    const ctx = gsap.context(() => {
      // Title animation
      gsap.fromTo(
        titleRef.current,
        { y: 100, opacity: 0 },
        { y: 0, opacity: 1, duration: 0.8, delay: 0.2, ease: 'expo.out' }
      );

      // Subtitle animation
      gsap.fromTo(
        subtitleRef.current,
        { y: 50, opacity: 0 },
        { y: 0, opacity: 1, duration: 0.6, delay: 0.4, ease: 'expo.out' }
      );

      // CTA animation
      gsap.fromTo(
        ctaRef.current,
        { scale: 0.8, opacity: 0 },
        { scale: 1, opacity: 1, duration: 0.6, delay: 0.6, ease: 'back.out(1.7)' }
      );

      // Image animation
      gsap.fromTo(
        imageRef.current,
        { rotateX: 45, opacity: 0, y: 50 },
        { rotateX: 0, opacity: 1, y: 0, duration: 1.2, delay: 0.4, ease: 'elastic.out(1, 0.5)' }
      );
    }, heroRef);

    return () => ctx.revert();
  }, []);

  // Mouse parallax effect
  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      const x = (e.clientX / window.innerWidth - 0.5) * 20;
      const y = (e.clientY / window.innerHeight - 0.5) * 20;
      setMousePos({ x, y });
    };

    window.addEventListener('mousemove', handleMouseMove, { passive: true });
    return () => window.removeEventListener('mousemove', handleMouseMove);
  }, []);

  return (
    <section
      id="hero"
      ref={heroRef}
      className="relative min-h-screen flex items-center overflow-hidden bg-[#0e0e0e]"
    >
      {/* Animated background canvas */}
      <canvas
        ref={canvasRef}
        className="absolute inset-0 w-full h-full"
        style={{ opacity: 0.8 }}
      />

      {/* Gradient overlay */}
      <div className="absolute inset-0 bg-gradient-to-br from-[#cbf400]/5 via-transparent to-transparent" />

      {/* Content */}
      <div className="container-custom relative z-10 pt-32 pb-20">
        <div className="grid lg:grid-cols-2 gap-12 items-center">
          {/* Left content */}
          <div className="text-white">
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#cbf400]/10 backdrop-blur-sm mb-6 border border-[#cbf400]/20">
              <span className="w-2 h-2 rounded-full bg-[#cbf400] animate-pulse" />
              <span className="text-sm font-semibold text-[#cbf400]">+23 anos de experiência</span>
            </div>

            <h1
              ref={titleRef}
              className="text-4xl md:text-5xl lg:text-6xl font-black leading-tight mb-6"
              style={{ fontFamily: 'Urbanist, sans-serif' }}
            >
              Tecnologia que{' '}
              <span className="text-gradient">impulsiona</span> seu negócio
            </h1>

            <p
              ref={subtitleRef}
              className="text-lg md:text-xl text-gray-400 mb-8 max-w-xl font-medium"
            >
              Soluções em TI Gerenciada, Cloud e Segurança para empresas que não podem parar.
              Seu parceiro estratégico em transformação digital.
            </p>

            <div ref={ctaRef} className="flex flex-wrap gap-4">
              <a
                href="https://api.whatsapp.com/send?phone=551148101704&text=Olá!%20Visitei%20o%20site%20e%20gostaria%20de%20saber%20mais%20informações%20sobre%20os%20serviços"
                target="_blank"
                rel="noopener noreferrer"
                className="btn-primary inline-flex items-center gap-2"
              >
                Fale com um especialista
                <ArrowRight className="w-5 h-5" />
              </a>
              <a
                href="#services"
                onClick={(e) => {
                  e.preventDefault();
                  document.querySelector('#services')?.scrollIntoView({ behavior: 'smooth' });
                }}
                className="btn-secondary inline-flex items-center gap-2"
              >
                <Play className="w-5 h-5" />
                Conheça nossos serviços
              </a>
            </div>

            {/* Botao Avaliacao TI - Super destacado */}
            <div className="mt-6">
              <GlowButton
                to="/avaliacao"
                text="Avalie a maturidade da sua TI"
                size="lg"
              />
              <p className="text-gray-500 text-sm mt-2 ml-1">
                Descubra o nivel de maturidade tecnologica da sua empresa em 2 minutos
              </p>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-3 gap-6 mt-12 pt-8 border-t border-white/10">
              <div>
                <div className="text-3xl md:text-4xl font-black text-[#cbf400]">+500</div>
                <div className="text-sm text-gray-500 font-medium">Clientes atendidos</div>
              </div>
              <div>
                <div className="text-3xl md:text-4xl font-black text-[#cbf400]">99.9%</div>
                <div className="text-sm text-gray-500 font-medium">Uptime garantido</div>
              </div>
              <div>
                <div className="text-3xl md:text-4xl font-black text-[#cbf400]">24/7</div>
                <div className="text-sm text-gray-500 font-medium">Suporte técnico</div>
              </div>
            </div>
          </div>

          {/* Right content - Dashboard Image */}
          <div
            ref={imageRef}
            className="relative lg:pl-8"
            style={{
              transform: `perspective(1000px) rotateY(${mousePos.x * 0.5}deg) rotateX(${-mousePos.y * 0.5}deg)`,
              transition: 'transform 0.1s ease-out',
            }}
          >
            <div className="relative animate-float">
              {/* Glow effect */}
              <div className="absolute -inset-4 bg-gradient-to-r from-[#cbf400]/20 to-[#cbf400]/10 rounded-2xl blur-2xl opacity-50" />
              
              {/* Dashboard image */}
              <div className="relative rounded-2xl overflow-hidden shadow-2xl border border-[#cbf400]/20">
                <img
                  src="/hero-dashboard.jpg"
                  alt="Dashboard Avanzato"
                  className="w-full h-auto"
                />
                
                {/* Glossy overlay */}
                <div 
                  className="absolute inset-0 bg-gradient-to-br from-white/10 via-transparent to-transparent pointer-events-none"
                  style={{
                    transform: `translateX(${mousePos.x}%) translateY(${mousePos.y}%)`,
                  }}
                />
              </div>

              {/* Floating badge */}
              <div className="absolute -bottom-4 -left-4 bg-[#1a1a1a] rounded-xl p-4 shadow-xl border border-[#cbf400]/30">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-[#cbf400]/20 flex items-center justify-center">
                    <svg className="w-5 h-5 text-[#cbf400]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                  <div>
                    <div className="text-white font-bold text-sm">Sistema operacional</div>
                    <div className="text-gray-500 text-xs">Todos os serviços ativos</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom gradient fade */}
      <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-[#0e0e0e] to-transparent" />
    </section>
  );
};

export default Hero;
