'use client';

import { useState, useEffect, use } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import FreelancerLayout from '@/components/layout/FreelancerLayout';
import { useFreelancerProfile } from '@/hooks/useFreelancerProfile';
import './membership.css';
import StripePaymentForm from '@/components/payments/StripePaymentForm';
import { getCountryDataByDomain } from '@/lib/countries';
import { fa } from 'zod/v4/locales';
import { useSearchParams } from 'next/navigation';

interface FreelancerMembershipPageProps {
  params: Promise<{
    locale: string;
  }>;
}

interface MembershipData {
  id: string;
  category: string;
  icon: string;
  status: 'active' | 'expiring' | 'expired';
  expiryDays?: number;
}

interface MembershipHistory {
  id: string;
  category: string;
  categoryIcon: string;
  transactionId: string;
  amount: number;
  currency: string;
  paymentMethod: string;
  startDate: string;
  endDate: string;
  status: 'active' | 'expired' | 'expiring';
  paymentStatus: 'completed' | 'failed' | 'processing';
  date: string;
}

interface Category {
  id: string;
  name: string;
  slug: string;
  description?: string;
  icon?: string;
  isActive: boolean;
}

interface CountryOption {
  id: string;
  name: string;
  code: string;
}

interface UserProfile {
  id: string;
  firstName?: string;
  lastName?: string;
  address?: string;
  city?: string;
  zipCode?: string;
  state?: string;
  countryId?: string;
  profileImage?: string;
}

export default function FreelancerMembershipPage({ params }: FreelancerMembershipPageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  const { profile } = useFreelancerProfile();
  const searchParams = useSearchParams();
  const buyCategory = searchParams.get('category-buy');
  const datacounter =    getCountryDataByDomain();
  
  const [memberships, setMemberships] = useState<MembershipData[]>([]);
  const [membershipHistory, setMembershipHistory] = useState<MembershipHistory[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCategoriesLoading, setIsCategoriesLoading] = useState(false);
  const [isCountriesLoading, setIsCountriesLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [historyFilter, setHistoryFilter] = useState('');
  const [showAddMembershipModal, setShowAddMembershipModal] = useState(false);
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('');
  const [selectedCountry, setSelectedCountry] = useState<string>(locale === 'ch' ? 'CH' : 'LU');
  const [billingName, setBillingName] = useState<string>('');
  const [addressLine1, setAddressLine1] = useState<string>('');
  const [city, setCity] = useState<string>('');
  const [postalCode, setPostalCode] = useState<string>('');
  const [stateCode, setStateCode] = useState<string>('');
  const [paymentMethod, setPaymentMethod] = useState<'card' | 'twint'>('card');
  const [cardNumber, setCardNumber] = useState<string>('');
  const [expirationDate, setExpirationDate] = useState<string>('');
  const [securityCode, setSecurityCode] = useState<string>('');
  const [countries, setCountries] = useState<CountryOption[]>([]);
  const [showPaymentForm, setShowPaymentForm] = useState(false);
  const [clientSecret, setClientSecret] = useState<string>('');
  const [paymentAmount, setPaymentAmount] = useState<number>(0);
  const [paymentCurrency, setPaymentCurrency] = useState<string>('EUR');
  const [paymentCategoryNames, setPaymentCategoryNames] = useState<string[]>([]);
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isProfileLoading, setIsProfileLoading] = useState(false);
  const [isSubscribed, setIsSubscribed] = useState(false);  
  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setIsSubscribed(e.target.checked);
  };

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push(`/${locale}/login`);
      return;
    }

    if (status === 'authenticated') {
      fetchMembershipData();
      fetchCategories();
      fetchCountries();
      fetchUserProfile();
    }
  }, [status, locale, router, historyFilter]);

  const fetchMembershipData = async () => {
    try {
      setIsLoading(true);
      const errors: string[] = [];
      
      // Fetch active memberships
      try {
        const membershipsResponse = await fetch('/api/freelancer/memberships');
        if (membershipsResponse.ok) {
          const membershipsData = await membershipsResponse.json();
          if (membershipsData.success && membershipsData.data) {
            setMemberships(membershipsData.data);
          } else {
            errors.push('Failed to load active memberships');
          }
        } else {
          const errorData = await membershipsResponse.json().catch(() => ({ error: 'Unknown error' }));
          console.error('Failed to fetch memberships:', errorData);
          errors.push('Failed to load active memberships');
        }
      } catch (err) {
        errors.push('Failed to load active memberships');
      }
      
      // Fetch membership history
      try {
        const historyParams = new URLSearchParams();
        if (historyFilter) {
          historyParams.append('status', historyFilter);
        }
        
        const historyResponse = await fetch(`/api/freelancer/memberships/history?${historyParams.toString()}`);
        if (historyResponse.ok) {
          const historyData = await historyResponse.json();
          if (historyData.success && historyData.data && historyData.data.transactions) {
            setMembershipHistory(historyData.data.transactions);
          } else {
            errors.push('Failed to load membership history');
          }
        } else {
          const errorData = await historyResponse.json().catch(() => ({ error: 'Unknown error' }));
          console.error('Failed to fetch membership history:', errorData);
          errors.push('Failed to load membership history');
        }
      } catch (err) {
        errors.push('Failed to load membership history');
      }
      
      // Show single consolidated error if any errors occurred
      if (errors.length > 0) {
        showError(
          errors.length === 1 
            ? errors[0] 
            : `Multiple errors occurred: ${errors.join(', ')}.`, 
          'Data Load Error'
        );
      }
      
    } catch (error) {
      console.error('Error fetching membership data:', error);
      showError('Failed to load membership data. Please check your internet connection and try again.', 'Connection Error');
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      setIsCategoriesLoading(true);
      const response = await fetch('/api/categories?active=true');
      
      if (response.ok) {
        const categoriesData = await response.json();
        if (Array.isArray(categoriesData)) {
          setCategories(categoriesData.filter(cat => cat.isActive));
          // open buy category modal  
          if(buyCategory){
              setShowAddMembershipModal(true);
              setSelectedCategoryId(buyCategory)
            }
        } else {
          console.warn('Categories API returned unexpected format:', categoriesData);
          setCategories([]);
        }
      } else {
        const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
        console.error('Failed to fetch categories:', errorData);
        // Only show error if it's critical - categories loading is not blocking
        console.warn('Categories could not be loaded, user can retry');
      }
    } catch (error) {
      console.error('Error fetching categories:', error);
      // Only show error if it's critical - categories loading is not blocking
      console.warn('Categories could not be loaded, user can retry');
    } finally {
      setIsCategoriesLoading(false);
    }
  };

  const fetchCountries = async () => {
    try {
      setIsCountriesLoading(true);
      const res = await fetch('/api/countries');
      if (!res.ok) {
        const err = await res.json().catch(() => ({ message: 'Unknown error' }));
        console.error('Failed to fetch countries:', err);
        // Set a default fallback instead of showing error toast
        setCountries([{ id: 'CH', name: 'Switzerland', code: 'CH' }, { id: 'LU', name: 'Luxembourg', code: 'LU' }]);
        return;
      }
      const data = await res.json();
      const list: CountryOption[] = Array.isArray(data?.countries) ? data.countries : [];
      setCountries(list);
      // Auto-select based on user profile country first, then locale
      if (!selectedCountry) {
        let preferred = locale === 'ch' ? 'CH' : 'LU';
        if (userProfile?.countryId) {
          const profileCountry = list.find(c => c.code === userProfile.countryId);
          if (profileCountry) {
            preferred = userProfile.countryId;
          }
        }
        const hasPreferred = list.find(c => c.code.toUpperCase() === preferred);
        setSelectedCountry(hasPreferred ? preferred : (list[0]?.code || ''));
      }
    } catch (error) {
      console.error('Error fetching countries:', error);
      // Set a default fallback instead of showing error toast
      setCountries([{ id: 'CH', name: 'Switzerland', code: 'CH' }, { id: 'LU', name: 'Luxembourg', code: 'LU' }]);
    } finally {
      setIsCountriesLoading(false);
    }
  };

  const fetchUserProfile = async () => {
    try {
      setIsProfileLoading(true);
      const res = await fetch('/api/profile');
      if (res.ok) {
        const data = await res.json();
        if (data.success && data.data) {
          setUserProfile(data.data);
          
          // Pre-fill form fields with profile data
          if (data.data.firstName && data.data.lastName) {
            setBillingName(`${data.data.firstName} ${data.data.lastName}`.trim());
          }
          if (data.data.address) {
            setAddressLine1(data.data.address);
          }
          if (data.data.city) {
            setCity(data.data.city);
          }
          if (data.data.zipCode) {
            setPostalCode(data.data.zipCode);
          }
          if (data.data.state) {
            setStateCode(data.data.state);
          }
          if (data.data.countryId) {
            setSelectedCountry(data.data.countryId);
          }
        }
      }
    } catch (error) {
      console.error('Error fetching user profile:', error);
      // Don't show error to user as profile data is optional for pre-filling
    } finally {
      setIsProfileLoading(false);
    }
  };

  const handlePurchase = async (e: React.FormEvent) => {
    e.preventDefault();
    var checkError = false;
    if (!selectedCategoryId) {
      showError('Please select a category.');
      checkError = true;
    }
    // if (!selectedCountry) {
    //   showError('Please select a country.');
    //   checkError = true;
    // }   
    if(!datacounter?.id){
        showError('Please select a country.');
        checkError = true;
    }
    if (!billingName) {
      showError('Billing name field is required.');
      checkError = true;
    }
    if (!addressLine1) {
      showError('Address Line1 field is required.');
      checkError = true;
    }
    if (!city) {
      showError('Ciyt field is required.');
      checkError = true;
    }
    if (!postalCode) {
      showError('Postal code field is required.');
      checkError = true;
    }
    if (!stateCode) {
      showError('State code field is required.');
      checkError = true;
    }
    if(checkError){
      return false;
    }    
    try {
      setIsSubmitting(true);

      var priceIdIs = isSubscribed ? datacounter?.priceId : "";
      const response = await fetch('/api/freelancer/membership/purchase', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          priceId: priceIdIs,
          // priceId: '',
          categoryIds: [selectedCategoryId],
          currency,
          // country: selectedCountry,
          country: datacounter?.id,
          billingName,
          addressLine1,
          city,
          postalCode,
          state: stateCode
        })
      });

      const result = await response.json().catch(() => ({}));
      if (response.ok && result?.success && result?.data?.clientSecret) {
        // Open Stripe PaymentElement
        setClientSecret(result.data.clientSecret);
        setPaymentAmount(result.data.amount);
        setPaymentCurrency(result.data.currency);
        setPaymentCategoryNames(result.data.categoryNames || []);
        setShowPaymentForm(true);
        showSuccess(result.message || 'Payment initialized. Complete your payment to activate the membership.', 'Payment Ready');
      } else {
        const errorMsg = result?.message || result?.error || 'Failed to start payment. Please try again.';
        showError(errorMsg, 'Purchase Error');
      }
    } catch (error: any) {
      showError(error?.message || 'Unexpected error during purchase. Please try again.', 'Purchase Error');
    } finally {
      setIsSubmitting(false);
    }
  };

  // legacy createPaymentIntent flow removed in favor of membership/purchase API

  const resetForm = () => {
    setSelectedCategoryId('');
    setSelectedCountry(locale === 'ch' ? 'CH' : 'LU');
    setPaymentMethod('card');
    setCardNumber('');
    setExpirationDate('');
    setSecurityCode('');
    setBillingName('');
    setAddressLine1('');
    setCity('');
    setPostalCode('');
    setStateCode('');
  };

  // multi-select toggle removed; using single select like original HTML

  const getCurrency = () => {
    // Determine currency based on user profile country first, then selected country, then locale
    const country = userProfile?.countryId || selectedCountry || (locale === 'ch' ? 'CH' : 'LU');
    return country.toUpperCase() === 'CH' ? 'CHF' : 'EUR';
  };

  const currency = getCurrency();

  const getBasePrice = () => {
    const country = userProfile?.countryId || selectedCountry || (locale === 'ch' ? 'CH' : 'LU');
    return country.toUpperCase() === 'CH' ? 19.90 : 9.90;
  };

  const getPaymentMethods = () => {
    const country = userProfile?.countryId || selectedCountry || (locale === 'ch' ? 'CH' : 'LU');
    const methods = ['card'];
    
    switch (country.toUpperCase()) {
      case 'CH': // Switzerland
        methods.push('twint');
        break;
      case 'DE': // Germany
        methods.push('sepa_debit', 'sofort');
        break;
      case 'NL': // Netherlands
        methods.push('sepa_debit', 'ideal');
        break;
      case 'BE': // Belgium
        methods.push('sepa_debit', 'bancontact');
        break;
      case 'FR': // France
      case 'IT': // Italy
      case 'ES': // Spain
      case 'PT': // Portugal
      case 'LU': // Luxembourg
        methods.push('sepa_debit');
        break;
    }
    
    return methods;
  };

  const handlePaymentSuccess = async (pi: any) => {
    try {
      // Close payment modal first to show success state
      setShowPaymentForm(false);
      setShowAddMembershipModal(false);
      
      // Show single initial success message
      // showSuccess('Payment successful! Activating your membership...', 'Payment Complete');
      
      // Single attempt to confirm payment - avoid retry loops with multiple toasts
      try {
        const res = await fetch('/api/payments/confirm', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paymentIntentId: pi?.id }),
        });
        const data = await res.json().catch(() => ({}));
        
        if (res.ok && data?.success) {
          // Membership activated successfully - single success message
          // showSuccess('Membership activated! You can now bid on projects.', 'Membership Active');
          await fetchMembershipData();
          resetForm();
            setTimeout(() => {
              window.location.reload();  
            }, 1500);
        } else {
          // Single error message for failed activation
          showError('Payment confirmed but membership activation is taking longer than expected. Please refresh the page in a moment.', 'Activation Delayed');
          resetForm();
        }
      } catch (err: any) {
        showError('Payment confirmed but we encountered an issue. Please refresh the page to check your membership status.', 'Status Check Failed');
        resetForm();
      }
      
    } catch (err: any) {
      showError('Payment completed but an error occurred. Please refresh the page to check your membership status.', 'Activation Error');
      setShowPaymentForm(false);
      setShowAddMembershipModal(false);
      resetForm();
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <span className="badge badge-active">Active</span>;
      case 'expired':
        return <span className="badge badge-expired">Expired</span>;
      default:
        return <span className="badge badge-pending">Pending</span>;
    }
  };

  const getMembershipStatusClass = (membership: MembershipData) => {
    if (membership.status === 'active') return 'active';
    if (membership.status === 'expiring') return 'experie';
    return 'expired';
  };

  if (status === 'loading' || isLoading) {
    return (
      <FreelancerLayout 
        locale={locale}
        userProfile={profile ? {
          name: `${profile.firstName} ${profile.lastName}`,
          profileImage: profile.profileImage || "/assets/image/profile03.png",
          rating: profile.rating || 4.5,
          reviewCount: profile.reviewCount || 0
        } : {
          name: session?.user?.name || "Freelancer",
          profileImage: session?.user?.image || "/assets/image/profile03.png",
          rating: 4.5,
          reviewCount: 0
        }}

        unreadMessagesCount={0}
      >
        <div className="d-flex justify-content-center align-items-center min-vh-100">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      </FreelancerLayout>
    );
  }

  return (
    <FreelancerLayout
      locale={locale}
      userProfile={profile ? {
        name: `${profile.firstName} ${profile.lastName}`,
        profileImage: profile.profileImage || "/assets/image/profile03.png",
        rating: profile.rating || 4.5,
        reviewCount: profile.reviewCount || 0
      } : {
        name: session?.user?.name || "Freelancer",
        profileImage: session?.user?.image || "/assets/image/profile03.png",
        rating: 4.5,
        reviewCount: 0
      }}

      unreadMessagesCount={0}
    >
      <section className="profile-wrapper client-wrapper py-60">
        <div className="container">
          <div className="row">
            <div className="col-12">
              
              {/* My Membership Section */}
              <div className="category-listing">
                <div className="tab-title">
                  <h5>My Membership</h5>
                  <div className="project-filter">
                    <button 
                      className="custom-btn secondary-btn"
                      onClick={() => setShowAddMembershipModal(true)}
                    >
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8 12H16" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M12 16V8" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M9 22H15C20 22 22 20 22 15V9C22 4 20 2 15 2H9C4 2 2 4 2 9V15C2 20 4 22 9 22Z" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                      Add Membership
                    </button>
                  </div>
                </div>
                
                {memberships.length > 0 ? (
                  <ul className="category-list-wrap">
                    {memberships.map((membership) => (
                      <li key={membership.id}>
                        <div className="cat-outer">
                          <div className="cat-img">
                            <img 
                              src={membership.icon || `/assets/image/category/${membership.category}.svg`} 
                              alt={membership.category}
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.src = `/assets/image/category/default.svg`;
                              }}
                            />
                          </div>
                          <div className={`plan-validaty ${getMembershipStatusClass(membership)}`}>
                            {membership.status === 'active' && 'Active'}
                            {membership.status === 'expiring' && `Expiring in ${membership.expiryDays} days`}
                            {membership.status === 'expired' && 'Expired'}
                          </div>
                        </div>
                        <div className="title-h">{membership.category}</div>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <div className="text-center py-5">
                    <p className="text-muted">No active memberships found.</p>
                    <button 
                      className="custom-btn secondary-btn"
                      onClick={() => setShowAddMembershipModal(true)}
                    >
                      Add Your First Membership
                    </button>
                  </div>
                )}
              </div>

              {/* Membership History Section */}
              <div className="membership-list">
                <div className="tab-title">
                  <h5>History</h5>
                  <div className="project-filter">
                    <div className="custom-select shadow-none">
                      <select 
                        value={historyFilter} 
                        onChange={(e) => setHistoryFilter(e.target.value)}
                      >
                        <option value="">All</option>
                        <option value="active">Active</option>
                        <option value="expired">Expired</option>
                      </select>
                    </div>
                  </div>
                </div>
                
                {membershipHistory.length > 0 ? (
                  <div className="table-container">
                    <table className="custom-table">
                      <thead>
                        <tr>
                          <th>S.no</th>
                          <th>Category</th>
                          <th>Transaction ID</th>
                          <th>Start Date</th>
                          <th>End Date</th>
                          <th>Status</th>
                          <th>Payment</th>
                        </tr>
                      </thead>
                      <tbody>
                        {membershipHistory.map((history, index) => (
                          <tr key={history.id}>
                            <td>{index + 1}</td>
                            <td>
                              <div className="d-flex align-items-center">
                                {history.categoryIcon && (
                                  <img 
                                    src={history.categoryIcon} 
                                    alt={history.category} 
                                    className="me-2" 
                                    style={{ width: '20px', height: '20px' }}
                                    onError={(e) => {
                                      const target = e.target as HTMLImageElement;
                                      target.src = `/assets/image/category/default.svg`;
                                    }}
                                  />
                                )}
                                {history.category}
                              </div>
                            </td>
                            <td>{history.transactionId}</td>
                            <td>{new Date(history.startDate).toLocaleDateString()}</td>
                            <td>{new Date(history.endDate).toLocaleDateString()}</td>
                            <td>{getStatusBadge(history.status)}</td>
                            <td className="payment">{history.paymentStatus === 'completed' ? 'Succeeded' : 'Failed'}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div className="text-center py-5">
                    <p className="text-muted">No membership history found.</p>
                  </div>
                )}
              </div>

            </div>
          </div>
        </div>
      </section>

      {/* Add Membership Modal */}
      {showAddMembershipModal && !showPaymentForm && (
        <div className="modal fade show custom-modal" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content">
              <div className="tab-title mb-4">
                <h5>Add Membership</h5>
                <button 
                  type="button" 
                  className="btn-close" 
                  onClick={() => setShowAddMembershipModal(false)}
                ></button>
              </div>
              <form onSubmit={handlePurchase}>
                <div className="form-group">
                  <div className="mb-20">
                    <label className="form-label">Select Category</label>
                    {isCategoriesLoading ? (
                      <div className="text-center py-3">
                        <div className="spinner-border spinner-border-sm" role="status">
                          <span className="visually-hidden">Loading categories...</span>
                        </div>
                      </div>
                    ) : (
                      <div className="input-icon">
                        <select
                          className="form-select"
                          value={selectedCategoryId || ''}
                          onChange={(e) => setSelectedCategoryId(e.target.value)}
                          required
                        >
                          <option value="">-- Select Category --</option>
                          {categories.map((cat) => (
                            <option key={cat.id} value={cat.id}>
                              {cat.name}
                            </option>
                          ))}
                        </select>
                      </div>
                    )}
                  </div>
                 {/* <div className="form-group mb-0">
                     <div className="mb-20">
                      <label className="form-label">Amount</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          value={`${currency === 'CHF' ? 'CHF' : '€'} ${getBasePrice().toFixed(2)}`}
                          disabled
                        />
                      </div>
                    </div>
                    <div className="mb-20">
                      <label className="form-label">Currency</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          value={currency}
                          disabled
                        />
                      </div>
                    </div> */}
                    {/* <div className="mb-20">
                    <label className="form-label">Country</label>
                    <div className="input-icon">
                      {isCountriesLoading ? (
                        <div className="text-center py-2">
                          <div className="spinner-border spinner-border-sm" role="status">
                            <span className="visually-hidden">Loading countries...</span>
                          </div>
                        </div>
                      ) : (
                        <select
                          className="form-select"
                          value={selectedCountry || ''}
                          onChange={(e) => setSelectedCountry(e.target.value)}
                        >
                          <option value="">-- Select Country --</option>
                          {countries.map((c) => (
                            <option key={c.id} value={c.code}>
                              {c.name}
                            </option>
                          ))}
                        </select>
                      )}
                      {userProfile && userProfile.countryId && selectedCountry === userProfile.countryId && (
                        <small className="text-muted">Selected from your profile</small>
                      )}
                    </div>
                  </div> 
                  </div>*/}
                </div>
                <div className="form-group">
                  {/* <div className="mb-20">
                    <label className="form-label">Country</label>
                    <div className="input-icon">
                      {isCountriesLoading ? (
                        <div className="text-center py-2">
                          <div className="spinner-border spinner-border-sm" role="status">
                            <span className="visually-hidden">Loading countries...</span>
                          </div>
                        </div>
                      ) : (
                        <select
                          className="form-select"
                          value={selectedCountry || ''}
                          onChange={(e) => setSelectedCountry(e.target.value)}
                        >
                          <option value="">-- Select Country --</option>
                          {countries.map((c) => (
                            <option key={c.id} value={c.code}>
                              {c.name}
                            </option>
                          ))}
                        </select>
                      )}
                      {userProfile && userProfile.countryId && selectedCountry === userProfile.countryId && (
                        <small className="text-muted">Selected from your profile</small>
                      )}
                    </div>
                  </div> */}
                </div>
                <div className="mb-3">
                  <div className="alert alert-info">
                    <strong>Payment Details</strong><br/>
                    <div className='payment-info'>
                      {/* <span>Amount: <strong>{currency === 'CHF' ? 'CHF' : '€'} {getBasePrice().toFixed(2)}</strong></span> */}
                      <span>Amount: <strong>{datacounter?.currencySymbol ?? ''} {getBasePrice().toFixed(2)}</strong></span>
                      {/* <span>Country: <strong>{countries.find(c => c.code === (userProfile?.countryId || selectedCountry))?.name || 'Not selected'}</strong></span> */}
                      <span>Country: <strong>{datacounter?.name ?? ''}</strong></span>
                      <span>Available Payment Methods: <strong>{getPaymentMethods().includes('twint') ? 'Card, TWINT' : getPaymentMethods().includes('sepa_debit') ? 'Card, SEPA Direct Debit' : 'Card'}</strong></span>
                    </div>
                  </div>
                </div>

                <div className="form-group">
                  <div className="mb-20">
                    <label className="form-label">Billing Name (required for export transactions)</label>
                    <div className="input-icon">
                      <input
                        type="text"
                        className="form-control"
                        placeholder={userProfile ? "Name from profile" : "Full Name"}
                        value={billingName}
                        onChange={(e) => setBillingName(e.target.value)}
                      />
                      {userProfile && userProfile.firstName && userProfile.lastName && 
                       billingName === `${userProfile.firstName} ${userProfile.lastName}`.trim() && (
                        <small className="text-muted">Pre-filled from your profile</small>
                      )}
                    </div>
                  </div>
                  {/* <div className="form-group mb-0"> */}
                    <div className="mb-20">
                      <label className="form-label">Address Line 1 (required)</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          placeholder={userProfile ? "Address from profile" : "Street address"}
                          value={addressLine1}
                          onChange={(e) => setAddressLine1(e.target.value)}
                        />
                        {userProfile && userProfile.address && !addressLine1 && (
                          <small className="text-muted">Pre-filled from your profile</small>
                        )}
                      </div>
                    </div>
                  </div>
                <div className="form-group">
                    <div className="mb-20">
                      <label className="form-label">City (required)</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          placeholder={userProfile && userProfile.city ? "City from profile" : "City"}
                          value={city}
                          onChange={(e) => setCity(e.target.value)}
                        />
                        {userProfile && userProfile.city && !city && (
                          <small className="text-muted">Pre-filled from your profile</small>
                        )}
                      </div>
                    </div>
                    <div className="mb-20">
                      <label className="form-label">Postal Code (required)</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          placeholder={userProfile && userProfile.zipCode ? "Postal code from profile" : "Postal code"}
                          value={postalCode}
                          onChange={(e) => setPostalCode(e.target.value)}
                        />
                        {userProfile && userProfile.zipCode && !postalCode && (
                          <small className="text-muted">Pre-filled from your profile</small>
                        )}
                      </div>
                    </div>
                    <div className="mb-20">
                      <label className="form-label">State/Province (required)</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          placeholder={userProfile && userProfile.state ? "State from profile" : "State or province"}
                          value={stateCode}
                          onChange={(e) => setStateCode(e.target.value)}
                        />
                        {userProfile && userProfile.state && !stateCode && (
                          <small className="error-text">Pre-filled from your profile</small>
                        )}
                      </div>
                    </div>
                  {/* </div> */}
                </div>
                <div className="form-group">
                  <div className="">
                    <label className="form-label">Select Payment Method</label>
                    <div className="payment-methods">
                      <div
                        className={`payment-option ${paymentMethod === 'card' ? 'active' : ''}`}
                        role="button"
                        onClick={() => setPaymentMethod('card')}
                      >
                        <span>Card</span>
                        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path fillRule="evenodd" clipRule="evenodd" d="M3.65625 3.9375C2.8796 3.9375 2.25 4.5671 2.25 5.34375V12.6562C2.25 13.4329 2.8796 14.0625 3.65625 14.0625H14.3438C15.1204 14.0625 15.75 13.4329 15.75 12.6562V5.34375C15.75 4.5671 15.1204 3.9375 14.3438 3.9375H3.65625ZM1.125 5.34375C1.125 3.94578 2.25828 2.8125 3.65625 2.8125H14.3438C15.7417 2.8125 16.875 3.94578 16.875 5.34375V12.6562C16.875 14.0542 15.7417 15.1875 14.3438 15.1875H3.65625C2.25828 15.1875 1.125 14.0542 1.125 12.6562V5.34375Z" fill="#EF7310"/>
                          <path fillRule="evenodd" clipRule="evenodd" d="M16.3125 7.80469H1.6875V5.69531H16.3125V7.80469ZM3.44531 10.5469C3.44531 9.96439 3.91751 9.49219 4.5 9.49219H6.1875C6.76999 9.49219 7.24219 9.96439 7.24219 10.5469V11.25C7.24219 11.8325 6.76999 12.3047 6.1875 12.3047H4.5C3.91751 12.3047 3.44531 11.8325 3.44531 11.25V10.5469Z" fill="#EF7310"/>
                        </svg>
                      </div>
                      <div
                        className={`payment-option ${paymentMethod === 'twint' ? 'active' : ''}`}
                        role="button"
                        onClick={() => setPaymentMethod('twint')}
                      >
                        <span>TWINT</span>
                        <svg width="21" height="22" viewBox="0 0 21 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M18.6667 0.5H2.33333C1.04467 0.5 0 1.54467 0 2.83333V19.1667C0 20.4553 1.04467 21.5 2.33333 21.5H18.6667C19.9553 21.5 21 20.4553 21 19.1667V2.83333C21 1.54467 19.9553 0.5 18.6667 0.5Z" fill="black"/>
                          <path d="M16.134 14.0072C16.134 14.1787 16.0115 14.3829 15.8645 14.4646L10.6705 17.4699C10.5235 17.5516 10.2785 17.5516 10.1315 17.4699L4.93747 14.4646C4.79047 14.3829 4.66797 14.1706 4.66797 14.0072V7.99657C4.66797 7.82507 4.79047 7.62091 4.93747 7.53924L10.1315 4.53391C10.2785 4.45224 10.5235 4.45224 10.6705 4.53391L15.8645 7.53924C16.0115 7.62091 16.134 7.83324 16.134 7.99657V14.0072Z" fill="white"/>
                        </svg>
                      </div>
                    </div>
                  </div>
                </div>
               {paymentMethod === 'card' && 
                  <div className="form-group pt-3">
                      <div>                   
                          <label
                            style={{
                              display: "flex",
                              alignItems: "flex-start",
                              gap: "8px",
                              cursor: "pointer",
                              userSelect: "none",
                            }}
                          >
                            <input
                              type="checkbox"
                              checked={isSubscribed}
                              onChange={handleCheckboxChange}
                              style={{ marginTop: "4px" }}
                            />
                            <span>
                              You want to activate subscription for every month? Amount will be
                              automatically deducted for this category.
                            </span>
                          </label>                        
                          {isSubscribed &&
                              <p style={{ color: "green", marginTop: "8px" }}>
                                  Subscription will auto-renew every month.
                              </p>
                          }
                          </div>
                  </div>
                }
                {/* {paymentMethod === 'card' ? (
                  <div id="cardFields" className="payment-fields active">
                    <div className="form-group">
                      <div className="mb-20">
                        <label className="form-label">Card Number</label>
                        <div className="input-icon">
                          <input
                            type="text"
                            className="form-control"
                            placeholder="Enter Card Number"
                            value={cardNumber || ''}
                            onChange={(e) => setCardNumber(e.target.value)}
                          />
                        </div>
                      </div>
                      <div className="form-group mb-0">
                        <div className="mb-20">
                          <label className="form-label">Expiration Date</label>
                          <div className="input-icon">
                            <input
                              type="text"
                              className="form-control"
                              placeholder="MM/YY"
                              value={expirationDate || ''}
                              onChange={(e) => setExpirationDate(e.target.value)}
                            />
                          </div>
                        </div>
                        <div className="mb-20">
                          <label className="form-label">Security Code</label>
                          <div className="input-icon">
                            <input
                              type="text"
                              className="form-control"
                              placeholder="Enter Security Code"
                              value={securityCode || ''}
                              onChange={(e) => setSecurityCode(e.target.value)}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div id="twintFields" className="payment-fields active">
                    <div className="form-group">
                      <div className="mb-20">
                        <label className="form-label">TWINT Mobile</label>
                        <div className="input-icon">
                          <input
                            type="text"
                            className="form-control"
                            placeholder="Enter TWINT mobile number"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                )} */}
                <button 
                  type="submit" 
                  className="w-100 mt-4 custom-btn secondary-btn"
                  // disabled={isSubmitting || !selectedCategoryId || isCategoriesLoading}
                  disabled={isSubmitting || isCategoriesLoading}
                >
                  {isSubmitting ? (
                    <>
                      <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                      Processing...
                    </>
                  ) : (
                    'Pay Now'
                  )}
                </button>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Stripe Payment Modal */}
      {showAddMembershipModal && showPaymentForm && (
        <div className="modal fade show custom-modal" style={{ display: 'block', backgroundColor: 'rgba(0,0,0,0.5)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content p-3">
              <div className="tab-title mb-3 d-flex justify-content-between align-items-center">
                <h5>Complete Payment</h5>
                <button 
                  type="button" 
                  className="btn-close" 
                  onClick={() => {
                    setShowPaymentForm(false);
                    setShowAddMembershipModal(false);
                    resetForm();
                  }}
                ></button>
              </div>
              {clientSecret ? (
                <StripePaymentForm
                  clientSecret={clientSecret}
                  amount={paymentAmount}
                  currency={paymentCurrency}
                  categoryNames={paymentCategoryNames}
                  onSuccess={handlePaymentSuccess}
                  onError={(msg) => showError(msg, 'Payment Error')}
                  onCancel={() => {
                    setShowPaymentForm(false);
                  }}
                />
              ) : (
                <div className="text-center py-4">
                  <div className="spinner-border" role="status">
                    <span className="visually-hidden">Loading payment...</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </FreelancerLayout>
  );
}