import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { sendLeadToMautic, sendLeadViaMailto, trackConversion, trackFacebookPixel } from '../config/mautic';
import { 
  Mail, Phone, MapPin, Clock, Send, Check, Loader2,
  MessageSquare, Headphones
} from 'lucide-react';

gsap.registerPlugin(ScrollTrigger);

const canais = [
  {
    icon: <Phone className="w-6 h-6" />,
    titulo: 'Telefone',
    valor: '(11) 4810-1704',
    descricao: 'Segunda a Sexta, 8h às 18h',
    link: 'tel:+551148101704',
  },
  {
    icon: <MessageSquare className="w-6 h-6" />,
    titulo: 'WhatsApp',
    valor: '(11) 4810-1704',
    descricao: 'Atendimento 24/7',
    link: 'https://api.whatsapp.com/send?phone=551148101704',
  },
  {
    icon: <Mail className="w-6 h-6" />,
    titulo: 'Email',
    valor: 'contato@avanzato.com.br',
    descricao: 'Resposta em até 24h',
    link: 'mailto:contato@avanzato.com.br',
  },
  {
    icon: <Headphones className="w-6 h-6" />,
    titulo: 'Suporte Técnico',
    valor: 'suporte@avanzato.com.br',
    descricao: 'Para clientes Avanzato',
    link: 'https://suporte.avanzato.com.br/',
  },
];

const Contato = () => {
  const heroRef = useRef<HTMLDivElement>(null);
  const formRef = useRef<HTMLDivElement>(null);
  
  const [formData, setFormData] = useState({
    nome: '',
    email: '',
    empresa: '',
    telefone: '',
    servico: '',
    mensagem: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  useEffect(() => {
    const ctx = gsap.context(() => {
      const heroItems = heroRef.current?.querySelectorAll('.animate-item');
      if (heroItems && heroItems.length > 0) {
        gsap.fromTo(
          heroItems,
          { y: 50, opacity: 0 },
          {
            y: 0,
            opacity: 1,
            duration: 0.8,
            stagger: 0.1,
            ease: 'expo.out',
          }
        );
      }

      if (formRef.current) {
        gsap.fromTo(
          formRef.current,
          { y: 50, opacity: 0 },
          {
            y: 0,
            opacity: 1,
            duration: 0.8,
            ease: 'expo.out',
            scrollTrigger: {
              trigger: formRef.current,
              start: 'top 80%',
            },
          }
        );
      }
    });

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    // Enviar ao Formspree
    try {
      const response = await fetch('https://formspree.io/f/xwvjqyrr', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          nome: formData.nome,
          email: formData.email,
          empresa: formData.empresa,
          telefone: formData.telefone,
          servico: formData.servico,
          mensagem: formData.mensagem,
        }),
      });

      if (response.ok) {
        setIsSubmitted(true);
        setFormData({ nome: '', email: '', empresa: '', telefone: '', servico: '', mensagem: '' });

        // Google Ads conversion tracking
        trackConversion();

        // Facebook Pixel - Lead
        trackFacebookPixel('Lead', {
          content_name: 'Formulario Contato',
          content_category: 'lead_contato',
        });

        setTimeout(() => setIsSubmitted(false), 5000);
      } else {
        alert('Erro ao enviar. Tente novamente ou use o WhatsApp.');
      }
    } catch {
      // Fallback: enviar via mailto se Formspree falhar
      sendLeadViaMailto({
        nome: formData.nome,
        email: formData.email,
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  return (
    <div className="bg-[#0e0e0e] min-h-screen">
      {/* Hero */}
      <section ref={heroRef} className="pt-32 pb-20 relative overflow-hidden">
        <div className="absolute top-0 right-0 w-[600px] h-[600px] bg-[#cbf400]/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
        
        <div className="container-custom relative z-10">
          <div className="text-center max-w-3xl mx-auto">
            <span className="animate-item inline-block px-4 py-2 rounded-full bg-[#cbf400]/10 text-[#cbf400] text-sm font-semibold mb-6 border border-[#cbf400]/20">
              Contato
            </span>
            
            <h1 className="animate-item text-4xl md:text-5xl lg:text-6xl font-black text-white mb-6">
              Vamos <span className="text-gradient">conversar</span>
            </h1>
            
            <p className="animate-item text-xl text-gray-400">
              Entre em contato conosco. Nossa equipe está pronta para ajudar sua empresa.
            </p>
          </div>
        </div>
      </section>

      {/* Canais de Contato */}
      <section className="py-12 bg-[#1a1a1a] border-y border-white/5">
        <div className="container-custom">
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
            {canais.map((canal, index) => (
              <a
                key={index}
                href={canal.link}
                target={canal.link.startsWith('http') ? '_blank' : undefined}
                rel={canal.link.startsWith('http') ? 'noopener noreferrer' : undefined}
                className="group bg-[#0e0e0e] rounded-2xl p-6 border border-white/5 hover:border-[#cbf400]/30 transition-colors"
              >
                <div className="w-12 h-12 rounded-xl bg-[#cbf400]/10 flex items-center justify-center mb-4 text-[#cbf400] group-hover:bg-[#cbf400] group-hover:text-[#0e0e0e] transition-colors">
                  {canal.icon}
                </div>
                <h3 className="text-white font-bold mb-1">{canal.titulo}</h3>
                <p className="text-[#cbf400] font-medium mb-1">{canal.valor}</p>
                <p className="text-gray-500 text-sm">{canal.descricao}</p>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Formulário + Endereço */}
      <section className="py-20">
        <div className="container-custom">
          <div className="grid lg:grid-cols-2 gap-12">
            {/* Formulário */}
            <div ref={formRef}>
              <h2 className="text-2xl font-bold text-white mb-6">Envie uma mensagem</h2>
              
              {isSubmitted ? (
                <div className="bg-[#1a1a1a] rounded-2xl p-8 text-center border border-[#cbf400]/20">
                  <div className="w-16 h-16 rounded-full bg-[#cbf400]/20 flex items-center justify-center mx-auto mb-4">
                    <Check className="w-8 h-8 text-[#cbf400]" />
                  </div>
                  <h3 className="text-xl font-bold text-white mb-2">Mensagem enviada!</h3>
                  <p className="text-gray-400">Entraremos em contato em breve.</p>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="bg-[#1a1a1a] rounded-2xl p-8 border border-white/5">
                  <div className="grid sm:grid-cols-2 gap-6 mb-6">
                    <div>
                      <label className="block text-sm font-semibold text-gray-300 mb-2">Nome *</label>
                      <input
                        type="text"
                        name="nome"
                        value={formData.nome}
                        onChange={handleChange}
                        required
                        className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all"
                        placeholder="Seu nome"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-gray-300 mb-2">Email *</label>
                      <input
                        type="email"
                        name="email"
                        value={formData.email}
                        onChange={handleChange}
                        required
                        className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all"
                        placeholder="seu@email.com"
                      />
                    </div>
                  </div>
                  
                  <div className="grid sm:grid-cols-2 gap-6 mb-6">
                    <div>
                      <label className="block text-sm font-semibold text-gray-300 mb-2">Empresa</label>
                      <input
                        type="text"
                        name="empresa"
                        value={formData.empresa}
                        onChange={handleChange}
                        className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all"
                        placeholder="Nome da empresa"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-gray-300 mb-2">Telefone</label>
                      <input
                        type="tel"
                        name="telefone"
                        value={formData.telefone}
                        onChange={handleChange}
                        className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all"
                        placeholder="(11) 99999-9999"
                      />
                    </div>
                  </div>
                  
                  <div className="mb-6">
                    <label className="block text-sm font-semibold text-gray-300 mb-2">Serviço de interesse</label>
                    <select
                      name="servico"
                      value={formData.servico}
                      onChange={handleChange}
                      className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all"
                    >
                      <option value="">Selecione um serviço</option>
                      <option value="ti-gerenciada">TI Gerenciada</option>
                      <option value="cloud">Cloud Computing</option>
                      <option value="seguranca">Segurança da Informação</option>
                      <option value="suporte">Suporte Técnico</option>
                      <option value="consultoria">Consultoria</option>
                      <option value="outro">Outro</option>
                    </select>
                  </div>
                  
                  <div className="mb-6">
                    <label className="block text-sm font-semibold text-gray-300 mb-2">Mensagem *</label>
                    <textarea
                      name="mensagem"
                      value={formData.mensagem}
                      onChange={handleChange}
                      required
                      rows={4}
                      className="w-full px-4 py-3 rounded-lg bg-[#0e0e0e] border border-white/10 text-white focus:border-[#cbf400] focus:ring-2 focus:ring-[#cbf400]/20 outline-none transition-all resize-none"
                      placeholder="Como podemos ajudar?"
                    />
                  </div>
                  
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-70"
                  >
                    {isSubmitting ? (
                      <>
                        <Loader2 className="w-5 h-5 animate-spin" />
                        Enviando...
                      </>
                    ) : (
                      <>
                        Enviar mensagem
                        <Send className="w-5 h-5" />
                      </>
                    )}
                  </button>
                </form>
              )}
            </div>
            
            {/* Endereços + Mapas */}
            <div className="flex flex-col h-full">
              <h2 className="text-2xl font-bold text-white mb-6">Onde estamos</h2>
              
              {/* Bloco 1 - Guarulhos (Grande, alinhado com formulário) */}
              <div className="bg-[#1a1a1a] rounded-2xl overflow-hidden border border-white/5 flex-1 flex flex-col">
                <div className="p-4 border-b border-white/5">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-[#cbf400]/10 flex items-center justify-center flex-shrink-0">
                      <MapPin className="w-5 h-5 text-[#cbf400]" />
                    </div>
                    <div>
                      <p className="text-[#cbf400] font-medium text-sm">Guarulhos - Matriz</p>
                      <p className="text-gray-400 text-sm">Rua Juiz de Fora, 76</p>
                    </div>
                  </div>
                </div>
                <div className="flex-1 min-h-[400px]">
                  <iframe
                    src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3659.0!2d-46.5333!3d-23.4667!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cef5b0b8e8e8e8%3A0x0!2sRua+Juiz+de+Fora%2C+76+-+Guarulhos+-+SP!5e0!3m2!1spt-BR!2sbr!4v1"
                    width="100%"
                    height="100%"
                    style={{ border: 0, filter: 'grayscale(100%) invert(92%) contrast(83%)' }}
                    allowFullScreen
                    loading="lazy"
                    referrerPolicy="no-referrer-when-downgrade"
                    title="Guarulhos"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Mapas SP e Mogi - Lado a lado */}
      <section className="py-12 bg-[#0e0e0e]">
        <div className="container-custom">
          <div className="grid md:grid-cols-2 gap-6">
            {/* Bloco 2 - São Paulo */}
            <div className="bg-[#1a1a1a] rounded-2xl overflow-hidden border border-white/5">
              <div className="p-4 border-b border-white/5">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-[#cbf400]/10 flex items-center justify-center flex-shrink-0">
                    <MapPin className="w-5 h-5 text-[#cbf400]" />
                  </div>
                  <div>
                    <p className="text-[#cbf400] font-medium text-sm">São Paulo</p>
                    <p className="text-gray-400 text-sm">Rua Dom Estevão Pimentel, 165</p>
                  </div>
                </div>
              </div>
              <div className="aspect-[16/9]">
                <iframe
                  src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3659.0!2d-46.6333!3d-23.5500!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cef5b0b8e8e8e8%3A0x0!2sRua+Dom+Estev%C3%A3o+Pimentel%2C+165+-+S%C3%A3o+Paulo+-+SP!5e0!3m2!1spt-BR!2sbr!4v1"
                  width="100%"
                  height="100%"
                  style={{ border: 0, filter: 'grayscale(100%) invert(92%) contrast(83%)' }}
                  allowFullScreen
                  loading="lazy"
                  referrerPolicy="no-referrer-when-downgrade"
                  title="São Paulo"
                />
              </div>
            </div>

            {/* Bloco 3 - Mogi das Cruzes */}
            <div className="bg-[#1a1a1a] rounded-2xl overflow-hidden border border-white/5">
              <div className="p-4 border-b border-white/5">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-[#cbf400]/10 flex items-center justify-center flex-shrink-0">
                    <MapPin className="w-5 h-5 text-[#cbf400]" />
                  </div>
                  <div>
                    <p className="text-[#cbf400] font-medium text-sm">Mogi das Cruzes</p>
                    <p className="text-gray-400 text-sm">Rua Professor Flaviano de Melo, 250</p>
                  </div>
                </div>
              </div>
              <div className="aspect-[16/9]">
                <iframe
                  src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3659.0!2d-46.1833!3d-23.5167!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cef5b0b8e8e8e8%3A0x0!2sRua+Professor+Flaviano+de+Melo%2C+250+-+Mogi+das+Cruzes+-+SP!5e0!3m2!1spt-BR!2sbr!4v1"
                  width="100%"
                  height="100%"
                  style={{ border: 0, filter: 'grayscale(100%) invert(92%) contrast(83%)' }}
                  allowFullScreen
                  loading="lazy"
                  referrerPolicy="no-referrer-when-downgrade"
                  title="Mogi das Cruzes"
                />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Horário */}
      <section className="pb-20 bg-[#0e0e0e]">
        <div className="container-custom">
          <div className="bg-[#1a1a1a] rounded-2xl p-6 border border-white/5 max-w-2xl mx-auto">
            <div className="flex items-start gap-4">
              <div className="w-12 h-12 rounded-xl bg-[#cbf400]/10 flex items-center justify-center flex-shrink-0">
                <Clock className="w-6 h-6 text-[#cbf400]" />
              </div>
              <div>
                <h3 className="text-white font-bold mb-1">Horário de atendimento</h3>
                <p className="text-gray-400">
                  Segunda a Sexta: 8h às 18h<br />
                  <span className="text-[#cbf400]">Suporte técnico: 24/7</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Contato;
