import { useState, useCallback, memo, useMemo } from "react";
import { motion } from "framer-motion";
import { useTranslation } from "react-i18next";
import emailjs from "emailjs-com";
import { BsGithub, BsInstagram, BsLinkedin, BsTwitterX } from "react-icons/bs";
import PropTypes from 'prop-types';
import GlassBackground from "./GlassBackground";

// Componente optimizado para los iconos de redes sociales con glassmorphism
const SocialIcon = memo(({ href, icon: Icon, hoverColor }) => (
  <motion.li 
    whileHover={{ 
      scale: 1.15, 
      y: -5,
      transition: { duration: 0.2, ease: "easeOut" }
    }}
    whileTap={{ scale: 0.95 }}
    className="relative group"
  >
    <a 
      href={href} 
      target="_blank" 
      rel="noopener noreferrer"
      className={`flex items-center justify-center w-12 h-12 rounded-full border border-adaptive glass-lite transition-all duration-300 text-xl opacity-80 hover:opacity-100 hover:border-violet-500/20 hover:shadow-[0_0_15px_rgba(139,92,246,0.25)] ${hoverColor}`}
    >
      <Icon />
      
      {/* Glow effect on hover */}
      <div className="absolute inset-0 rounded-full opacity-0 group-hover:opacity-30 transition-opacity duration-300 bg-gradient-to-r from-violet-500 to-sky-500 blur-lg -z-10"></div>
    </a>
  </motion.li>
));

SocialIcon.displayName = 'SocialIcon';
SocialIcon.propTypes = {
  href: PropTypes.string.isRequired,
  icon: PropTypes.elementType.isRequired,
  hoverColor: PropTypes.string.isRequired
};

const socialNetworks = [
  { id: 1, href: "https://www.instagram.com/radiocreep95", icon: BsInstagram, hoverColor: "text-pink-500 dark:text-pink-500 light:text-pink-600" },
  { id: 2, href: "https://www.linkedin.com/in/never130/", icon: BsLinkedin, hoverColor: "text-blue-500 dark:text-blue-500 light:text-blue-600" },
  { id: 3, href: "https://x.com/never130", icon: BsTwitterX, hoverColor: "text-adaptive" },
  { id: 4, href: "https://github.com/never130", icon: BsGithub, hoverColor: "text-orange-500 dark:text-orange-500 light:text-orange-600" }
];

const Contact = () => {
  const { t } = useTranslation();
  const [formData, setFormData] = useState({ name: "", email: "", message: "" });
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const validateForm = useCallback(() => {
    const newErrors = {};
    if (!formData.name.trim()) newErrors.name = t("contact.errors.name");
    if (!formData.email.trim()) {
      newErrors.email = t("contact.errors.email");
    } else {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        newErrors.email = t("contact.errors.emailInvalid");
      }
    }
    if (!formData.message.trim()) newErrors.message = t("contact.errors.message");
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData.name, formData.email, formData.message, t]);

  const handleChange = useCallback((e) => {
    const { name, value } = e.target;
    setFormData(prevData => ({ ...prevData, [name]: value }));
    if (errors[name]) {
      setErrors(prevErrors => ({ ...prevErrors, [name]: "" }));
    }
  }, [errors]);

  const handleSubmit = useCallback((e) => {
    e.preventDefault();
    
    if (!validateForm()) return;
    
    setIsSubmitting(true);
    setStatus("");
    setErrors({});

    const serviceId = "service_4zzkduf";
    const templateId = "template_pahpa4c";
    const userId = "SJFGZonkWvf5RR9h7";

    if (!serviceId || !templateId || !userId) {
      console.error("EmailJS configuration missing");
      setStatus("error");
      setIsSubmitting(false);
      return;
    }

    emailjs.sendForm(serviceId, templateId, e.target, userId)
      .then(
        (result) => {
          console.log("Email sent successfully:", result.text);
          setStatus("success");
          setFormData({ name: "", email: "", message: "" });
          setErrors({});
        },
        (error) => {
          console.error("EmailJS Error:", error);
          setStatus("error");
        }
      )
      .finally(() => setIsSubmitting(false));
  }, [validateForm]);

  const containerVariants = useMemo(() => ({
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: { staggerChildren: 0.1, delayChildren: 0.2 }
    }
  }), []);

  const itemVariants = useMemo(() => ({
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0, transition: { duration: 0.5 } }
  }), []);

  return (
    <section id="contact" className="section-container flex min-h-screen w-full items-center justify-center py-20">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 md:gap-16 w-full max-w-7xl px-4 sm:px-6">
        
        {/* Sección izquierda: Título + Descripción + Redes Sociales */}
        <motion.div
          variants={containerVariants}
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true }}
          className="flex flex-col items-center justify-center gap-6 md:gap-10 text-adaptive"
        >
          <motion.h2 variants={itemVariants} className="text-center text-3xl sm:text-4xl md:text-5xl font-bold text-indigo-200 dark:text-indigo-200 light:text-indigo-700 tracking-tight text-gradient-neon uppercase leading-none">
            {t("contact.title")}
          </motion.h2>

          <div className="flex flex-col items-center gap-6">
            <motion.p variants={itemVariants} className="text-center text-base sm:text-lg font-semibold text-adaptive-secondary leading-relaxed max-w-md">
              {t("contact.description")}
            </motion.p>

            <motion.ul variants={itemVariants} className="flex gap-4 sm:gap-6">
              {socialNetworks.map((network) => (
                <SocialIcon key={network.id} href={network.href} icon={network.icon} hoverColor={network.hoverColor} />
              ))}
            </motion.ul>
          </div>
        </motion.div>

        {/* Sección derecha: Formulario con glassmorphism */}
        <motion.div
          variants={containerVariants}
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true }}
          className="flex flex-col items-center justify-center gap-6 w-full mx-auto max-w-lg"
        >
          <div
            className="glass border border-adaptive relative isolate overflow-hidden rounded-3xl px-6 py-6 sm:px-8 sm:py-7 bg-black/65 dark:bg-black/65 light:bg-white/70 backdrop-blur-xl shadow-2xl w-full text-left"
          >
            <GlassBackground />
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
              className="mb-6 relative z-10"
            >
              <h3 className="text-2xl font-bold text-indigo-200 dark:text-indigo-200 light:text-indigo-700 mb-2 uppercase tracking-wide">
                {t("contact.button")}
              </h3>
              <div className="h-1 w-20 bg-gradient-to-r from-violet-500 via-indigo-500 to-sky-500 rounded-full shadow-[0_0_8px_#8b5cf6]"></div>
            </motion.div>
          <form onSubmit={handleSubmit} className="w-full flex flex-col gap-5 relative z-10">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 w-full">
              <div className="flex flex-col">
                <motion.input
                  variants={itemVariants}
                  type="text"
                  name="name"
                  autoComplete="name"
                  value={formData.name}
                  onChange={handleChange}
                  placeholder={t("contact.name")}
                  className={`p-4 rounded-2xl glass-lite border border-adaptive text-adaptive placeholder:text-gray-400 dark:placeholder:text-gray-400 light:placeholder:text-gray-500 focus-neon transition-all duration-300 ${
                    errors.name ? 'border-red-500/50' : ''
                  }`}
                  required
                />
                {errors.name && (
                  <span className="text-red-500 text-xs text-left mt-1 font-semibold">{errors.name}</span>
                )}
              </div>
              <div className="flex flex-col">
                <motion.input
                  variants={itemVariants}
                  type="email"
                  name="email"
                  autoComplete="email"
                  value={formData.email}
                  onChange={handleChange}
                  placeholder={t("contact.email")}
                  className={`p-4 rounded-2xl glass-lite border border-adaptive text-adaptive placeholder:text-gray-400 dark:placeholder:text-gray-400 light:placeholder:text-gray-500 focus-neon transition-all duration-300 ${
                    errors.email ? 'border-red-500/50' : ''
                  }`}
                  required
                />
                {errors.email && (
                  <span className="text-red-500 text-xs text-left mt-1 font-semibold">{errors.email}</span>
                )}
              </div>
            </div>
            <div className="flex flex-col">
              <motion.textarea
                variants={itemVariants}
                name="message"
                value={formData.message}
                onChange={handleChange}
                placeholder={t("contact.message")}
                className={`p-4 rounded-2xl glass-lite border border-adaptive text-adaptive placeholder:text-gray-400 dark:placeholder:text-gray-400 light:placeholder:text-gray-500 focus-neon h-40 w-full transition-all duration-300 resize-none ${
                  errors.message ? 'border-red-500/50' : ''
                }`}
                required
              />
              {errors.message && (
                <span className="text-red-500 text-xs text-left mt-1 font-semibold">{errors.message}</span>
              )}
            </div>
            <motion.button
              variants={itemVariants}
              whileHover={{ 
                scale: 1.03,
                boxShadow: "0 15px 30px rgba(99, 102, 241, 0.35)",
                transition: { duration: 0.2 }
              }}
              whileTap={{ scale: 0.97 }}
              type="submit"
              disabled={isSubmitting}
              className="w-full p-4 rounded-2xl bg-gradient-to-r from-violet-600 via-indigo-600 to-sky-600 hover:from-violet-500 hover:via-indigo-500 hover:to-sky-500 text-white text-base font-bold transition-all duration-300 disabled:opacity-70 disabled:cursor-not-allowed border-0 cursor-pointer relative overflow-hidden group shadow-lg shadow-indigo-500/20"
            >
              <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent transform -skew-x-12 -translate-x-full group-hover:translate-x-full transition-transform duration-700"></div>
              <span className="relative z-10 uppercase tracking-wider">
                {isSubmitting ? t("contact.sending") : t("contact.submit")}
              </span>
            </motion.button>
          </form>

          {status && (
            <motion.p
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              className={`mt-4 relative z-10 text-sm font-semibold text-center ${status === "success" ? "text-green-500" : "text-red-500"}`}
            >
              {t(`contact.${status}`)}
            </motion.p>
          )}
          </div>
        </motion.div>
      </div>
    </section>
  );
};

export default Contact;
