'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,
  Percent,
  BookOpen,
  Heart,
  Target
} 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';

// -------------------------
// Types - KEPT SAME
// -------------------------
type CountryPhone = { id: number; name: string; phonecode: string };
type Option = { label: string; value: string };
type ApiErrorResponse = {
  success: boolean;
  message?: string;
  errors?: Array<{ field: string; message: string }>; // KEPT SAME STRUCTURE
};

const DiscountOfferPage = () => {
  // -------------------------
  // Form State - KEPT SAME
  // -------------------------
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    lastEducationPer: '',
    phone: '', // KEPT as 'phone' not 'phone_number'
    lastEducation: '', // KEPT as 'lastEducation' not 'last_education'
    location: '',
    familyDetail: ''
  });

  const [countriesWithPhone, setCountriesWithPhone] = useState<CountryPhone[]>([]);
  const [selectedPhoneCode, setSelectedPhoneCode] = useState('92');
  const [isLoading, setIsLoading] = useState(false);
  const [apiErrors, setApiErrors] = useState<Array<{ field: string; message: string }>>([]); // KEPT SAME

  // -------------------------
  // Fetch Countries with Phone Codes - KEPT SAME
  // -------------------------
  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 - KEPT SAME FUNCTIONALITY
  // -------------------------
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear API errors when user starts typing - KEPT SAME
    if (apiErrors.length > 0) {
      setApiErrors([]);
    }
  };

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear API errors when user starts typing
    if (apiErrors.length > 0) {
      setApiErrors([]);
    }
  };

  const handlePhoneCodeChange = (e: any) => {
    setSelectedPhoneCode(e.target.value);
  };

  // Handle phone input with country code - KEPT SAME
  const handlePhoneInputChange = (e: any) => {
    const { value } = e.target;
    
    // Remove any non-digit characters
    const cleanedValue = value.replace(/\D/g, '');
    
    // Update the form data with raw digits
    setFormData(prev => ({ 
      ...prev, 
      phone: cleanedValue
    }));
  };

  // Format phone number for display - KEPT SAME
  const getDisplayPhoneNumber = () => {
    if (!formData.phone) return '';
    
    const phoneWithoutZero = formData.phone.replace(/^0+/, '');
    
    if (selectedPhoneCode === '92') {
      // Pakistani format: 300 1234567
      if (phoneWithoutZero.length <= 3) {
        return `${phoneWithoutZero}`;
      } else {
        return `${phoneWithoutZero.slice(0, 3)} ${phoneWithoutZero.slice(3)}`;
      }
    } else {
      // Other country format
      return `${phoneWithoutZero}`;
    }
  };

  // -------------------------
  // Error Display Function - KEPT SAME
  // -------------------------
  const renderError = (field: string) => {
    const apiError = apiErrors.find(error => error.field === field);
    if (apiError) {
      return <p className="text-red-500 text-sm mt-1">{apiError.message}</p>;
    }
    
    return null;
  };

  // -------------------------
  // Submit Handler - KEPT SAME
  // -------------------------
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setApiErrors([]);

    try {
      const payload = {
        ...formData,
        phonecode: selectedPhoneCode,
      };

      const response = await fetch('/api/frontend/discount-offers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data: ApiErrorResponse = await response.json();

      if (data.success) {
        setFormData({
          name: '',
          email: '',
          lastEducationPer: '',
          phone: '',
          lastEducation: '',
          location: '',
          familyDetail: ''
        });
        setSelectedPhoneCode('92');

        Swal.fire({
          title: 'Success!',
          text: 'Your discount offer application 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'
          }
        });
      } else {
        // Handle validation errors from backend - KEPT SAME
        if (data.errors && data.errors.length > 0) {
          setApiErrors(data.errors);
          
          const errorMessages = data.errors.map(error => 
            `• ${error.field}: ${error.message}`
          ).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 {
          Swal.fire({
            title: 'Submission Failed',
            text: data.message || 'Please try again later.',
            icon: 'error',
            confirmButtonText: 'OK'
          });
        }
      }
    } catch (error) {
      console.error('Error submitting form:', error);
      Swal.fire({
        title: 'Error Occurred',
        text: 'Something went wrong. Please try again.',
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // -------------------------
  // Options - KEPT SAME
  // -------------------------
  const phoneCodeOptions = countriesWithPhone.map(country => ({
    label: `${country.name} (+${country.phonecode})`,
    value: country.phonecode
  }));

  const educationOptions = ['Matric', 'Intermediate', 'Bachelor', 'Master'];
  const officeOptions = ['Lahore', 'Islamabad', 'Karachi', 'Faisalabad'];

  // -------------------------
  // Render - ONLY DESIGN CHANGED
  // -------------------------
  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section - NEW DESIGN */}
      <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">
              <Percent className="w-5 h-5" />
              100% Discount Offer
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Financial Support for{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Deserving Students
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Our special discount program supports talented students from financially challenged families 
              to pursue their study abroad dreams without financial barriers.
            </p>
          </div>
        </div>
      </div>

      {/* Stats Section - NEW DESIGN */}
      <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">
              Our Impact in Numbers
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Helping students achieve their study abroad dreams regardless of financial background
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <StatCard 
              Icon={Heart}
              number="100%"
              label="Fee Waiver"
              color="teal"
            />
            <StatCard 
              Icon={Users}
              number="500+"
              label="Students Supported"
              color="blue"
            />
            <StatCard 
              Icon={Target}
              number="95%"
              label="Success Rate"
              color="emerald"
            />
            <StatCard 
              Icon={Award}
              number="30+"
              label="Years Experience"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* Information Section - UPDATED DESIGN */}
      <div className="py-16 bg-linear-to-b from-white to-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Main Form Section - UPDATED DESIGN */}
          <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">
                  <Percent className="w-8 h-8 text-teal-600" />
                </div>
                <div>
                  <h2 className="text-3xl font-bold text-gray-900">Apply for Discount</h2>
                  <p className="text-gray-600 mt-2">
                    Fill the form below to apply for our 100% discount program
                  </p>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                <div className="grid md:grid-cols-2 gap-6">
                  {/* Name Input (First in row) */}
                  <div className="md:col-span-1">
                    <CustomInput 
                      Icon={User}
                      placeholder="Enter Your Name" 
                      name="name" 
                      value={formData.name} 
                      onChange={handleChange}
                    />
                    {renderError('name')}
                  </div>
                  
                  {/* Email Input (Second in row, same row as Name) */}
                  <div className="md:col-span-1">
                    <CustomInput 
                      Icon={Mail}
                      placeholder="Enter Your Email" 
                      type="email"
                      name="email" 
                      value={formData.email} 
                      onChange={handleChange}
                    />
                    {renderError('email')}
                  </div>
                  
                  {/* Phone Number (First in second row) */}
                  <div className="md:col-span-1">
                    <div className="relative">
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Phone Number
                      </label>
                      <div className="flex items-center rounded-xl border border-gray-300 focus-within:ring-2 focus-within:ring-teal-200 focus-within:border-teal-500 transition-all duration-300 overflow-hidden">
                        {/* Country Code Selector */}
                        <div className="relative shrink-0">
                          <div className="absolute left-4 top-1/2 transform -translate-y-1/2">
                            <Globe className="w-4 h-4 text-gray-400" />
                          </div>
                          <select
                            name="phone_code"
                            value={selectedPhoneCode}
                            onChange={handlePhoneCodeChange}
                            className="pl-12 pr-8 py-3.5 border-0 text-sm text-gray-700 focus:outline-none appearance-none cursor-pointer bg-gray-50 focus:bg-white"
                            style={{ 
                              WebkitAppearance: 'none',
                              MozAppearance: 'none',
                            }}
                          >
                            {phoneCodeOptions.map((option, id) => (
                              <option key={id} value={option.value}>
                                +{option.value}
                              </option>
                            ))}
                          </select>
                          <div className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none">
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7"></path>
                            </svg>
                          </div>
                          <div className="absolute right-0 top-1/2 transform -translate-y-1/2 h-6 w-px bg-gray-300"></div>
                        </div>
                        
                        {/* Phone Number Input */}
                        <div className="grow">
                          <input
                            type="tel"
                            placeholder="Phone Number"
                            value={getDisplayPhoneNumber()}
                            onChange={handlePhoneInputChange}
                            className="w-full pl-4 pr-4 py-3.5 border-0 text-sm text-gray-700 placeholder-gray-500 focus:outline-none focus:ring-0"
                            required
                          />
                        </div>
                      </div>
                      {renderError('phone')}
                    </div>
                  </div>

                  {/* Last Education (Second in second row, same row as Phone) */}
                  <div className="md:col-span-1">
                    <CustomSelect 
                      Icon={GraduationCap}
                      name="lastEducation" 
                      value={formData.lastEducation} 
                      onChange={handleSelectChange} 
                      options={educationOptions} 
                      placeholder="Select Last Education"
                    />
                    {renderError('lastEducation')}
                  </div>

                  {/* Percentage (First in third row) */}
                  <div className="md:col-span-1">
                    <CustomInput 
                      Icon={Percent}
                      placeholder="Percentage (0-100)" 
                      name="lastEducationPer" 
                      value={formData.lastEducationPer} 
                      onChange={handleChange}
                    />
                    {renderError('lastEducationPer')}
                  </div>
                  
                  {/* Office Location (Second in third row, same row as Percentage) */}
                  <div className="md:col-span-1">
                    <CustomSelect 
                      Icon={MapPin}
                      name="location" 
                      value={formData.location} 
                      onChange={handleSelectChange} 
                      options={officeOptions} 
                      placeholder="Select Office Location"
                    />
                    {renderError('location')}
                  </div>
                </div>
                
                {/* Family Detail Textarea */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Tell us about your background and why you deserve this discount...
                  </label>
                  <textarea
                    name="familyDetail"
                    value={formData.familyDetail}
                    onChange={handleChange}
                    placeholder="Share your story..."
                    className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:border-teal-500 focus:ring-2 focus:ring-teal-200 focus:outline-none transition-all duration-300 resize-none h-32"
                  />
                  {renderError('familyDetail')}
                </div>
                
                {/* Submit Button */}
                <button 
                  type="submit" 
                  disabled={isLoading}
                  className="w-full bg-linear-to-r from-teal-600 to-blue-500 text-white font-semibold py-3 px-6 rounded-xl hover:opacity-90 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? (
                    <div className="flex items-center justify-center gap-2">
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      Processing...
                    </div>
                  ) : (
                    'Submit Application'
                  )}
                </button>
              </form>
            </ModernCard>

            {/* Image & Features Section - NEW DESIGN */}
            <div className="space-y-8">
              {/* Image Card */}
              <ModernCard className="overflow-hidden">
                <div className="relative h-64 md:h-80">
                  <Image
                    src="/assets/do4.png"
                    alt="Discount Offer"
                    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">Why Apply for Discount?</h3>
                      <p className="text-white/90 text-sm">Tailored support for deserving students</p>
                    </div>
                  </div>
                </div>
              </ModernCard>

              {/* Features Grid */}
              <div className="grid sm:grid-cols-2 gap-6">
                <FeatureCard
                  Icon={Heart}
                  title="Financial Support"
                  description="100% discount on consultancy fees for deserving students"
                  color="teal"
                />

                <FeatureCard
                  Icon={BookOpen}
                  title="Expert Guidance"
                  description="Professional counseling for study abroad opportunities"
                  color="blue"
                />

                <FeatureCard
                  Icon={Shield}
                  title="Secure Process"
                  description="Your information is protected and confidential"
                  color="emerald"
                />

                <FeatureCard
                  Icon={Zap}
                  title="Quick Processing"
                  description="Fast turnaround time for application reviews"
                  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">Need More Information?</h3>
                <p className="text-white/80 mb-6">Contact us directly for program details</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 DiscountOfferPage;