'use client'

import { motion } from 'framer-motion'
import { useInView } from 'framer-motion'
import { useRef, useState } from 'react'
import { Mail, Phone, MapPin, Send, Linkedin, Twitter, ChevronDown, Facebook, CheckCircle, AlertCircle } from 'lucide-react'

const Contact = () => {
  const ref = useRef(null)
  const isInView = useInView(ref, { once: true, margin: '-50px' })
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    service: '',
    subject: '',
    message: ''
  })
  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitStatus, setSubmitStatus] = useState<{
    type: 'success' | 'error' | null;
    message: string;
  }>({ type: null, message: '' })

  const services = [
    'Full Stack Development',
    'Frontend Development',
    'Backend Development',
    'Web Application Maintenance',
    'API Development',
    'Database Design',
    'Performance Optimization',
    'Code Review & Consultation',
    'Technical Leadership',
    'Project Rescue'
  ]

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value
    }))
  }

  const handleServiceSelect = (service: string) => {
    setFormData(prev => ({
      ...prev,
      service
    }))
    setIsDropdownOpen(false)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)
    setSubmitStatus({ type: null, message: '' })

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })

      const data = await response.json()

      if (response.ok) {
        setSubmitStatus({
          type: 'success',
          message: 'Message sent successfully! I will get back to you soon.'
        })
        // Reset form
        setFormData({
          name: '',
          email: '',
          service: '',
          subject: '',
          message: ''
        })
      } else {
        setSubmitStatus({
          type: 'error',
          message: data.error || 'Failed to send message. Please try again.'
        })
      }
    } catch (error) {
      console.log(error);
      setSubmitStatus({
        type: 'error',
        message: 'Network error. Please check your connection and try again.'
      })
    } finally {
      setIsSubmitting(false)
      // Auto-hide status message after 5 seconds
      setTimeout(() => {
        setSubmitStatus({ type: null, message: '' })
      }, 5000)
    }
  }

  const contactInfo = [
    {
      icon: Mail,
      label: 'Email',
      value: 'ranausmaninbox@gmail.com',
      href: 'mailto:ranausmaninbox@gmail.com'
    },
    {
      icon: Phone,
      label: 'Phone',
      value: '+92 314 798 1434',
      href: 'tel:+923147981434'
    },
    {
      icon: MapPin,
      label: 'Location',
      value: 'Lahore, Pakistan',
      href: '#'
    }
  ]

  const socialLinks = [
    {
      icon: Linkedin,
      label: 'LinkedIn',
      href: 'https://www.linkedin.com/in/rana-muhammad-usman/',
      color: 'hover:text-blue-400'
    },
    {
      icon: Facebook,
      label: 'Facebook',
      href: 'https://www.facebook.com/ranausman4760',
      color: 'hover:text-gray-400'
    },
    {
      icon: Twitter,
      label: 'Twitter',
      href: 'https://twitter.com/yourusername',
      color: 'hover:text-blue-300'
    }
  ]

  return (
    <section id="contact" ref={ref} className="py-28 lg:py-36 bg-surface/10 relative overflow-hidden">
      {/* Background Elements */}
      <div className="absolute inset-0">
        <div className="absolute top-20 right-10 w-80 h-80 bg-primary/5 rounded-full blur-3xl"></div>
        <div className="absolute bottom-20 left-10 w-80 h-80 bg-secondary/5 rounded-full blur-3xl"></div>
      </div>

      <div className="w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        
        {/* Section Header */}
        <motion.div
          initial={{ opacity: 0, y: 40 }}
          animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-20"
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.8 }}
            animate={isInView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.8 }}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="inline-flex items-center gap-4 text-primary/70 mb-6"
          >
            <div className="w-12 h-px bg-linear-to-r from-transparent to-primary/40"></div>
            <span className="text-sm font-semibold tracking-widest uppercase text-primary">Get In Touch</span>
            <div className="w-12 h-px bg-linear-to-l from-transparent to-primary/40"></div>
          </motion.div>
          
          <motion.h2
            initial={{ opacity: 0, y: 30 }}
            animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
            transition={{ duration: 0.8, delay: 0.3 }}
            className="text-5xl lg:text-6xl font-light text-text mb-6"
          >
            Let us <span className="font-semibold bg-linear-to-r from-primary to-secondary bg-clip-text text-transparent">Connect</span>
          </motion.h2>
          
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
            transition={{ duration: 0.8, delay: 0.4 }}
            className="text-xl text-text/60 max-w-3xl mx-auto leading-relaxed font-light"
          >
            Ready to bring your ideas to life? Let us discuss your project and create something 
            amazing together. I am always open to new opportunities and collaborations.
          </motion.p>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16">
          
          {/* Contact Information */}
          <motion.div
            initial={{ opacity: 0, x: -40 }}
            animate={isInView ? { opacity: 1, x: 0 } : { opacity: 0, x: -40 }}
            transition={{ duration: 0.8, delay: 0.5 }}
            className="space-y-8"
          >
            <div>
              <h3 className="text-3xl font-semibold text-text mb-6">
                Let us Start a <span className="text-primary">Conversation</span>
              </h3>
              <p className="text-text/70 leading-relaxed text-lg mb-8">
                Whether you have a project in mind, want to collaborate, or just want to say hello, 
                I would love to hear from you. Let us connect and discuss how we can work together to 
                bring your vision to life.
              </p>
            </div>

            {/* Contact Info Cards */}
            <div className="space-y-4">
              {contactInfo.map((item, index) => (
                <motion.a
                  key={item.label}
                  href={item.href}
                  initial={{ opacity: 0, x: -20 }}
                  animate={isInView ? { opacity: 1, x: 0 } : { opacity: 0, x: -20 }}
                  transition={{ duration: 0.6, delay: 0.7 + index * 0.1 }}
                  className="flex items-center gap-4 p-4 bg-surface/50 backdrop-blur-sm rounded-2xl border border-gray-700/20 hover:border-primary/30 hover:transform hover:-translate-y-1 transition-all duration-300 group"
                >
                  <div className="w-12 h-12 bg-linear-to-br from-primary/20 to-primary/10 rounded-xl flex items-center justify-center group-hover:from-primary/30 group-hover:to-primary/20 transition-all duration-300">
                    <item.icon className="w-6 h-6 text-primary" />
                  </div>
                  <div>
                    <div className="text-text/60 text-sm font-medium">{item.label}</div>
                    <div className="text-text font-semibold group-hover:text-primary transition-colors duration-300">
                      {item.value}
                    </div>
                  </div>
                </motion.a>
              ))}
            </div>

            {/* Social Links */}
            <div className="pt-4">
              <h4 className="text-lg font-semibold text-text mb-4">Follow Me</h4>
              <div className="flex gap-4">
                {socialLinks.map((social, index) => (
                  <motion.a
                    key={social.label}
                    href={social.href}
                    target="_blank"
                    rel="noopener noreferrer"
                    initial={{ opacity: 0, scale: 0 }}
                    animate={isInView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
                    transition={{ duration: 0.4, delay: 1 + index * 0.1 }}
                    whileHover={{ scale: 1.1, y: -2 }}
                    className={`w-12 h-12 bg-surface/50 backdrop-blur-sm rounded-xl border border-gray-700/20 flex items-center justify-center text-text/60 ${social.color} hover:border-primary/30 transition-all duration-300`}
                  >
                    <social.icon className="w-5 h-5" />
                  </motion.a>
                ))}
              </div>
            </div>
          </motion.div>

          {/* Contact Form */}
          <motion.div
            initial={{ opacity: 0, x: 40 }}
            animate={isInView ? { opacity: 1, x: 0 } : { opacity: 0, x: 40 }}
            transition={{ duration: 0.8, delay: 0.7 }}
            className="bg-surface/50 backdrop-blur-sm rounded-3xl p-8 border border-gray-700/20"
          >
            {/* Status Message */}
            {submitStatus.type && (
              <motion.div
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className={`mb-6 p-4 rounded-xl flex items-center gap-3 ${
                  submitStatus.type === 'success' 
                    ? 'bg-green-500/10 border border-green-500/30 text-green-500' 
                    : 'bg-red-500/10 border border-red-500/30 text-red-500'
                }`}
              >
                {submitStatus.type === 'success' ? (
                  <CheckCircle className="w-5 h-5" />
                ) : (
                  <AlertCircle className="w-5 h-5" />
                )}
                <span className="text-sm">{submitStatus.message}</span>
              </motion.div>
            )}

            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                {/* Name Field */}
                <div>
                  <label htmlFor="name" className="block text-text font-medium mb-2">
                    Your Name *
                  </label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleChange}
                    required
                    disabled={isSubmitting}
                    className="w-full px-4 py-3 bg-background/50 border border-gray-700/30 rounded-xl text-text placeholder-text/40 focus:outline-none focus:border-primary transition-all duration-300 disabled:opacity-50"
                    placeholder="Enter your name"
                  />
                </div>

                {/* Email Field */}
                <div>
                  <label htmlFor="email" className="block text-text font-medium mb-2">
                    Email Address *
                  </label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    required
                    disabled={isSubmitting}
                    className="w-full px-4 py-3 bg-background/50 border border-gray-700/30 rounded-xl text-text placeholder-text/40 focus:outline-none focus:border-primary transition-all duration-300 disabled:opacity-50"
                    placeholder="Enter your email"
                  />
                </div>
              </div>

              {/* Services Dropdown */}
              <div className="relative">
                <label htmlFor="service" className="block text-text font-medium mb-2">
                  Service Needed *
                </label>
                <button
                  type="button"
                  onClick={() => !isSubmitting && setIsDropdownOpen(!isDropdownOpen)}
                  disabled={isSubmitting}
                  className="w-full px-4 py-3 bg-background/50 border border-gray-700/30 rounded-xl text-text focus:outline-none focus:border-primary transition-all duration-300 flex items-center justify-between disabled:opacity-50"
                >
                  <span className={formData.service ? 'text-text' : 'text-text/40'}>
                    {formData.service || 'Select a service'}
                  </span>
                  <ChevronDown className={`w-5 h-5 text-text/60 transition-transform duration-300 ${isDropdownOpen ? 'rotate-180' : ''}`} />
                </button>

                {/* Dropdown Menu */}
                {isDropdownOpen && !isSubmitting && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="absolute z-10 w-full mt-2 bg-surface border border-gray-700/30 rounded-xl shadow-2xl max-h-60 overflow-y-auto"
                  >
                    {services.map((service) => (
                      <button
                        key={service}
                        type="button"
                        onClick={() => handleServiceSelect(service)}
                        className="w-full px-4 py-3 text-left text-text hover:bg-primary/10 hover:text-primary transition-all duration-200 first:rounded-t-xl last:rounded-b-xl"
                      >
                        {service}
                      </button>
                    ))}
                  </motion.div>
                )}
              </div>

              {/* Subject Field */}
              <div>
                <label htmlFor="subject" className="block text-text font-medium mb-2">
                  Subject *
                </label>
                <input
                  type="text"
                  id="subject"
                  name="subject"
                  value={formData.subject}
                  onChange={handleChange}
                  required
                  disabled={isSubmitting}
                  className="w-full px-4 py-3 bg-background/50 border border-gray-700/30 rounded-xl text-text placeholder-text/40 focus:outline-none focus:border-primary transition-all duration-300 disabled:opacity-50"
                  placeholder="What is this about?"
                />
              </div>

              {/* Message Field */}
              <div>
                <label htmlFor="message" className="block text-text font-medium mb-2">
                  Message *
                </label>
                <textarea
                  id="message"
                  name="message"
                  value={formData.message}
                  onChange={handleChange}
                  required
                  rows={6}
                  disabled={isSubmitting}
                  className="w-full px-4 py-3 bg-background/50 border border-gray-700/30 rounded-xl text-text placeholder-text/40 focus:outline-none focus:border-primary transition-all duration-300 resize-none disabled:opacity-50"
                  placeholder="Tell me about your project requirements and goals"
                />
              </div>

              {/* Submit Button */}
              <motion.button
                type="submit"
                whileHover={{ scale: isSubmitting ? 1 : 1.02 }}
                whileTap={{ scale: isSubmitting ? 1 : 0.98 }}
                disabled={isSubmitting}
                className="w-full px-8 py-4 bg-linear-to-r from-primary to-secondary text-white rounded-2xl font-semibold text-lg shadow-2xl shadow-primary/25 hover:shadow-primary/40 transition-all duration-300 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" />
                    Sending...
                  </>
                ) : (
                  <>
                    <Send className="w-5 h-5" />
                    Send Message
                  </>
                )}
              </motion.button>

              {/* Form Note */}
              <p className="text-text/50 text-sm text-center">
                I typically respond within 24 hours. Looking forward to connecting with you.
              </p>
            </form>
          </motion.div>
        </div>

        {/* Quick Contact CTA */}
        <motion.div
          initial={{ opacity: 0, y: 40 }}
          animate={isInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
          transition={{ duration: 0.8, delay: 1 }}
          className="text-center mt-20"
        >
          <div className="bg-linear-to-br from-surface/40 to-surface/20 backdrop-blur-sm rounded-3xl p-12 border border-gray-700/10">
            <h3 className="text-3xl font-light text-text mb-4">
              Prefer a <span className="font-semibold text-primary">Quick Chat</span>?
            </h3>
            <p className="text-xl text-text/60 mb-8 max-w-2xl mx-auto leading-relaxed">
              Sometimes a quick conversation is all it takes to get started. Feel free to reach out directly.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center">
              <motion.a
                href="mailto:ranausmaninbox@gmail.com"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="px-8 py-4 bg-primary text-white rounded-2xl font-semibold text-lg shadow-2xl shadow-primary/25 hover:shadow-primary/40 transition-all duration-300"
              >
                Email Me Directly
              </motion.a>
              <motion.a
                href="tel:+923147981434"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                className="px-8 py-4 bg-surface text-text rounded-2xl font-semibold text-lg border border-gray-700/30 hover:border-primary hover:text-primary transition-all duration-300"
              >
                Call Me
              </motion.a>
            </div>
          </div>
        </motion.div>
      </div>
    </section>
  )
}

export default Contact