// src/app/components/admin/blocks/ContactSection.tsx

'use client';

import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { useState } from 'react';
import { 
  Mail, Phone, MessageCircle, ArrowRight, CheckCircle, 
  Star, Users, Rocket, LucideIcon 
} from 'lucide-react';
import { ContactSectionProps, ContactStat } from '@/lib/page-builder/types';

// Icon mapping
const iconMap: Record<string, LucideIcon> = {
  Mail: Mail,
  Phone: Phone,
  MessageCircle: MessageCircle,
  CheckCircle: CheckCircle,
  Star: Star,
  Users: Users,
  Rocket: Rocket
};

const getIconComponent = (iconName: string): LucideIcon => {
  return iconMap[iconName] || Star;
};

// Default stats
const defaultStats: ContactStat[] = [
  { icon: 'Users', number: '5,000+', label: 'Successful Publications' },
  { icon: 'Star', number: '98%', label: 'Client Satisfaction' },
  { icon: 'Rocket', number: '3-7', label: 'Days Average Delivery' },
  { icon: 'CheckCircle', number: '40+', label: 'Average DA Score' }
];

export default function ContactSection(props: ContactSectionProps) {
  const {
    id,
    className = '',
    title = 'Start Your',
    highlightedText = 'Success Story',
    description = 'Get featured on premium websites and watch your authority grow.',
    badgeText = 'Ready to Get Started?',
    showBadge = true,
    formTitle = 'Get Your Free Strategy Session',
    formDescription = 'Fill out the form below and our expert will contact you within 2 hours to discuss your guest posting strategy.',
    stats = defaultStats,
    showStats = true,
    showContactMethods = true,
    contactEmail = 'contact@outreachexpert.co',
    contactPhone = '+44 747 646 1429',
    contactEmailResponse = 'Average response: 2 hours',
    contactPhoneHours = 'Mon-Fri, 9AM-6PM EST',
    showGuarantee = true,
    guaranteeTitle = '100% Satisfaction Guarantee',
    guaranteeDescription = 'If we don\'t deliver quality backlinks from premium websites, you don\'t pay. Your success is our priority.',
    submitButtonText = 'Get Free Strategy Session',
    submittingText = 'Sending...',
    privacyText = 'No spam, ever. We respect your privacy and will never share your information.',
    apiEndpoint = '/api/contact'
  } = props;

  const [ref, inView] = useInView({
    triggerOnce: true,
    threshold: 0.1,
  });

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    website: '',
    message: ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setSubmitStatus('idle');
    setErrorMessage('');
    
    try {
      // Simulate API call - replace with actual API endpoint
      const response = await fetch(apiEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      
      if (!response.ok) {
        throw new Error('Failed to submit form');
      }
      
      setSubmitStatus('success');
      setFormData({ name: '', email: '', website: '', message: '' });
      
      // Reset success message after 3 seconds
      setTimeout(() => {
        setSubmitStatus('idle');
      }, 3000);
    } catch (err) {
      setSubmitStatus('error');
      setErrorMessage(err instanceof Error ? err.message : 'Something went wrong. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { y: 30, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: {
        type: "spring" as const,
        stiffness: 100,
        damping: 15
      }
    }
  };

  return (
    <section id={id} className={`py-24 bg-linear-to-br from-slate-900 via-purple-900 to-blue-900 relative overflow-hidden ${className}`}>
      {/* Background Elements */}
      <div className="absolute top-0 left-0 w-96 h-96 bg-blue-500/10 rounded-full blur-3xl"></div>
      <div className="absolute bottom-0 right-0 w-80 h-80 bg-purple-500/10 rounded-full blur-3xl"></div>
      <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-cyan-500/5 rounded-full blur-3xl"></div>

      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Section Header */}
        <motion.div
          ref={ref}
          initial={{ opacity: 0, y: 40 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.8 }}
          className="text-center mb-16"
        >
          {showBadge && (
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              animate={inView ? { opacity: 1, scale: 1 } : {}}
              transition={{ duration: 0.6, delay: 0.2 }}
              className="inline-flex items-center gap-3 bg-white/10 text-white/90 px-6 py-3 rounded-2xl text-sm font-semibold mb-8 backdrop-blur-sm border border-white/20"
            >
              <MessageCircle className="h-5 w-5" />
              {badgeText}
            </motion.div>
          )}
          
          <motion.h2
            initial={{ opacity: 0, y: 30 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8, delay: 0.3 }}
            className="text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-6"
          >
            {title}
            <span className="bg-linear-to-r from-cyan-400 to-purple-400 bg-clip-text text-transparent ml-4">
              {highlightedText}
            </span>
          </motion.h2>
          
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8, delay: 0.4 }}
            className="text-xl text-white/80 max-w-3xl mx-auto leading-relaxed font-light"
          >
            {description}
            <span className="font-semibold text-cyan-300"> Let`s discuss your goals and create a winning strategy.</span>
          </motion.p>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start">
          {/* Contact Form */}
          <motion.div
            variants={containerVariants}
            initial="hidden"
            animate={inView ? "visible" : "hidden"}
            className="bg-white/5 backdrop-blur-lg rounded-3xl p-8 border border-white/10 shadow-2xl"
          >
            <h3 className="text-2xl font-bold text-white mb-6">{formTitle}</h3>
            <p className="text-white/70 mb-8">{formDescription}</p>

            <form onSubmit={handleSubmit} className="space-y-6">
              <motion.div variants={itemVariants}>
                <label htmlFor="name" className="block text-white/80 text-sm font-medium mb-2">
                  Full Name *
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  required
                  value={formData.name}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-cyan-400 focus:border-transparent transition-all duration-300"
                  placeholder="Enter your full name"
                />
              </motion.div>

              <motion.div variants={itemVariants}>
                <label htmlFor="email" className="block text-white/80 text-sm font-medium mb-2">
                  Email Address *
                </label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  required
                  value={formData.email}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-cyan-400 focus:border-transparent transition-all duration-300"
                  placeholder="Enter your email address"
                />
              </motion.div>

              <motion.div variants={itemVariants}>
                <label htmlFor="website" className="block text-white/80 text-sm font-medium mb-2">
                  Website URL
                </label>
                <input
                  type="url"
                  id="website"
                  name="website"
                  value={formData.website}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-cyan-400 focus:border-transparent transition-all duration-300"
                  placeholder="https://yourwebsite.com"
                />
              </motion.div>

              <motion.div variants={itemVariants}>
                <label htmlFor="message" className="block text-white/80 text-sm font-medium mb-2">
                  Your Goals & Requirements
                </label>
                <textarea
                  id="message"
                  name="message"
                  rows={4}
                  value={formData.message}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-xl text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-cyan-400 focus:border-transparent transition-all duration-300 resize-none"
                  placeholder="Tell us about your business and what you hope to achieve with guest posting..."
                />
              </motion.div>

              {submitStatus === 'success' && (
                <div className="bg-green-500/20 border border-green-500/30 rounded-xl p-3 text-green-400 text-sm text-center">
                  ✓ Thank you! We`ll get back to you within 2 hours.
                </div>
              )}

              {submitStatus === 'error' && (
                <div className="bg-red-500/20 border border-red-500/30 rounded-xl p-3 text-red-400 text-sm text-center">
                  {errorMessage}
                </div>
              )}

              <motion.div variants={itemVariants}>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full bg-linear-to-r from-cyan-500 to-purple-500 text-white py-4 px-6 rounded-xl font-semibold hover:from-cyan-600 hover:to-purple-600 transition-all duration-300 shadow-lg hover:shadow-xl hover:scale-105 flex items-center justify-center gap-3 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? (
                    <>
                      <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                      {submittingText}
                    </>
                  ) : (
                    <>
                      {submitButtonText}
                      <ArrowRight className="h-5 w-5" />
                    </>
                  )}
                </button>
              </motion.div>

              <motion.p variants={itemVariants} className="text-white/50 text-sm text-center">
                {privacyText}
              </motion.p>
            </form>
          </motion.div>

          {/* Contact Info & Stats */}
          <motion.div
            initial={{ opacity: 0, x: 50 }}
            animate={inView ? { opacity: 1, x: 0 } : {}}
            transition={{ duration: 0.8, delay: 0.6 }}
            className="space-y-8"
          >
            {/* Contact Methods */}
            {showContactMethods && (
              <div className="bg-white/5 backdrop-blur-lg rounded-3xl p-8 border border-white/10 shadow-2xl">
                <h3 className="text-2xl font-bold text-white mb-6">Other Ways to Reach Us</h3>
                
                <div className="space-y-4">
                  <motion.a
                    href={`mailto:${contactEmail}`}
                    whileHover={{ scale: 1.02 }}
                    className="flex items-center gap-4 p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-all duration-300 group"
                  >
                    <div className="w-12 h-12 bg-linear-to-r from-cyan-500 to-blue-500 rounded-xl flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
                      <Mail className="h-6 w-6 text-white" />
                    </div>
                    <div>
                      <div className="text-white font-semibold">Email Us</div>
                      <div className="text-cyan-300 text-sm">{contactEmail}</div>
                      <div className="text-white/60 text-xs">{contactEmailResponse}</div>
                    </div>
                  </motion.a>

                  <motion.a
                    href={`tel:${contactPhone.replace(/[^0-9+]/g, '')}`}
                    whileHover={{ scale: 1.02 }}
                    className="flex items-center gap-4 p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-all duration-300 group"
                  >
                    <div className="w-12 h-12 bg-linear-to-r from-purple-500 to-pink-500 rounded-xl flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
                      <Phone className="h-6 w-6 text-white" />
                    </div>
                    <div>
                      <div className="text-white font-semibold">Call or Whatsapp</div>
                      <div className="text-cyan-300 text-sm">{contactPhone}</div>
                      <div className="text-white/60 text-xs">{contactPhoneHours}</div>
                    </div>
                  </motion.a>
                </div>
              </div>
            )}

            {/* Stats */}
            {showStats && (
              <div className="grid grid-cols-2 gap-4">
                {stats.map((stat, index) => {
                  const IconComponent = getIconComponent(stat.icon);
                  return (
                    <motion.div
                      key={stat.label}
                      initial={{ opacity: 0, y: 20 }}
                      animate={inView ? { opacity: 1, y: 0 } : {}}
                      transition={{ duration: 0.6, delay: 0.8 + index * 0.1 }}
                      className="bg-white/5 backdrop-blur-sm rounded-2xl p-4 border border-white/10 text-center"
                    >
                      <IconComponent className="h-8 w-8 text-cyan-400 mx-auto mb-2" />
                      <div className="text-2xl font-bold text-white">{stat.number}</div>
                      <div className="text-white/70 text-sm">{stat.label}</div>
                    </motion.div>
                  );
                })}
              </div>
            )}

            {/* Guarantee */}
            {showGuarantee && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={inView ? { opacity: 1 } : {}}
                transition={{ duration: 0.6, delay: 1.2 }}
                className="bg-linear-to-r from-green-500/20 to-emerald-500/20 rounded-2xl p-6 border border-green-500/30 text-center"
              >
                <CheckCircle className="h-12 w-12 text-green-400 mx-auto mb-3" />
                <h4 className="text-white font-bold text-lg mb-2">{guaranteeTitle}</h4>
                <p className="text-white/80 text-sm">
                  {guaranteeDescription}
                </p>
              </motion.div>
            )}
          </motion.div>
        </div>
      </div>
    </section>
  );
}