'use client';

import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import Image from 'next/image';
import { 
  User, 
  Mail, 
  Phone, 
  Globe, 
  GraduationCap, 
  Building2, 
  MapPin,
  Shield,
  Sparkles,
  Zap,
  Award,
  Users,
  Clock,
  Star,
  MessageSquare,
  CheckCircle
} from 'lucide-react';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';
import CustomInput from '../../components/shared/CustomInput';
import CustomSelect from '../../components/shared/CustomSelect';
import PhoneInput from '../../components/shared/PhoneInput';
import SubmitButton from '../../components/shared/SubmitButton';
import FeatureCard from '../../components/shared/FeatureCard';

import free from '../../../../public/assets/free_consulation.png';

// -------------------------
// Types
// -------------------------
type CountryPhone = { id: number; name: string; phonecode: string };
type Option = { label: string; value: string };
type ApiErrorResponse = {
  success: boolean;
  message?: string;
  errors?: Record<string, string[]>;
};

const FreeConsultation = () => {
  // -------------------------
  // Form State
  // -------------------------
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone_number: '',
    last_education: '',
    interested_country: '',
    apply_for: '',
    office_to_visit: ''
  });

  const [countriesWithPhone, setCountriesWithPhone] = useState<CountryPhone[]>([]);
  const [selectedPhoneCode, setSelectedPhoneCode] = useState('92');
  const [isLoading, setIsLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  // -------------------------
  // Fetch Countries with Phone Codes
  // -------------------------
  useEffect(() => {
    const controller = new AbortController();
    const fetchCountriesWithPhone = async () => {
      try {
        const res = await fetch(`/api/frontend/countries-with-phone`, { signal: controller.signal });
        if (!res.ok) throw new Error(`Failed to fetch countries: ${res.status}`);
        const data = await res.json();
        setCountriesWithPhone(data.data || []);
      } catch (err: any) {
        if (err.name === 'AbortError') return;
        console.error('Error fetching countries with phone codes:', err);
        setCountriesWithPhone([]);
      }
    };
    fetchCountriesWithPhone();
    return () => controller.abort();
  }, []);

  // -------------------------
  // Handlers
  // -------------------------
  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    if (fieldErrors[name]) {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    if (fieldErrors[name]) {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handlePhoneCodeChange = (e: any) => {
    setSelectedPhoneCode(e.target.value);
  };

  const handlePhoneInputChange = (e: any) => {
    const { value } = e.target;
    const cleanedValue = value.replace(/\D/g, '');
    setFormData(prev => ({ 
      ...prev, 
      phone_number: cleanedValue
    }));
  };

  const getDisplayPhoneNumber = () => {
    if (!formData.phone_number) return '';
    
    const phoneWithoutZero = formData.phone_number.replace(/^0+/, '');
    
    if (selectedPhoneCode === '92') {
      if (phoneWithoutZero.length <= 3) {
        return `${phoneWithoutZero}`;
      } else {
        return `${phoneWithoutZero.slice(0, 3)} ${phoneWithoutZero.slice(3)}`;
      }
    } else {
      return `${phoneWithoutZero}`;
    }
  };

  // -------------------------
  // Error Display Functions
  // -------------------------
  const displayFieldErrors = (errors: Record<string, string[]>) => {
    setFieldErrors(
      Object.fromEntries(
        Object.entries(errors).map(([field, messages]) => [field, messages[0]])
      )
    );
  };

  const displaySweetAlertError = (errorData: ApiErrorResponse) => {
    if (errorData.errors) {
      const errorMessages = Object.entries(errorData.errors)
        .map(([field, messages]) => `• ${messages.join(', ')}`)
        .join('\n');
      
      Swal.fire({
        title: 'Validation Error',
        html: `<div class="text-left"><p class="mb-3">Please correct the following errors:</p><pre class="text-sm text-red-600 whitespace-pre-wrap">${errorMessages}</pre></div>`,
        icon: 'error',
        confirmButtonText: 'OK',
        customClass: {
          popup: 'rounded-lg',
          confirmButton: 'bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded'
        }
      });
    } else if (errorData.message) {
      Swal.fire({
        title: 'Error',
        text: errorData.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } else {
      Swal.fire({
        title: 'Error',
        text: 'An unexpected error occurred',
        icon: 'error',
        confirmButtonText: 'OK'
      });
    }
  };

  // -------------------------
  // Submit Handler
  // -------------------------
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setFieldErrors({});

    try {
      const payload = {
        ...formData,
        phonecode: `${selectedPhoneCode}`
      };

      const response = await fetch('/api/frontend/free-consultations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data: ApiErrorResponse = await response.json();

      if (!response.ok) {
        if (data.errors) {
          displayFieldErrors(data.errors);
          displaySweetAlertError(data);
        } else {
          const errorMessage = data.message || 'An error occurred while submitting the form';
          Swal.fire({
            title: 'Error',
            text: errorMessage,
            icon: 'error',
            confirmButtonText: 'OK'
          });
        }
      } else {
        Swal.fire({
          title: 'Success!',
          text: data.message || 'Your consultation request has been submitted successfully!',
          icon: 'success',
          confirmButtonText: 'OK',
          timer: 3000,
          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'
          }
        });
        
        setFormData({
          name: '',
          email: '',
          phone_number: '',
          last_education: '',
          interested_country: '',
          apply_for: '',
          office_to_visit: ''
        });
        setSelectedPhoneCode('92');
      }
    } catch (err) {
      console.error('Error submitting form:', err);
      Swal.fire({
        title: 'Network Error',
        text: 'Submission failed. Please check your internet connection and try again.',
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // -------------------------
  // Options
  // -------------------------
  const phoneCodeOptions = countriesWithPhone.map(country => ({
    label: `${country.name} (+${country.phonecode})`,
    value: country.phonecode
  }));

  const educationOptions = ['Matric', 'Intermediate', 'Bachelor', 'Master'];
  const interestedCountryOptions = ['Italy', 'France', 'Turkey', 'China', 'Cyprus', 'Sweden', 'Finland', 'South Korea', 'UK'];
  const officeOptions = ['Lahore', 'Islamabad', 'Karachi', 'Faisalabad'];
  const applyForOptions = ['Study Visa', 'Visit Visa', 'IELTS'];

  // -------------------------
  // Render
  // -------------------------
  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(20)].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() * 100 + 50,
                height: Math.random() * 100 + 50,
                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">
              <Shield className="w-5 h-5" />
              100% Free Consultation
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Get Expert{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Study Abroad
              </span>{' '}
              <br />
              Guidance — Free!
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Our expert consultants will help you choose the right country, program, and university, 
              while guiding you through every step of the admission and visa process.
            </p>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Why Students Choose Us
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Proven track record of helping students achieve their study abroad dreams
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCard 
              Icon={Award}
              number="95%"
              label="Visa Success Rate"
              color="teal"
            />
            <StatCard 
              Icon={Users}
              number="10K+"
              label="Happy Students"
              color="blue"
            />
            <StatCard 
              Icon={Clock}
              number="24"
              label="Hour Response Time"
              color="emerald"
            />
            <StatCard 
              Icon={Star}
              number="4.9"
              label="Customer Rating"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <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-3xl font-bold text-gray-900">Fill in your details</h2>
                  <p className="text-gray-600 mt-2">
                    Complete the form below and our team will contact you within 24 hours
                  </p>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid md:grid-cols-2 gap-6">
                  <CustomInput 
                    Icon={User}
                    placeholder="Enter Your Name" 
                    name="name" 
                    value={formData.name} 
                    onChange={handleChange}
                    error={fieldErrors.name}
                  />
                  
                  <CustomInput 
                    Icon={Mail}
                    placeholder="Enter Your Email" 
                    type="email"
                    name="email" 
                    value={formData.email} 
                    onChange={handleChange}
                    error={fieldErrors.email}
                  />
                  
                  <PhoneInput
                    phoneCodeOptions={phoneCodeOptions}
                    selectedPhoneCode={selectedPhoneCode}
                    onPhoneCodeChange={handlePhoneCodeChange}
                    phoneNumber={formData.phone_number}
                    onPhoneNumberChange={handlePhoneInputChange}
                    getDisplayPhoneNumber={getDisplayPhoneNumber}
                    error={fieldErrors.phone_number}
                  />

                  <CustomSelect 
                    Icon={GraduationCap}
                    name="last_education" 
                    value={formData.last_education} 
                    onChange={handleSelectChange} 
                    options={educationOptions} 
                    placeholder="Select Last Education"
                    error={fieldErrors.last_education}
                  />

                  <CustomSelect 
                    Icon={Globe}
                    name="interested_country" 
                    value={formData.interested_country} 
                    onChange={handleSelectChange} 
                    options={interestedCountryOptions} 
                    placeholder="Select Interested Country"
                    error={fieldErrors.interested_country}
                  />

                  <CustomSelect 
                    Icon={Building2}
                    name="apply_for" 
                    value={formData.apply_for} 
                    onChange={handleSelectChange} 
                    options={applyForOptions} 
                    placeholder="Select Apply For"
                    error={fieldErrors.apply_for}
                  />

                  <CustomSelect 
                    Icon={MapPin}
                    name="office_to_visit" 
                    value={formData.office_to_visit} 
                    onChange={handleSelectChange} 
                    options={officeOptions} 
                    placeholder="Select Office to Visit"
                    error={fieldErrors.office_to_visit}
                  />
                </div>

                <SubmitButton isLoading={isLoading} />

                <p className="text-center text-gray-500 text-sm">
                  By submitting this form, you agree to our Privacy Policy and Terms of Service
                </p>
              </form>
            </ModernCard>

            {/* Image & Features Section */}
            <div className="space-y-8">
              {/* Image Card */}
              <ModernCard className="overflow-hidden">
                <div className="relative h-64 md:h-80">
                  <Image
                    src={free}
                    alt="Education Consultation"
                    fill
                    className="object-cover"
                    priority
                  />
                  <div className="absolute inset-0 bg-linear-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">Personalized Guidance</h3>
                      <p className="text-white/90 text-sm">Tailored solutions for your study abroad journey</p>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* Features Grid */}
              <div className="grid sm:grid-cols-2 gap-6">
                <FeatureCard
                  Icon={CheckCircle}
                  title="Expert Advisors"
                  description="Certified education consultants with years of experience"
                  color="teal"
                />

                <FeatureCard
                  Icon={Zap}
                  title="Fast Processing"
                  description="Quick turnaround time for all your applications"
                  color="blue"
                />

                <FeatureCard
                  Icon={Shield}
                  title="Secure Process"
                  description="Your information is protected and confidential"
                  color="emerald"
                />

                <FeatureCard
                  Icon={Users}
                  title="Multiple Locations"
                  description="Visit our offices in major cities across Pakistan"
                  color="amber"
                />
              </div>

              {/* CTA Card */}
              <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-8 text-center">
                <h3 className="text-2xl font-bold text-white mb-4">Still Have Questions?</h3>
                <p className="text-white/80 mb-6">Contact us directly for immediate assistance</p>
                <div className="flex flex-col sm:flex-row gap-4 justify-center">
                  <a 
                    href="tel:+923330033235" 
                    className="inline-flex items-center justify-center gap-2 bg-white/20 backdrop-blur-sm text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/30 transition-all duration-300"
                  >
                    <Phone className="w-4 h-4" />
                    Call Now
                  </a>
                  <a 
                    href="mailto:info@universitiespage.com" 
                    className="inline-flex items-center justify-center gap-2 border-2 border-white/30 text-white font-semibold py-3 px-6 rounded-xl hover:bg-white/10 transition-all duration-300"
                  >
                    <Mail className="w-4 h-4" />
                    Email Us
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      
    </div>
  );
};

export default FreeConsultation;