'use client';

import { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import { useUserStore } from '../../../store/useUserStore';
import { 
  X, 
  User, 
  Mail, 
  Phone, 
  Lock, 
  MapPin, 
  GraduationCap,
  CheckCircle,
  Eye,
  EyeOff,
  Globe,
  CreditCard,
  DollarSign,
  Calendar,
  Percent,
  Loader
} from 'lucide-react';

// Stripe Elements import
import { Elements } from '@stripe/react-stripe-js';
import { getStripeJs } from '../../../lib/stripe';
import PaymentForm from '../../components/PaymentForm';

const ApplyNowModal = () => {
  const { user, isLoggedIn, setUser } = useUserStore();
  const [showModal, setShowModal] = useState(false);
  const [applyData, setApplyData] = useState(null);
  const [isLoginForm, setIsLoginForm] = useState(true);
  const [isRegisterForm, setIsRegisterForm] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState(''); // 'cash' or 'online'
  const [showPaymentForm, setShowPaymentForm] = useState(false);
  const [clientSecret, setClientSecret] = useState('');
  const [stripePromise, setStripePromise] = useState(null);
  const [paymentLoading, setPaymentLoading] = useState(false); // New loading state for payment
  
  const [formData, setFormData] = useState({
    // Login form
    email: '',
    password: '',
    
    // Registration form - Only required fields
    first_name: '',
    last_name: '',
    phone: '',
    phone_code: '92', // +92 selected by default
    nationality: '', // Country null by default
    state: '',
    city: '',
    program_type: '',
    gender: '',
    agree: false,
  });
  
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [loading, setLoading] = useState(false);

  // Load countries and Stripe on component mount
  useEffect(() => {
    loadCountries();
    getStripeJs().then(setStripePromise);
  }, []);

  const loadCountries = async () => {
    try {
      const response = await fetch('/api/frontend/countries-with-phone');
      const data = await response.json();
      if (data.success) {
        setCountries(data.data);
        // Find Pakistan in the countries list to set as default
        const pakistan = data.data.find(country => country.phonecode === '92');
        if (pakistan) {
          setFormData(prev => ({
            ...prev,
            phone_code: '92', // +92
            // nationality remains null as requested
          }));
        }
      }
    } catch (error) {
      console.error('Error loading countries:', error);
    }
  };

  const loadStates = async (countryId) => {
    try {
      const response = await fetch(`/api/frontend/states?countryId=${countryId}`, { method: "POST" });
      const data = await response.json();
      if (data.success) {
        setStates(data.states);
      }
    } catch (error) {
      console.error('Error loading states:', error);
    }
  };

  const loadCities = async (stateId) => {
    try {
      const response = await fetch(`/api/frontend/cities?stateId=${stateId}`, { method: "POST" });
      const data = await response.json();
      if (data.success) {
        setCities(data.cities);
      }
    } catch (error) {
      console.error('Error loading cities:', error);
    }
  };

  // Calculate price based on backend data structure
  const calculatePrice = () => {
    if (!applyData) return 0;
    
    // Use the consultation_fee_after_discount if available and valid
    if (applyData.consultation_fee_after_discount && parseFloat(applyData.consultation_fee_after_discount) > 0) {
      return parseFloat(applyData.consultation_fee_after_discount);
    }
    
    // Fallback to original consultation fee
    return applyData.consultation_fee || 0;
  };

  // Check if discount is available
  const hasDiscount = () => {
    if (!applyData) return false;
    
    const originalPrice = applyData.consultation_fee || 0;
    const discountedPrice = applyData.consultation_fee_after_discount ? 
      parseFloat(applyData.consultation_fee_after_discount) : 0;
    
    return discountedPrice > 0 && discountedPrice < originalPrice;
  };

  // Get discount percentage
  const getDiscountPercentage = () => {
    if (!applyData || !applyData.consultation_fee_discount) return 0;
    return applyData.consultation_fee_discount;
  };

  // Get original price
  const getOriginalPrice = () => {
    if (!applyData) return 0;
    return applyData.consultation_fee || 0;
  };

  // Global function to open modal
  const openApplyNowModal = (item) => {
    setApplyData({
      type: item.type,
      id: item.id,
      name: item.type === 'course' ? item.name : item.university,
      university: item.university || item.name,
      courseName: item.type === 'course' ? item.name : item.courseName,
      
      // Use backend data structure
      consultation_fee: item.consultation_fee || 0,
      consultation_fee_discount: item.consultation_fee_discount || 0,
      consultation_fee_after_discount: item.consultation_fee_after_discount || 0
    });
    
    if (isLoggedIn && user?.role !== 'admin') {
      setShowModal(true);
      setIsLoginForm(false);
      setIsRegisterForm(false);
      setPaymentMethod('');
      setShowPaymentForm(false);
      setClientSecret('');
      setPaymentLoading(false); // Reset payment loading
    } else if (!isLoggedIn) {
      setShowModal(true);
      setIsLoginForm(true);
      setIsRegisterForm(false);
      setPaymentMethod('');
      setShowPaymentForm(false);
      setClientSecret('');
      setPaymentLoading(false); // Reset payment loading
    } else {
      Swal.fire({
        title: 'Not Available',
        text: 'Admin users cannot apply for courses/universities',
        icon: 'warning',
        confirmButtonColor: '#0B6F78'
      });
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const response = await fetch('/api/frontend/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: formData.email,
          password: formData.password
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setUser(data.data);
        setIsLoginForm(false);
        setIsRegisterForm(false);
        
        Swal.fire({
          title: 'Login Successful!',
          icon: 'success',
          confirmButtonColor: '#0B6F78',
          timer: 1500,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          title: 'Login Failed',
          text: data.message || 'Invalid credentials',
          icon: 'error',
          confirmButtonColor: '#0B6F78'
        });
      }
    } catch (error) {
      Swal.fire({
        title: 'Error',
        text: 'Something went wrong. Please try again.',
        icon: 'error',
        confirmButtonColor: '#0B6F78'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const response = await fetch('/api/frontend/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          first_name: formData.first_name,
          last_name: formData.last_name,
          phone: `+${formData.phone_code}${formData.phone}`,
          email: formData.email, // Using the same email from login form
          password: formData.password, // Using the same password from login form
          confirm_password: formData.password,
          nationality: formData.nationality,
          state: formData.state,
          city: formData.city,
          program_type: formData.program_type,
          gender: formData.gender,
          agree: formData.agree
        }),
      });

      const data = await response.json();

      if (response.ok) {
        const loginResponse = await fetch('/api/frontend/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            email: formData.email,
            password: formData.password
          }),
        });

        const loginData = await loginResponse.json();

        if (loginResponse.ok) {
          setUser(loginData.data);
          setIsLoginForm(false);
          setIsRegisterForm(false);
          
          Swal.fire({
            title: 'Registration Successful!',
            text: 'Your account has been created and you are now logged in.',
            icon: 'success',
            confirmButtonColor: '#0B6F78'
          });
        }
      } else {
        const errorMessages = data.message || {};
        
        if (typeof errorMessages === 'object') {
          // Now display these erros is Swal\
          const errorMessagesString = Object.values(errorMessages).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Something went wrong, please try again later',
            text: errorMessagesString,
            confirmButtonColor: '#0B6D76'
          });
        } else {
          throw new Error(errorMessages);
        }
      }
    } catch (error) {
      Swal.fire({
        title: 'Error',
        text: error,
        icon: 'error',
        confirmButtonColor: '#0B6F78'
      });
    } finally {
      setLoading(false);
    }
  };

  // Create Stripe Payment Intent
  const createPaymentIntent = async () => {
    try {
      setPaymentLoading(true); // Set specific payment loading state
      const amount = calculatePrice();
      
      const response = await fetch('/api/frontend/payment-intent', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          amount,
          consultationType: `${applyData.type} - ${applyData.name || applyData.university}`,
          customerEmail: user.email,
          customerName: user.name,
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || 'Failed to create payment intent');
      }

      setClientSecret(data.clientSecret);
      setShowPaymentForm(true);
      
      // Add a small delay to ensure the payment form is properly rendered
      // before hiding the loading state
      setTimeout(() => {
        setPaymentLoading(false);
      }, 500);
      
    } catch (error) {
      console.error('Error creating payment intent:', error);
      setPaymentLoading(false); // Make sure to reset loading state on error
      Swal.fire({
        title: 'Payment Error',
        text: error.message || 'Failed to initialize payment',
        icon: 'error',
        confirmButtonColor: '#0B6F78'
      });
    }
  };

  // Handle payment method selection
  const handlePaymentMethodSelect = async (method) => {
    if (paymentLoading) return; // Prevent multiple clicks
    
    setPaymentMethod(method);
    
    if (method === 'online') {
      await createPaymentIntent();
    }
  };

  // Handle successful payment
  const handlePaymentSuccess = async (paymentIntentId, transactionId) => {
    // Submit application after successful payment
    await submitApplication(paymentIntentId, 'paid');
  };

  // Handle payment error
  const handlePaymentError = (error) => {
    console.error('Payment error:', error);
    Swal.fire({
      title: 'Payment Failed',
      text: error || 'Payment processing failed. Please try again.',
      icon: 'error',
      confirmButtonColor: '#0B6F78'
    });
  };

  // Submit application (common function for both cash and online)
  const submitApplication = async (paymentIntentId = null, paymentStatus = 'pending') => {
    setLoading(true);

    try {
      const response = await fetch('/api/frontend/apply-now', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          type: applyData.type,
          apply_id: applyData.id,
          item_name: applyData.name || applyData.university,
          user_id: user.id,
          payment_method: paymentMethod,
          payment_status: paymentStatus,
          payment_intent_id: paymentIntentId,
          amount: calculatePrice(),
          consultation_fee: getOriginalPrice(),
          consultation_fee_discount: getDiscountPercentage(),
          consultation_fee_after_discount: calculatePrice()
        }),
      });

      const data = await response.json();

      if (response.ok) {
        let successMessage = 'Application Submitted!';
        if (paymentMethod === 'online' && paymentStatus === 'paid') {
          successMessage = 'Payment Successful & Application Submitted!';
        }

        Swal.fire({
          title: successMessage,
          html: `
            <div class="text-center">
              <div class="bg-gradient-to-r from-green-400 to-green-600 rounded-full w-20 h-20 flex items-center justify-center mx-auto mb-4 shadow-lg">
                <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                </svg>
              </div>
              <h3 class="text-xl font-bold text-gray-900 mb-2">Application Successful!</h3>
              <p class="text-gray-600 mb-4">
                Your application for <strong class="text-[#0B6F78]">${applyData.name || applyData.university}</strong> has been submitted successfully.
              </p>
              <div class="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-4 text-white">
                <p class="text-sm">
                  <strong>Payment Method:</strong> ${paymentMethod === 'online' ? 'Online (Paid)' : 'Cash (Pending)'}
                </p>
                <p class="text-sm mt-1">
                  <strong>Amount:</strong> PKR ${calculatePrice().toFixed(2)}
                  ${hasDiscount() ? ` <span class="text-green-300">(${getDiscountPercentage()}% discount applied)</span>` : ''}
                </p>
              </div>
            </div>
          `,
          icon: 'success',
          confirmButtonColor: '#0B6F78',
          confirmButtonText: 'Great! Thank You'
        });
        
        // Reset everything
        setShowModal(false);
        setApplyData(null);
        setPaymentMethod('');
        setShowPaymentForm(false);
        setClientSecret('');
        setPaymentLoading(false); // Reset payment loading
        setFormData({
          email: '',
          password: '',
          first_name: '',
          last_name: '',
          phone: '',
          phone_code: '92',
          nationality: '',
          state: '',
          city: '',
          program_type: '',
          gender: '',
          agree: false,
        });
      } else {
        Swal.fire({
          title: 'Application Failed',
          text: data.message || 'Please try again.',
          icon: 'error',
          confirmButtonColor: '#0B6F78'
        });
      }
    } catch (error) {
      Swal.fire({
        title: 'Error',
        text: 'Something went wrong. Please try again.',
        icon: 'error',
        confirmButtonColor: '#0B6F78'
      });
    } finally {
      setLoading(false);
    }
  };

  // Handle final application submission for cash payment
  const handleFinalApply = async () => {
    if (paymentMethod === 'cash') {
      await submitApplication(null, 'pending');
    }
    // For online payment, it's handled in handlePaymentSuccess
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));

    // Load states when country is selected via nationality
    if (name === 'nationality' && value) {
      loadStates(value);
      setFormData(prev => ({ 
        ...prev, 
        state: '', 
        city: '',
        phone_code: countries.find(country => country.id === value)?.phonecode || '92'
      }));
      setStates([]);
      setCities([]);
    }

    // Load cities when state is selected
    if (name === 'state' && value) {
      loadCities(value);
      setFormData(prev => ({ ...prev, city: '' }));
      setCities([]);
    }
  };

  // Format phone number with country code
  const getFullPhoneNumber = () => {
    return `+${formData.phone_code}${formData.phone}`;
  };

  // Make the function globally available
  useEffect(() => {
    window.openApplyNowModal = openApplyNowModal;
  }, [isLoggedIn, user]);

  if (!showModal) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[95vh] overflow-hidden border border-gray-100">
        {/* Header */}
        <div className="relative bg-gradient-to-br from-[#0B6F78] via-[#0a5a62] to-[#0a306b] p-8 text-white">
          <div className="absolute top-4 right-4">
            <button 
              onClick={() => setShowModal(false)}
              className="p-2 hover:bg-white/10 rounded-full transition-colors duration-200"
            >
              <X size={24} />
            </button>
          </div>
          
          <div className="text-center">
            <div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <GraduationCap size={32} />
            </div>
            <h2 className="text-3xl font-bold mb-2">
              {isLoginForm ? 'Welcome Back' : 
               isRegisterForm ? 'Create Account' : 
               showPaymentForm ? 'Complete Payment' :
               paymentMethod ? 'Confirm Application' : 'Select Payment Method'}
            </h2>
            <p className="text-white/90 text-lg">
              {applyData?.type === 'course' ? 'Course' : 'University'}: {applyData?.university}
            </p>
          </div>
        </div>

        <div className="p-8 max-h-[calc(95vh-200px)] overflow-y-auto">
          {/* Login Form */}
          {isLoginForm && (
            <form onSubmit={handleLogin} className="space-y-6">
              <div className="space-y-4">
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    placeholder="Enter your email"
                    className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                    required
                  />
                </div>
                
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <input
                    type={showPassword ? "text" : "password"}
                    name="password"
                    value={formData.password}
                    onChange={handleInputChange}
                    placeholder="Enter your password"
                    className="w-full pl-12 pr-12 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                  >
                    {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-4 rounded-2xl font-semibold hover:shadow-lg transform hover:scale-[1.02] transition-all duration-200 disabled:opacity-50 disabled:transform-none disabled:hover:shadow-none"
              >
                {loading ? (
                  <div className="flex items-center justify-center">
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                    Logging in...
                  </div>
                ) : (
                  'Login & Continue'
                )}
              </button>

              <div className="text-center pt-4">
                <p className="text-gray-600">
                  Don't have an account?{' '}
                  <button
                    type="button"
                    onClick={() => {
                      setIsLoginForm(false);
                      setIsRegisterForm(true);
                    }}
                    className="text-[#0B6F78] font-semibold hover:text-[#0a5a62] transition-colors"
                  >
                    Create one here
                  </button>
                </p>
              </div>
            </form>
          )}

          {/* Registration Form */}
          {isRegisterForm && (
            <form onSubmit={handleRegister} className="space-y-6">
              {/* 1. First Name & Last Name */}
              <div className="grid grid-cols-2 gap-4">
                <div className="relative">
                  <User className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <input
                    type="text"
                    name="first_name"
                    value={formData.first_name}
                    onChange={handleInputChange}
                    placeholder="First Name"
                    className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                    required
                  />
                </div>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <input
                    type="text"
                    name="last_name"
                    value={formData.last_name}
                    onChange={handleInputChange}
                    placeholder="Last Name"
                    className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                    required
                  />
                </div>
              </div>

              {/* 2. Phone Code & Number */}
              <div className="relative">
                <Phone className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <div className="flex">
                  <select
                    name="phone_code"
                    value={formData.phone_code}
                    onChange={handleInputChange}
                    className="w-32 pl-10 pr-4 py-4 border border-gray-200 rounded-l-2xl border-r-0 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                    required
                  >
                    {countries.map(country => (
                      <option 
                        key={country.id} 
                        value={country.phonecode}
                        selected={country.phonecode === '92'}
                      >
                        +{country.phonecode}
                      </option>
                    ))}
                  </select>
                  <input
                    type="tel"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="Phone Number"
                    className="flex-1 pl-4 pr-4 py-4 border border-gray-200 rounded-r-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                    required
                  />
                </div>
              </div>

              {/* 3. Program Type */}
              <div className="relative">
                <GraduationCap className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <select
                  name="program_type"
                  value={formData.program_type}
                  onChange={handleInputChange}
                  className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                  required
                >
                  <option value="">Select Program Type</option>
                  <option value="undergraduate">Undergraduate</option>
                  <option value="graduate">Graduate</option>
                  <option value="phd">PhD</option>
                  <option value="certificate">Certificate</option>
                </select>
              </div>

              {/* 4. Country */}
              <div className="relative">
                <Globe className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <select
                  name="nationality"
                  value={formData.nationality}
                  onChange={handleInputChange}
                  className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                  required
                >
                  <option value="">Select Country</option>
                  {countries.map(country => (
                    <option key={country.id} value={country.id}>
                      {country.name}
                    </option>
                  ))}
                </select>
              </div>

              {/* 5. State & City */}
              <div className="grid grid-cols-2 gap-4">
                <div className="relative">
                  <MapPin className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <select
                    name="state"
                    value={formData.state}
                    onChange={handleInputChange}
                    className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                    required
                    disabled={!formData.nationality}
                  >
                    <option value="">Select State</option>
                    {states.map(state => (
                      <option key={state.id} value={state.id}>
                        {state.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="relative">
                  <MapPin className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                  <select
                    name="city"
                    value={formData.city}
                    onChange={handleInputChange}
                    className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                    required
                    disabled={!formData.state}
                  >
                    <option value="">Select City</option>
                    {cities.map(city => (
                      <option key={city.id} value={city.id}>
                        {city.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* 6. Gender */}
              <div className="relative">
                <User className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <select
                  name="gender"
                  value={formData.gender}
                  onChange={handleInputChange}
                  className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 appearance-none"
                  required
                >
                  <option value="">Select Gender</option>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                  <option value="Other">Other</option>
                </select>
              </div>

              {/* 7. Email */}
              <div className="relative">
                <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  placeholder="Email Address"
                  className="w-full pl-12 pr-4 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                  required
                />
              </div>

              {/* 8. Password */}
              <div className="relative">
                <Lock className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
                <input
                  type={showPassword ? "text" : "password"}
                  name="password"
                  value={formData.password}
                  onChange={handleInputChange}
                  placeholder="Password"
                  className="w-full pl-12 pr-12 py-4 border border-gray-200 rounded-2xl focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent bg-gray-50/50 transition-all duration-200"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>

              {/* Terms Agreement */}
              <div className="flex items-center space-x-3 p-4 bg-blue-50 rounded-2xl border border-blue-100">
                <input
                  type="checkbox"
                  name="agree"
                  checked={formData.agree}
                  onChange={handleInputChange}
                  className="w-5 h-5 text-[#0B6F78] border-gray-300 rounded focus:ring-[#0B6F78]"
                  required
                />
                <label className="text-sm text-gray-700">
                  I agree to the <span className="text-[#0B6F78] font-semibold">terms and conditions</span> and <span className="text-[#0B6F78] font-semibold">privacy policy</span>
                </label>
              </div>
              
              <div className="flex gap-4 pt-2">
                <button
                  type="button"
                  onClick={() => {
                    setIsRegisterForm(false);
                    setIsLoginForm(true);
                  }}
                  className="flex-1 border-2 border-gray-300 text-gray-700 py-4 rounded-2xl font-semibold hover:bg-gray-50 hover:border-gray-400 transition-all duration-200"
                >
                  Back to Login
                </button>
                <button
                  type="submit"
                  disabled={loading || !formData.agree}
                  className="flex-1 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white py-4 rounded-2xl font-semibold hover:shadow-lg transform hover:scale-[1.02] transition-all duration-200 disabled:opacity-50 disabled:transform-none disabled:hover:shadow-none"
                >
                  {loading ? (
                    <div className="flex items-center justify-center">
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                      Creating Account...
                    </div>
                  ) : (
                    'Create Account & Apply'
                  )}
                </button>
              </div>
            </form>
          )}

          {/* Payment Method Selection */}
          {!isLoginForm && !isRegisterForm && user && !paymentMethod && !showPaymentForm && (
            <div className="space-y-6">
              <div className="text-center mb-2">
                <h3 className="font-bold text-gray-900 text-xl mb-2">Select Payment Method</h3>
                <p className="text-gray-600">
                  Choose how you would like to pay for your application
                </p>
              </div>

              {/* Enhanced Price Display */}
              <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-6 text-white">
                <h4 className="text-lg font-semibold mb-3 text-center">Consultation Fee</h4>
                
                <div className="space-y-2">
                  {/* Original Price */}
                  <div className="flex justify-between items-center">
                    <span className="text-white/80">Original Price:</span>
                    <span className="text-lg">PKR {getOriginalPrice().toFixed(2)}</span>
                  </div>
                  
                  {/* Discount */}
                  {hasDiscount() && (
                    <div className="flex justify-between items-center">
                      <span className="text-white/80 flex items-center">
                        <Percent size={14} className="mr-1" />
                        Discount ({getDiscountPercentage()}%):
                      </span>
                      <span className="text-green-300">
                        -PKR {(getOriginalPrice() - calculatePrice()).toFixed(2)}
                      </span>
                    </div>
                  )}
                  
                  {/* Divider */}
                  <div className="border-t border-white/20 my-2"></div>
                  
                  {/* Final Price */}
                  <div className="flex justify-between items-center">
                    <span className="text-white font-semibold">Final Price:</span>
                    <span className="text-2xl font-bold">PKR {calculatePrice().toFixed(2)}</span>
                  </div>
                </div>

                {hasDiscount() && (
                  <div className="mt-3 p-2 bg-green-500/20 rounded-lg text-center">
                    <p className="text-green-300 text-sm font-medium">
                      You save PKR {(getOriginalPrice() - calculatePrice()).toFixed(2)}!
                    </p>
                  </div>
                )}
              </div>

              {/* Payment Options */}
              <div className="grid grid-cols-1 gap-4">
                <button
                  onClick={() => handlePaymentMethodSelect('cash')}
                  disabled={paymentLoading}
                  className="p-6 border-2 border-gray-200 rounded-2xl hover:border-[#0B6F78] hover:bg-blue-50 transition-all duration-200 text-left disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <div className="flex items-center space-x-4">
                    <div className="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
                      <DollarSign className="text-green-600" size={24} />
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900">Pay with Cash</h4>
                      <p className="text-gray-600 text-sm">Pay offline when you visit our office</p>
                    </div>
                  </div>
                </button>

                <button
                  onClick={() => handlePaymentMethodSelect('online')}
                  disabled={paymentLoading}
                  className="p-6 border-2 border-gray-200 rounded-2xl hover:border-[#0B6F78] hover:bg-blue-50 transition-all duration-200 text-left disabled:opacity-50 disabled:cursor-not-allowed relative"
                >
                  {paymentLoading && (
                    <div className="absolute inset-0 bg-white/80 rounded-2xl flex items-center justify-center z-10">
                      <div className="flex items-center space-x-2 text-[#0B6F78]">
                        <Loader className="w-5 h-5 animate-spin" />
                        <span className="font-medium">Preparing payment...</span>
                      </div>
                    </div>
                  )}
                  <div className="flex items-center space-x-4">
                    <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                      <CreditCard className="text-blue-600" size={24} />
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900">Pay Online</h4>
                      <p className="text-gray-600 text-sm">Secure payment with credit/debit card</p>
                    </div>
                  </div>
                </button>
              </div>

              <div className="text-center pt-4">
                <button
                  onClick={() => setShowModal(false)}
                  disabled={paymentLoading}
                  className="text-gray-600 hover:text-gray-800 transition-colors disabled:opacity-50"
                >
                  Cancel
                </button>
              </div>
            </div>
          )}

          {/* Stripe Payment Form */}
          {showPaymentForm && clientSecret && stripePromise && (
            <div className="space-y-6">
              <div className="text-center mb-2">
                <CreditCard className="w-12 h-12 text-blue-500 mx-auto mb-3" />
                <h3 className="font-bold text-gray-900 text-xl mb-2">Complete Payment</h3>
                <p className="text-gray-600">
                  Secure payment for {applyData?.name || applyData?.university}
                </p>
                <div className="bg-gray-100 rounded-xl p-4 mt-4">
                  <div className="text-center">
                    <p className="text-lg font-semibold text-gray-900">
                      Amount: PKR {calculatePrice().toFixed(2)}
                    </p>
                    {hasDiscount() && (
                      <p className="text-sm text-green-600 mt-1">
                        {getDiscountPercentage()}% discount applied
                      </p>
                    )}
                  </div>
                </div>
              </div>

              <Elements stripe={stripePromise} options={{ clientSecret }}>
                <PaymentForm
                  amount={calculatePrice()}
                  consultationType={`${applyData.type} - ${applyData.name || applyData.university}`}
                  customerEmail={user.email}
                  customerName={user.name}
                  onSuccess={handlePaymentSuccess}
                  onError={handlePaymentError}
                />
              </Elements>

              <div className="text-center">
                <button
                  onClick={() => {
                    setShowPaymentForm(false);
                    setPaymentMethod('');
                    setClientSecret('');
                    setPaymentLoading(false);
                  }}
                  className="text-gray-600 hover:text-gray-800 transition-colors"
                >
                  ← Back to Payment Methods
                </button>
              </div>
            </div>
          )}

          {/* Confirmation View for Cash Payment */}
          {!isLoginForm && !isRegisterForm && user && paymentMethod === 'cash' && !showPaymentForm && (
            <div className="space-y-6">
              <div className="text-center mb-2">
                <CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-3" />
                <h3 className="font-bold text-gray-900 text-xl mb-2">Confirm Your Application</h3>
                <p className="text-gray-600">
                  Please review your application details before submitting
                </p>
              </div>

              {/* Clean Information Layout */}
              <div className="bg-gray-50 rounded-2xl p-6 border border-gray-200">
                <div className="space-y-4">
                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">Name:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1">{user.name}</span>
                  </div>
                  
                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">Email:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1">{user.email}</span>
                  </div>
                  
                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">Application Type:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1 capitalize">{applyData?.type}</span>
                  </div>
                  
                  {applyData?.type === 'course' && (
                    <div className="flex justify-between items-start">
                      <span className="text-gray-600 font-medium min-w-[140px]">Course Name:</span>
                      <span className="font-semibold text-gray-900 text-right flex-1">{applyData?.name}</span>
                    </div>
                  )}
                  
                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">University:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1">{applyData?.university}</span>
                  </div>

                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">Payment Method:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1 capitalize">Cash</span>
                  </div>

                  <div className="flex justify-between items-start">
                    <span className="text-gray-600 font-medium min-w-[140px]">Amount:</span>
                    <span className="font-semibold text-gray-900 text-right flex-1">
                      ${calculatePrice().toFixed(2)}
                      {hasDiscount() && (
                        <div className="text-sm text-green-600">
                          (${getOriginalPrice().toFixed(2)} - {getDiscountPercentage()}% discount)
                        </div>
                      )}
                    </span>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex gap-4 pt-4">
                <button
                  onClick={() => {
                    setPaymentMethod('');
                    setShowPaymentForm(false);
                  }}
                  className="flex-1 border-2 border-gray-300 text-gray-700 py-3 rounded-xl font-semibold hover:bg-gray-50 transition-all duration-200"
                >
                  ← Back
                </button>
                <button
                  onClick={handleFinalApply}
                  disabled={loading}
                  className="flex-1 bg-gradient-to-r from-green-500 to-green-600 text-white py-3 rounded-xl font-semibold hover:shadow-lg transition-all duration-200 disabled:opacity-50"
                >
                  {loading ? (
                    <div className="flex items-center justify-center">
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                      Submitting...
                    </div>
                  ) : (
                    'Confirm & Apply Now'
                  )}
                </button>
               </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ApplyNowModal;