'use client';

import { useState, FormEvent } from 'react';
import { 
  User, 
  Globe, 
  AlertCircle, 
  Mail, 
  Phone, 
  MessageSquare, 
  FileText, 
  Send,
  Sparkles,
  Shield,
  CheckCircle,
  Clock,
  MapPin,
  ChevronRight,
  Info
} from 'lucide-react';
import Swal from 'sweetalert2';
import Image from "next/image";

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import CustomInput from '../../components/shared/CustomInput';
import FeatureCard from '../../components/shared/FeatureCard';

interface FormData {
  name: string;
  email: string;
  subject: string;
  phone: string;
  location: string;
  message: string;
}

interface FormErrors {
  name?: string;
  email?: string;
  subject?: string;
  phone?: string;
  location?: string;
  message?: string;
}

const Complaint = () => {
  const [formData, setFormData] = useState<FormData>({
    name: '',
    email: '',
    subject: '',
    phone: '',
    location: '',
    message: ''
  });
  
  const [errors, setErrors] = useState<FormErrors>({});
  const [loading, setLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    
    // Clear error when user starts typing
    if (errors[name as keyof FormErrors]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  };

  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};
    
    if (!formData.name.trim()) {
      newErrors.name = '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.subject.trim()) {
      newErrors.subject = 'Subject is required';
    }
    
    if (!formData.phone.trim()) {
      newErrors.phone = 'Phone number is required';
    }
    
    if (!formData.location) {
      newErrors.location = 'Please select your location';
    }
    
    if (!formData.message.trim()) {
      newErrors.message = 'Please provide details about your complaint or suggestion';
    } else if (formData.message.trim().length < 10) {
      newErrors.message = 'Please provide more details (minimum 10 characters)';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      Swal.fire({
        icon: 'warning',
        title: 'Please check your information',
        text: 'Some fields require your attention',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    setLoading(true);

    try {
      const res = await fetch('/api/frontend/complaints', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });

      const data = await res.json();

      if (res.ok && data.success) {
        // Reset form
        setFormData({
          name: '',
          email: '',
          subject: '',
          phone: '',
          location: '',
          message: ''
        });

        Swal.fire({
          icon: 'success',
          title: 'Thank You for Your Feedback!',
          text: 'Your complaint/suggestion has been submitted successfully. We will review it and get back to you shortly.',
          confirmButtonColor: '#10B981',
          timer: 4000,
          background: '#ffffff',
          color: '#1f2937',
          customClass: {
            confirmButton: 'bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-3 rounded-xl font-semibold'
          }
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Submission Failed',
          text: data.message || 'There was an issue submitting your feedback. Please try again.',
          confirmButtonColor: '#EF4444'
        });
      }
    } catch (error) {
      console.error('Error submitting form:', error);
      Swal.fire({
        icon: 'error',
        title: 'Connection Error',
        text: 'Unable to connect to the server. Please check your internet connection and try again.',
        confirmButtonColor: '#EF4444'
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(15)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 80 + 40,
                height: Math.random() * 80 + 40,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <MessageSquare className="w-5 h-5" />
              Your Voice Matters
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Share Your{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Feedback
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Your opinion matters to us. Whether you have a complaint or a suggestion, 
              we`re here to listen and improve our services.
            </p>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20">
        <div className="grid lg:grid-cols-2 gap-12 items-start">
          {/* Form Section */}
          <ModernCard className="p-8">
            <div className="flex items-center gap-4 mb-8">
              <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                <MessageSquare className="w-8 h-8 text-teal-600" />
              </div>
              <div>
                <h2 className="text-2xl font-bold text-gray-900">Submit Your Feedback</h2>
                <p className="text-gray-600 mt-2">
                  Fill in the details below and we`ll get back to you shortly
                </p>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="grid md:grid-cols-2 gap-6">
                <CustomInput 
                  Icon={User}
                  placeholder="Your Full Name" 
                  name="name" 
                  value={formData.name} 
                  onChange={handleChange}
                  error={errors.name}
                  required
                />
                
                <CustomInput 
                  Icon={Mail}
                  placeholder="Your Email Address" 
                  type="email"
                  name="email" 
                  value={formData.email} 
                  onChange={handleChange}
                  error={errors.email}
                  required
                />
                
                <CustomInput 
                  Icon={Phone}
                  placeholder="Phone Number" 
                  name="phone"
                  value={formData.phone} 
                  onChange={handleChange}
                  error={errors.phone}
                  required
                />

                {/* Location Select */}
                <div className="relative">
                  <div className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 z-10">
                    <MapPin className="w-5 h-5" />
                  </div>
                  <select
                    name="location"
                    value={formData.location}
                    onChange={handleChange}
                    className={`w-full pl-12 pr-4 py-4 bg-white border-2 ${
                      errors.location ? 'border-red-300' : 'border-gray-200'
                    } rounded-2xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-gray-700 appearance-none cursor-pointer`}
                    required
                  >
                    <option value="">Select Your Location</option>
                    <option value="lahore">Lahore Office</option>
                    <option value="islamabad">Islamabad Office</option>
                    <option value="karachi">Karachi Office</option>
                    <option value="faisalabad">Faisalabad Office</option>
                  </select>
                  <div className="absolute right-4 top-1/2 transform -translate-y-1/2 pointer-events-none">
                    <ChevronRight className="w-5 h-5 text-gray-400 rotate-90" />
                  </div>
                  {errors.location && (
                    <p className="text-red-500 text-sm mt-2 pl-4">{errors.location}</p>
                  )}
                </div>
              </div>

              <CustomInput 
                Icon={FileText}
                placeholder="Subject of Your Feedback" 
                name="subject"
                value={formData.subject} 
                onChange={handleChange}
                error={errors.subject}
                required
              />

              {/* Message Textarea */}
              <div className="relative">
                <div className="absolute left-4 top-4 text-gray-400 z-10">
                  <MessageSquare className="w-5 h-5" />
                </div>
                <textarea
                  name="message"
                  placeholder="Please describe your complaint or suggestion in detail..."
                  value={formData.message}
                  onChange={handleChange}
                  rows={4}
                  className={`w-full pl-12 pr-4 py-4 bg-white border-2 ${
                    errors.message ? 'border-red-300' : 'border-gray-200'
                  } rounded-2xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent text-gray-700 resize-none`}
                  required
                />
                {errors.message && (
                  <p className="text-red-500 text-sm mt-2 pl-4">{errors.message}</p>
                )}
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={loading}
                className="w-full group/btn cursor-pointer bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold py-5 px-8 rounded-2xl hover:shadow-xl transition-all duration-300 flex items-center justify-center gap-3 disabled:opacity-50 transform hover:-translate-y-1"
              >
                {loading ? (
                  <>
                    <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    <span>Submitting...</span>
                  </>
                ) : (
                  <>
                    <Send className="w-5 h-5" />
                    <span>Submit Feedback</span>
                    <ChevronRight className="w-5 h-5 transition-transform duration-300 group-hover/btn:translate-x-1" />
                  </>
                )}
              </button>

              <div className="flex items-center justify-center text-sm text-gray-500">
                <Shield className="w-4 h-4 text-teal-600 mr-2" />
                <span>Your information is secure and confidential</span>
              </div>
            </form>
          </ModernCard>

          {/* Information Section */}
          <div className="space-y-8">
            {/* Why Feedback Matters */}
            <ModernCard className="p-8">
              <div className="flex items-center gap-4 mb-6">
                <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                  <Info className="w-8 h-8 text-teal-600" />
                </div>
                <h3 className="text-2xl font-bold text-gray-900">Why Your Feedback Matters</h3>
              </div>
              
              <div className="space-y-4">
                <FeatureCard
                  Icon={AlertCircle}
                  title="Improve Our Services"
                  description="Helps us address issues promptly and enhance service quality"
                  color="teal"
                />

                <FeatureCard
                  Icon={Sparkles}
                  title="Drive Innovation"
                  description="Your suggestions might lead to new features and improvements"
                  color="blue"
                />

                <FeatureCard
                  Icon={Shield}
                  title="Better Experience"
                  description="We're committed to providing the best possible experience"
                  color="emerald"
                />
              </div>
            </ModernCard>

            {/* What Happens Next */}
            <ModernCard className="p-8">
              <div className="flex items-center gap-4 mb-6">
                <div className="p-3 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 border border-teal-100">
                  <Clock className="w-8 h-8 text-teal-600" />
                </div>
                <h3 className="text-2xl font-bold text-gray-900">What Happens Next?</h3>
              </div>
              
              <div className="space-y-4">
                <div className="flex items-start gap-4 p-4 bg-gray-50 rounded-xl">
                  <div className="flex-shrink-0 w-10 h-10 bg-linear-to-r from-teal-600 to-blue-500 rounded-full flex items-center justify-center">
                    <span className="text-white font-bold text-sm">1</span>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-1">Feedback Received</h4>
                    <p className="text-sm text-gray-600">Your feedback is logged in our system</p>
                  </div>
                </div>

                <div className="flex items-start gap-4 p-4 bg-gray-50 rounded-xl">
                  <div className="flex-shrink-0 w-10 h-10 bg-linear-to-r from-teal-600 to-blue-500 rounded-full flex items-center justify-center">
                    <span className="text-white font-bold text-sm">2</span>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-1">Team Review</h4>
                    <p className="text-sm text-gray-600">Our team reviews it within 24-48 business hours</p>
                  </div>
                </div>

                <div className="flex items-start gap-4 p-4 bg-gray-50 rounded-xl">
                  <div className="flex-shrink-0 w-10 h-10 bg-linear-to-r from-teal-600 to-blue-500 rounded-full flex items-center justify-center">
                    <span className="text-white font-bold text-sm">3</span>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-1">Follow-up</h4>
                    <p className="text-sm text-gray-600">We`ll contact you if we need additional information</p>
                  </div>
                </div>

                <div className="flex items-start gap-4 p-4 bg-gray-50 rounded-xl">
                  <div className="flex-shrink-0 w-10 h-10 bg-linear-to-r from-teal-600 to-blue-500 rounded-full flex items-center justify-center">
                    <span className="text-white font-bold text-sm">4</span>
                  </div>
                  <div>
                    <h4 className="font-semibold text-gray-900 mb-1">Response & Action</h4>
                    <p className="text-sm text-gray-600">You`ll receive a response outlining any actions taken</p>
                  </div>
                </div>
              </div>
            </ModernCard>

            {/* Image Section */}
            <ModernCard className="overflow-hidden">
              <div className="relative h-64 md:h-80">
                <Image
                  src="/assets/comp.png"
                  alt="Customer feedback illustration"
                  fill
                  className="object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent"></div>
                <div className="absolute bottom-6 left-6 right-6">
                  <div className="bg-white/20 backdrop-blur-lg rounded-xl p-4 border border-white/30">
                    <h3 className="text-xl font-bold text-white mb-2">We Value Every Voice</h3>
                    <p className="text-white/90 text-sm">Committed to continuous improvement based on your feedback</p>
                  </div>
                </div>
              </div>
            </ModernCard>
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-12 text-center shadow-2xl">
            <h3 className="text-3xl md:text-4xl font-bold text-white mb-6">
              Need Immediate Assistance?
            </h3>
            <p className="text-white/90 text-lg md:text-xl mb-8 max-w-2xl mx-auto leading-relaxed">
              For urgent matters, contact our support team directly for immediate help.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <a 
                href="tel:+923330033235" 
                className="px-8 py-4 bg-white cursor-pointer text-teal-700 font-semibold rounded-2xl hover:bg-gray-100 transition-all duration-300 transform hover:-translate-y-1 shadow-lg text-lg"
              >
                <span className="flex items-center gap-2">
                  <Phone className="w-5 h-5" />
                  Call Support
                </span>
              </a>
              <a 
                href="mailto:support@example.com" 
                className="px-8 py-4 bg-transparent border-2 cursor-pointer border-white text-white font-semibold rounded-2xl hover:bg-white hover:text-teal-700 transition-all duration-300 transform hover:-translate-y-1 text-lg"
              >
                <span className="flex items-center gap-2">
                  <Mail className="w-5 h-5" />
                  Email Support
                </span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Complaint;