'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Loader2, CheckCircle } from 'lucide-react';
import toast from 'react-hot-toast';

interface AuditModalProps {
  isOpen: boolean;
  onClose: () => void;
}

// Expanded industries list to cover more categories
const industries = [
  'E-commerce & Retail',
  'SaaS & Software',
  'Marketing & Advertising Agency',
  'Healthcare & Medical',
  'Finance & Banking',
  'Insurance',
  'Education & E-learning',
  'Real Estate',
  'Travel & Tourism',
  'Hospitality & Restaurants',
  'Technology & IT Services',
  'Manufacturing',
  'Construction & Engineering',
  'Legal Services',
  'Consulting & Business Services',
  'Non-profit & Organizations',
  'Fitness & Wellness',
  'Beauty & Cosmetics',
  'Automotive',
  'Energy & Utilities',
  'Agriculture',
  'Logistics & Transportation',
  'Media & Entertainment',
  'Sports & Recreation',
  'Home Services',
  'B2B Services',
  'Startup',
  'Other'
];

const trafficRanges = [
  'Less than 1k',
  '1k-10k',
  '10k-50k',
  '50k-100k',
  '100k-500k',
  '500k-1M',
  '1M+'
];

const goalsOptions = [
  'Increase Organic Traffic',
  'Improve Domain Authority',
  'Generate More Leads',
  'Boost Brand Awareness',
  'Outrank Competitors',
  'Increase Sales/Revenue',
  'Build Quality Backlinks',
  'Improve Search Rankings',
  'Expand to New Markets',
  'Establish Thought Leadership'
];

export default function AuditModal({ isOpen, onClose }: AuditModalProps) {
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    website: '',
    company: '',
    industry: '',
    monthlyTraffic: '',
    goals: [] as string[],
  });
  
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    // Required field validation
    if (!formData.fullName.trim()) {
      newErrors.fullName = 'Full name is required';
    }

    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }

    if (!formData.website.trim()) {
      newErrors.website = 'Website URL is required';
    } else if (!/^https?:\/\/.+\..+/.test(formData.website)) {
      newErrors.website = 'Please enter a valid website URL (include http:// or https://)';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      toast.error('Please fix the errors in the form');
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await fetch('/api/frontend/audit-leads', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      const result = await response.json();

      if (response.ok) {
        toast.success('Audit request submitted successfully! We\'ll contact you within 24 hours.');
        setIsSuccess(true);
        setTimeout(() => {
          onClose();
          setIsSuccess(false);
          setFormData({
            fullName: '',
            email: '',
            website: '',
            company: '',
            industry: '',
            monthlyTraffic: '',
            goals: [],
          });
          setErrors({});
        }, 2000);
      } else {
        // Handle specific API errors
        if (response.status === 409) {
          toast.error(result.error || 'You have already submitted an audit request with this email and website');
        } else if (response.status === 400) {
          toast.error(result.error || 'Please check your form data');
        } else {
          toast.error(result.error || 'Something went wrong! Please try again.');
        }
      }
    } catch (error) {
      console.error('Error submitting form:', error);
      toast.error('Failed to submit. Please check your connection and try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleGoalToggle = (goal: string) => {
    setFormData(prev => ({
      ...prev,
      goals: prev.goals.includes(goal)
        ? prev.goals.filter(g => g !== goal)
        : [...prev.goals, goal]
    }));
  };

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-100 flex items-center justify-center">
        {/* Backdrop */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="absolute inset-0 bg-black/60 backdrop-blur-sm"
          onClick={onClose}
        />
        
        {/* Modal */}
        <motion.div
          initial={{ opacity: 0, scale: 0.9, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.9, y: 20 }}
          className="relative bg-surface border border-white/10 rounded-2xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto"
        >
          {isSuccess ? (
            <div className="p-8 text-center bg-surface">
              <CheckCircle className="h-16 w-16 text-success-500 mx-auto mb-4" />
              <h3 className="text-2xl font-bold text-text-primary mb-2">
                Thank You!
              </h3>
              <p className="text-text-secondary mb-6">
                Your free audit request has been received. We`ll contact you within 24 hours.
              </p>
            </div>
          ) : (
            <>
              {/* Header */}
              <div className="flex items-center justify-between p-6 border-b border-white/10 bg-surface">
                <div>
                  <h2 className="text-2xl font-bold text-text-primary">
                    Get Your Free SEO Audit
                  </h2>
                  <p className="text-text-secondary mt-1">
                    Complete the form below and we`ll analyze your website
                  </p>
                </div>
                <button
                  onClick={onClose}
                  className="p-2 hover:bg-primary-500/10 rounded-lg transition-colors duration-200"
                >
                  <X className="h-5 w-5 text-text-primary" />
                </button>
              </div>

              {/* Form */}
              <form onSubmit={handleSubmit} className="p-6 space-y-6 bg-surface">
                {/* Full Name */}
                <div>
                  <label className="block text-sm font-medium text-text-primary mb-2">
                    Full Name *
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.fullName}
                    onChange={(e) => handleInputChange('fullName', e.target.value)}
                    className={`w-full px-4 py-3 bg-white dark:bg-gray-800 border rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 ${
                      errors.fullName 
                        ? 'border-red-500 dark:border-red-400' 
                        : 'border-gray-300 dark:border-gray-600'
                    }`}
                    placeholder="Enter your full name"
                  />
                  {errors.fullName && (
                    <p className="mt-1 text-sm text-red-500 dark:text-red-400">{errors.fullName}</p>
                  )}
                </div>

                {/* Email */}
                <div>
                  <label className="block text-sm font-medium text-text-primary mb-2">
                    Work Email *
                  </label>
                  <input
                    type="email"
                    required
                    value={formData.email}
                    onChange={(e) => handleInputChange('email', e.target.value)}
                    className={`w-full px-4 py-3 bg-white dark:bg-gray-800 border rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 ${
                      errors.email 
                        ? 'border-red-500 dark:border-red-400' 
                        : 'border-gray-300 dark:border-gray-600'
                    }`}
                    placeholder="your@company.com"
                  />
                  {errors.email && (
                    <p className="mt-1 text-sm text-red-500 dark:text-red-400">{errors.email}</p>
                  )}
                </div>

                {/* Website */}
                <div>
                  <label className="block text-sm font-medium text-text-primary mb-2">
                    Website URL *
                  </label>
                  <input
                    type="url"
                    required
                    value={formData.website}
                    onChange={(e) => handleInputChange('website', e.target.value)}
                    className={`w-full px-4 py-3 bg-white dark:bg-gray-800 border rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 ${
                      errors.website 
                        ? 'border-red-500 dark:border-red-400' 
                        : 'border-gray-300 dark:border-gray-600'
                    }`}
                    placeholder="https://example.com"
                  />
                  {errors.website && (
                    <p className="mt-1 text-sm text-red-500 dark:text-red-400">{errors.website}</p>
                  )}
                </div>

                {/* Company & Industry */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-text-primary mb-2">
                      Company Name
                    </label>
                    <input
                      type="text"
                      value={formData.company}
                      onChange={(e) => handleInputChange('company', e.target.value)}
                      className="w-full px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
                      placeholder="Your company name"
                    />
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-text-primary mb-2">
                      Industry
                    </label>
                    <select
                      value={formData.industry}
                      onChange={(e) => handleInputChange('industry', e.target.value)}
                      className="w-full px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100"
                    >
                      <option value="">Select Industry</option>
                      {industries.map(industry => (
                        <option key={industry} value={industry}>{industry}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Monthly Traffic */}
                <div>
                  <label className="block text-sm font-medium text-text-primary mb-2">
                    Current Monthly Traffic
                  </label>
                  <select
                    value={formData.monthlyTraffic}
                    onChange={(e) => handleInputChange('monthlyTraffic', e.target.value)}
                    className="w-full px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200 text-gray-900 dark:text-gray-100"
                  >
                    <option value="">Select Traffic Range</option>
                    {trafficRanges.map(traffic => (
                      <option key={traffic} value={traffic}>{traffic}</option>
                    ))}
                  </select>
                </div>

                {/* Goals */}
                <div>
                  <label className="block text-sm font-medium text-text-primary mb-3">
                    What are your main goals? (Select all that apply)
                  </label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    {goalsOptions.map(goal => (
                      <label 
                        key={goal} 
                        className="flex items-center space-x-3 p-3 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-xl hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors duration-200 cursor-pointer"
                      >
                        <input
                          type="checkbox"
                          checked={formData.goals.includes(goal)}
                          onChange={() => handleGoalToggle(goal)}
                          className="h-4 w-4 text-blue-500 focus:ring-blue-500 border-gray-300 dark:border-gray-500 rounded"
                        />
                        <span className="text-gray-900 dark:text-gray-100 text-sm">{goal}</span>
                      </label>
                    ))}
                  </div>
                </div>

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="w-full btn-primary py-4 text-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="h-5 w-5 animate-spin" />
                      Submitting...
                    </>
                  ) : (
                    'Get Free SEO Audit'
                  )}
                </button>
              </form>
            </>
          )}
        </motion.div>
      </div>
    </AnimatePresence>
  );
}