// app/main/consultant/page.tsx
'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { 
  Search, Filter, MapPin, Star, DollarSign, Users, 
  Award, ChevronDown, ChevronUp, X, Loader2,
  Shield, CheckCircle, Sparkles, Grid, List,
  Calendar, Globe, Zap, Phone, Mail, Clock,
  Target, Languages, Briefcase
} from 'lucide-react';

interface Consultant {
  id: number;
  user_id: number;
  name: string;
  company_name: string;
  city: string;
  state: string;
  nationality: string;
  average_rating: number;
  rating_count: number;
  services: string[];
  specialization: string[];
  consultation_fee: number;
  consultation_currency: string;
  profile_picture: string | null;
  experience_years: number | null;
  verified: boolean;
  digital_only: boolean;
  premium_featured: number | null;
  seo_slug: string | null;
  phone: string | null;
  email: string | null;
  languages: string[];
  target_countries: string[];
  response_time: string;
  availability: string;
  designation: string;
  profile_status: string;
}

interface Pagination {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

interface FilterState {
  city: string;
  state: string;
  nationality: string;
  specialization: string;
  minRating: string;
  maxFee: string;
  verification: boolean;
  digitalOnly: boolean;
  targetCountry: string;
  language: string;
}

import { Suspense } from 'react';

export default function ConsultantsPageWrapper() {
  return (
    <Suspense fallback={<div>Loading consultants...</div>}>
      <ConsultantsPage />
    </Suspense>
  );
}

function ConsultantsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [consultants, setConsultants] = useState<Consultant[]>([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState<Pagination | null>(null);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showFilters, setShowFilters] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'featured' | 'rating' | 'fee-low' | 'fee-high'>('featured');
  const [isFilterApplied, setIsFilterApplied] = useState(false);
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  
  const [filters, setFilters] = useState<FilterState>({
    city: '',
    state: '',
    nationality: '',
    specialization: '',
    minRating: '',
    maxFee: '',
    verification: false,
    digitalOnly: false,
    targetCountry: '',
    language: ''
  });

  const [availableCities, setAvailableCities] = useState<string[]>([]);
  const [availableStates, setAvailableStates] = useState<string[]>([]);
  const [availableNationalities, setAvailableNationalities] = useState<string[]>([]);
  const [availableSpecializations, setAvailableSpecializations] = useState<string[]>([]);
  const [availableLanguages, setAvailableLanguages] = useState<string[]>([]);
  const [availableTargetCountries, setAvailableTargetCountries] = useState<string[]>([]);

  // Load initial data and filter options
  useEffect(() => {
    const initialPage = parseInt(searchParams.get('page') || '1');
    fetchConsultants(initialPage);
    fetchFilterOptions();
  }, []);

  // Handle search with debouncing
  useEffect(() => {
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    searchTimeoutRef.current = setTimeout(() => {
      fetchConsultants(1); // Always go to page 1 when searching
    }, 500);

    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [searchQuery]);

  // Apply filters when they change
  useEffect(() => {
    checkIfFiltersApplied();
    fetchConsultants(1); // Reset to page 1 when filters change
  }, [filters, sortBy]);

  const checkIfFiltersApplied = () => {
    const hasFilter = Object.values(filters).some(value => {
      if (typeof value === 'boolean') return value === true;
      if (typeof value === 'string') return value !== '';
      return false;
    });
    setIsFilterApplied(hasFilter || searchQuery !== '');
  };

  const fetchConsultants = async (page = 1) => {
    try {
      setLoading(true);
      
      const params = new URLSearchParams();
      params.set('page', page.toString());
      params.set('limit', '12');
      
      // Always include search query in API call
      if (searchQuery) {
        params.set('search', searchQuery);
      }
      
      // Apply all filters to API call
      if (filters.city) params.set('city', filters.city);
      if (filters.state) params.set('state', filters.state);
      if (filters.nationality) params.set('nationality', filters.nationality);
      if (filters.specialization) params.set('specialization', filters.specialization);
      if (filters.minRating) params.set('minRating', filters.minRating);
      if (filters.maxFee) params.set('maxFee', filters.maxFee);
      if (filters.verification) params.set('verification', 'true');
      if (filters.digitalOnly) params.set('digitalOnly', 'true');
      if (filters.targetCountry) params.set('targetCountry', filters.targetCountry);
      if (filters.language) params.set('language', filters.language);
      
      // Add sorting
      if (sortBy) {
        params.set('sort', sortBy);
      }

      const response = await fetch(`/api/frontend/consultants?${params}`);
      const data = await response.json();
      
      if (data.success) {
        setConsultants(data.data);
        setPagination(data.pagination);
        
        // Update URL with page number
        const newParams = new URLSearchParams(searchParams.toString());
        newParams.set('page', page.toString());
        router.replace(`?${newParams.toString()}`, { scroll: false });
      }
    } catch (error) {
      console.error('Error fetching consultants:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchFilterOptions = async () => {
    try {
      const response = await fetch('/api/frontend/consultants/filter-options');
      const data = await response.json();
      
      if (data.success) {
        setAvailableCities(data.cities || []);
        setAvailableStates(data.states || []);
        setAvailableNationalities(data.nationalities || []);
        setAvailableSpecializations(data.specializations || []);
        setAvailableLanguages(data.languages || []);
        setAvailableTargetCountries(data.targetCountries || []);
      }
    } catch (error) {
      console.error('Error fetching filter options:', error);
    }
  };

  const resetFilters = () => {
    setFilters({
      city: '',
      state: '',
      nationality: '',
      specialization: '',
      minRating: '',
      maxFee: '',
      verification: false,
      digitalOnly: false,
      targetCountry: '',
      language: ''
    });
    setSearchQuery('');
    setSortBy('featured');
    fetchConsultants(1);
  };

  const handlePageChange = (page: number) => {
    fetchConsultants(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const getPremiumBadge = (level: number) => {
    const badges = [
      { label: 'Featured', color: 'bg-gradient-to-r from-blue-500 to-blue-600', icon: Sparkles },
      { label: 'Premium', color: 'bg-gradient-to-r from-purple-500 to-purple-600', icon: Award },
      { label: 'Elite', color: 'bg-gradient-to-r from-amber-500 to-amber-600', icon: Star },
      { label: 'Platinum', color: 'bg-gradient-to-r from-gray-700 to-gray-900', icon: Shield },
      { label: 'Diamond', color: 'bg-gradient-to-r from-cyan-500 to-blue-500', icon: DiamondIcon }
    ];
    
    if (level >= 1 && level <= 5) {
      const badge = badges[level - 1];
      const Icon = badge.icon;
      return (
        <div className={`px-3 py-1.5 ${badge.color} text-white rounded-full text-xs font-bold flex items-center gap-1.5 shadow-lg`}>
          <Icon className="w-3.5 h-3.5" />
          {badge.label}
        </div>
      );
    }
    return null;
  };

  const getRatingColor = (rating: number) => {
    if (rating >= 4.5) return 'bg-gradient-to-r from-emerald-500 to-green-500';
    if (rating >= 4.0) return 'bg-gradient-to-r from-green-500 to-green-400';
    if (rating >= 3.5) return 'bg-gradient-to-r from-yellow-500 to-yellow-400';
    if (rating >= 3.0) return 'bg-gradient-to-r from-amber-500 to-amber-400';
    return 'bg-gradient-to-r from-red-500 to-red-400';
  };

  const getAvailabilityBadge = (availability: string) => {
    switch(availability?.toLowerCase()) {
      case 'high':
        return <span className="px-2 py-1 bg-emerald-100 text-emerald-800 text-xs font-medium rounded-full">High Availability</span>;
      case 'limited':
        return <span className="px-2 py-1 bg-amber-100 text-amber-800 text-xs font-medium rounded-full">Limited Spots</span>;
      case 'waitlist':
        return <span className="px-2 py-1 bg-red-100 text-red-800 text-xs font-medium rounded-full">Waitlist Only</span>;
      default:
        return <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">Available</span>;
    }
  };

  // Consultant Card Component
  const ConsultantCard = ({ consultant, viewMode }: { consultant: Consultant, viewMode: 'grid' | 'list' }) => (
    <div
      className={`group bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 border border-gray-200/70 hover:border-blue-300 overflow-hidden ${
        viewMode === 'list' ? 'flex' : ''
      } cursor-pointer`}
      onClick={() => consultant.seo_slug && router.push(`/consultant/${consultant.seo_slug}`)}
    >
      {/* Premium Badge */}
      {consultant.premium_featured && (
        <div className="absolute top-4 left-4 z-20">
          {getPremiumBadge(consultant.premium_featured)}
        </div>
      )}
      
      {/* Profile Image Section */}
      <div className={viewMode === 'list' 
        ? 'w-56 flex-shrink-0 relative' 
        : 'h-56 relative'
      }>
        {consultant.profile_picture ? (
          <img
            src={consultant.profile_picture}
            alt={consultant.company_name}
            className={`w-full h-full object-cover transition-transform duration-500 group-hover:scale-105 ${
              viewMode === 'list' ? 'rounded-l-2xl' : 'rounded-t-2xl'
            }`}
          />
        ) : (
          <div className={`w-full h-full bg-gradient-to-br from-blue-600 to-cyan-500 flex items-center justify-center ${
            viewMode === 'list' ? 'rounded-l-2xl' : 'rounded-t-2xl'
          }`}>
            <span className="text-5xl font-bold text-white">
              {consultant.company_name?.charAt(0).toUpperCase() || 'C'}
            </span>
          </div>
        )}
        
        {/* Verified & Status Badges */}
        <div className="absolute bottom-3 right-3 flex flex-col gap-2">
          {consultant.verified && (
            <div className="w-8 h-8 bg-gradient-to-r from-emerald-500 to-green-500 rounded-full flex items-center justify-center shadow-lg" 
                 title="Verified Consultant">
              <CheckCircle className="w-4 h-4 text-white" />
            </div>
          )}
          {consultant.digital_only && (
            <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-cyan-500 rounded-full flex items-center justify-center shadow-lg"
                 title="Digital Consultations Only">
              <Globe className="w-4 h-4 text-white" />
            </div>
          )}
        </div>
      </div>
      
      {/* Content Section */}
      <div className={`p-6 ${viewMode === 'list' ? 'flex-1' : ''}`}>
        <div className="flex items-start justify-between mb-4">
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <h3 className="text-xl font-bold text-gray-900 group-hover:text-blue-700 transition-colors">
                {consultant.company_name}
              </h3>
              {consultant.designation && (
                <span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded">
                  {consultant.designation}
                </span>
              )}
            </div>
            {/*<p className="text-gray-600">{consultant.name}</p>*/}
          </div>
          
          {/* Fee Display */}
          <div className="text-right">
            <div className="text-2xl font-bold text-emerald-700">
              {getFormattedFee(consultant.consultation_fee, consultant.consultation_currency)}
            </div>
            <div className="text-xs text-gray-500">Consultation Fee</div>
          </div>
        </div>
        
        {/* Rating & Stats */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className={`flex items-center px-3 py-1.5 rounded-full ${getRatingColor(consultant.average_rating || 0)} text-white`}>
              <Star className="w-4 h-4 fill-white" />
              <span className="ml-1.5 font-bold">{(consultant.average_rating || 0).toFixed(1)}</span>
              <span className="ml-1 text-white/90 text-sm">({consultant.rating_count || 0})</span>
            </div>
          </div>
          
          {getAvailabilityBadge(consultant.availability)}
        </div>
        
        {/* Location & Nationality */}
        <div className="flex items-center gap-4 text-gray-600 mb-4">
          <div className="flex items-center gap-1.5">
            <MapPin className="w-4 h-4" />
            <span>
              {consultant.city}{consultant.state ? `, ${consultant.state}` : ''}
              {consultant.nationality ? `, ${consultant.nationality}` : ''}
            </span>
          </div>
        </div>
        
        {/* Specializations */}
        <div className="mb-4">
          <div className="flex items-center gap-2 mb-2">
            <Briefcase className="w-4 h-4 text-gray-500" />
            <span className="text-sm font-medium text-gray-700">Specializations:</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {consultant.specialization?.slice(0, 3).map((spec, idx) => (
              <span
                key={idx}
                className="px-3 py-1.5 bg-gradient-to-r from-blue-50 to-cyan-50 text-blue-700 text-xs font-medium rounded-lg border border-blue-100"
              >
                {spec}
              </span>
            ))}
            {consultant.specialization?.length > 3 && (
              <span className="px-2 py-1 bg-gray-100 text-gray-600 text-xs font-medium rounded-lg">
                +{consultant.specialization.length - 3} more
              </span>
            )}
          </div>
        </div>
        
        {/* Languages & Target Countries */}
        <div className="grid grid-cols-2 gap-3 mb-5">
          {consultant.languages?.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-1">
                <Languages className="w-3.5 h-3.5 text-gray-500" />
                <span className="text-xs font-medium text-gray-700">Languages</span>
              </div>
              <div className="text-sm text-gray-600">
                {consultant.languages.slice(0, 2).join(', ')}
                {consultant.languages.length > 2 && '...'}
              </div>
            </div>
          )}
          
          {consultant.target_countries?.length > 0 && (
            <div>
              <div className="flex items-center gap-2 mb-1">
                <Target className="w-3.5 h-3.5 text-gray-500" />
                <span className="text-xs font-medium text-gray-700">Target Countries</span>
              </div>
              <div className="text-sm text-gray-600">
                {consultant.target_countries.slice(0, 2).join(', ')}
                {consultant.target_countries.length > 2 && '...'}
              </div>
            </div>
          )}
        </div>
        
        {/* Action Buttons */}
        <div className="flex gap-3">
          <Link
            href={`/consultant/${consultant.seo_slug}`}
            onClick={(e) => e.stopPropagation()}
            className="flex-1 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-medium rounded-xl hover:from-blue-700 hover:to-blue-800 transition-all duration-300 shadow-md hover:shadow-lg group-hover:shadow-xl flex items-center justify-center gap-2"
          >
            <Calendar className="w-4 h-4" />
            View Detail
          </Link>
        </div>
      </div>
    </div>
  );

  // Pagination Component
  const PaginationComponent = () => {
    if (!pagination || pagination.totalPages <= 1) return null;
    
    const renderPageNumbers = () => {
      const pages = [];
      const maxVisiblePages = 5;
      let startPage = Math.max(1, pagination.page - Math.floor(maxVisiblePages / 2));
      let endPage = Math.min(pagination.totalPages, startPage + maxVisiblePages - 1);
      
      if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
      }
      
      // First page
      if (startPage > 1) {
        pages.push(
          <button
            key={1}
            onClick={() => handlePageChange(1)}
            className={`w-10 h-10 rounded-xl transition-all duration-300 ${
              pagination.page === 1
                ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg'
                : 'bg-white text-gray-700 border border-gray-300 hover:border-blue-400 hover:text-blue-600 hover:shadow'
            }`}
          >
            1
          </button>
        );
        if (startPage > 2) {
          pages.push(
            <span key="ellipsis-start" className="w-10 h-10 flex items-center justify-center text-gray-500">
              ...
            </span>
          );
        }
      }
      
      // Middle pages
      for (let i = startPage; i <= endPage; i++) {
        if (i === 1 && startPage > 1) continue;
        pages.push(
          <button
            key={i}
            onClick={() => handlePageChange(i)}
            className={`w-10 h-10 rounded-xl transition-all duration-300 ${
              pagination.page === i
                ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg'
                : 'bg-white text-gray-700 border border-gray-300 hover:border-blue-400 hover:text-blue-600 hover:shadow'
            }`}
          >
            {i}
          </button>
        );
      }
      
      // Last page
      if (endPage < pagination.totalPages) {
        if (endPage < pagination.totalPages - 1) {
          pages.push(
            <span key="ellipsis-end" className="w-10 h-10 flex items-center justify-center text-gray-500">
              ...
            </span>
          );
        }
        pages.push(
          <button
            key={pagination.totalPages}
            onClick={() => handlePageChange(pagination.totalPages)}
            className={`w-10 h-10 rounded-xl transition-all duration-300 ${
              pagination.page === pagination.totalPages
                ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white shadow-lg'
                : 'bg-white text-gray-700 border border-gray-300 hover:border-blue-400 hover:text-blue-600 hover:shadow'
            }`}
          >
            {pagination.totalPages}
          </button>
        );
      }
      
      return pages;
    };
    
    return (
      <div className="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="text-gray-600">
          Showing {(pagination.page - 1) * pagination.limit + 1} to{' '}
          {Math.min(pagination.page * pagination.limit, pagination.total)} of{' '}
          {pagination.total} consultants
        </div>
        
        <div className="flex items-center gap-2">
          <button
            onClick={() => handlePageChange(pagination.page - 1)}
            disabled={!pagination.hasPrevPage}
            className="px-4 py-2 bg-white border border-gray-300 rounded-xl hover:border-blue-400 hover:text-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 flex items-center gap-2"
          >
            <ChevronUp className="w-4 h-4 rotate-90" />
            Previous
          </button>
          
          <div className="flex items-center gap-2">
            {renderPageNumbers()}
          </div>
          
          <button
            onClick={() => handlePageChange(pagination.page + 1)}
            disabled={!pagination.hasNextPage}
            className="px-4 py-2 bg-white border border-gray-300 rounded-xl hover:border-blue-400 hover:text-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 flex items-center gap-2"
          >
            Next
            <ChevronUp className="w-4 h-4 -rotate-90" />
          </button>
        </div>
      </div>
    );
  };

  // Custom Diamond Icon component
  const DiamondIcon = ({ className }: { className?: string }) => (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2L2 9L12 22L22 9L12 2Z" />
    </svg>
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-blue-50/30">
      {/* Hero Section */}
      <div className="bg-gradient-to-r from-[#0B6F78] via-[#0a5c7a] to-[#0a306b] text-white relative overflow-hidden">
        <div className="absolute inset-0 bg-[url('/grid-pattern.svg')] opacity-10"></div>
        <div className="container mx-auto px-4 py-12 md:py-16 relative z-10">
          <div className="max-w-4xl mx-auto text-center">
            <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 bg-clip-text text-transparent bg-gradient-to-r from-white to-blue-100">
              Find Your Perfect Study Abroad Consultant
            </h1>
            <p className="text-xl text-blue-100 mb-8">
              Connect with verified experts who will guide you through your study abroad journey
            </p>
            
            {/* Search Bar */}
            <div className="relative max-w-2xl mx-auto">
              <div className="relative">
                <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-blue-300" />
                <input
                  type="text"
                  placeholder="Search by name, company, specialization, country..."
                  className="w-full pl-12 pr-4 py-4 rounded-2xl bg-white/10 backdrop-blur-sm border-2 border-white/20 text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-blue-300 hover:text-white"
                  >
                    <X className="w-5 h-5" />
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Sidebar Filters - Simplified */}
          <div className={`lg:w-1/4 ${showFilters ? 'block' : 'hidden lg:block'}`}>
            <div className="bg-white rounded-2xl shadow-xl border border-gray-200/70 p-6 sticky top-8">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                  <Filter className="w-5 h-5 text-blue-600" />
                  Filters
                  {isFilterApplied && (
                    <span className="px-2 py-1 bg-blue-100 text-blue-700 text-xs font-medium rounded-full">
                      Active
                    </span>
                  )}
                </h2>
                <button
                  onClick={resetFilters}
                  className="text-sm text-blue-600 hover:text-blue-700 font-medium hover:underline"
                >
                  Clear All
                </button>
              </div>
              
              <div className="space-y-6">
                {/* Location Filters */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <MapPin className="w-4 h-4 text-gray-500" />
                    Location
                  </h3>
                  <div className="space-y-3">
                    <select
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                      value={filters.nationality}
                      onChange={(e) => setFilters({...filters, nationality: e.target.value})}
                    >
                      <option value="">All Countries</option>
                      {availableNationalities.map(country => (
                        <option key={country} value={country}>{country}</option>
                      ))}
                    </select>
                    
                    <select
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                      value={filters.state}
                      onChange={(e) => setFilters({...filters, state: e.target.value})}
                    >
                      <option value="">All States</option>
                      {availableStates.map(state => (
                        <option key={state} value={state}>{state}</option>
                      ))}
                    </select>
                    
                    <select
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                      value={filters.city}
                      onChange={(e) => setFilters({...filters, city: e.target.value})}
                    >
                      <option value="">All Cities</option>
                      {availableCities.map(city => (
                        <option key={city} value={city}>{city}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Specialization Filter */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3">Specialization</h3>
                  <select
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                    value={filters.specialization}
                    onChange={(e) => setFilters({...filters, specialization: e.target.value})}
                  >
                    <option value="">All Specializations</option>
                    {availableSpecializations.map(spec => (
                      <option key={spec} value={spec}>{spec}</option>
                    ))}
                  </select>
                </div>

                {/* Target Countries */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3">Target Study Countries</h3>
                  <select
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                    value={filters.targetCountry}
                    onChange={(e) => setFilters({...filters, targetCountry: e.target.value})}
                  >
                    <option value="">All Countries</option>
                    {availableTargetCountries.map(country => (
                      <option key={country} value={country}>{country}</option>
                    ))}
                  </select>
                </div>

                {/* Languages */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3">Languages</h3>
                  <select
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                    value={filters.language}
                    onChange={(e) => setFilters({...filters, language: e.target.value})}
                  >
                    <option value="">All Languages</option>
                    {availableLanguages.map(lang => (
                      <option key={lang} value={lang}>{lang}</option>
                    ))}
                  </select>
                </div>

                {/* Rating Filter */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <Star className="w-4 h-4 text-amber-500" />
                    Minimum Rating
                  </h3>
                  <div className="grid grid-cols-4 gap-2">
                    {[4.5, 4.0, 3.5, 3.0].map(rating => (
                      <button
                        key={rating}
                        onClick={() => setFilters({
                          ...filters,
                          minRating: filters.minRating === rating.toString() ? '' : rating.toString()
                        })}
                        className={`py-2 text-center rounded-lg border transition-colors ${
                          filters.minRating === rating.toString()
                            ? 'bg-gradient-to-r from-amber-50 to-yellow-50 border-amber-500 text-amber-700 font-bold'
                            : 'border-gray-300 text-gray-700 hover:border-amber-400 hover:bg-amber-50/50'
                        }`}
                      >
                        {rating}+
                      </button>
                    ))}
                  </div>
                </div>

                {/* Fee Range */}
                <div>
                  <h3 className="font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <DollarSign className="w-4 h-4 text-emerald-500" />
                    Max Consultation Fee
                  </h3>
                  <div className="space-y-2">
                    <input
                      type="number"
                      placeholder="e.g., 500"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
                      value={filters.maxFee}
                      onChange={(e) => setFilters({...filters, maxFee: e.target.value})}
                    />
                  </div>
                </div>

                {/* Toggle Filters */}
                <div className="space-y-3 pt-4 border-t border-gray-200">
                  <label className="flex items-center gap-3 cursor-pointer p-2 rounded-lg hover:bg-gray-50">
                    <input
                      type="checkbox"
                      className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                      checked={filters.verification}
                      onChange={(e) => setFilters({...filters, verification: e.target.checked})}
                    />
                    <span className="text-gray-700 font-medium">Verified Consultants Only</span>
                    <CheckCircle className="w-4 h-4 text-emerald-500 flex-shrink-0" />
                  </label>
                  
                  <label className="flex items-center gap-3 cursor-pointer p-2 rounded-lg hover:bg-gray-50">
                    <input
                      type="checkbox"
                      className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                      checked={filters.digitalOnly}
                      onChange={(e) => setFilters({...filters, digitalOnly: e.target.checked})}
                    />
                    <span className="text-gray-700 font-medium">Digital Consultations Only</span>
                    <Globe className="w-4 h-4 text-blue-500 flex-shrink-0" />
                  </label>
                </div>
              </div>
              
              {/* Apply Filters Button for Mobile */}
              <button
                onClick={() => setShowFilters(false)}
                className="mt-8 w-full py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-medium rounded-xl hover:from-blue-700 hover:to-blue-800 transition-all duration-300 lg:hidden"
              >
                Apply Filters
              </button>
            </div>
          </div>

          {/* Main Content Area */}
          <div className="lg:w-3/4">
            {/* Header Controls */}
            <div className="bg-white rounded-2xl shadow-lg border border-gray-200/70 p-6 mb-8">
              <div className="flex flex-col sm:flex-row items-center justify-between gap-6">
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">
                    {pagination?.total || 0} Expert Consultants
                  </h2>
                  <p className="text-gray-600 mt-1">
                    Showing {consultants.length} on this page
                    {isFilterApplied && ' • Filters applied'}
                  </p>
                </div>
                
                <div className="flex items-center gap-4">
                  {/* View Mode Toggle */}
                  <div className="flex items-center gap-2 bg-gray-100 p-1 rounded-xl">
                    <button
                      onClick={() => setViewMode('grid')}
                      className={`p-2.5 rounded-lg transition-all duration-300 ${
                        viewMode === 'grid' 
                          ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md' 
                          : 'hover:bg-gray-200 text-gray-700'
                      }`}
                      title="Grid View"
                    >
                      <Grid className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => setViewMode('list')}
                      className={`p-2.5 rounded-lg transition-all duration-300 ${
                        viewMode === 'list' 
                          ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md' 
                          : 'hover:bg-gray-200 text-gray-700'
                      }`}
                      title="List View"
                    >
                      <List className="w-4 h-4" />
                    </button>
                  </div>
                  
                  {/* Sort By - Simplified */}
                  <div className="relative">
                    <select
                      className="px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white appearance-none pr-10"
                      value={sortBy}
                      onChange={(e) => setSortBy(e.target.value as any)}
                    >
                      <option value="featured">Featured First</option>
                      <option value="rating">Highest Rated</option>
                      <option value="fee-low">Lowest Fee</option>
                      <option value="fee-high">Highest Fee</option>
                    </select>
                    <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none" />
                  </div>
                  
                  {/* Mobile Filter Toggle */}
                  <button
                    onClick={() => setShowFilters(!showFilters)}
                    className="lg:hidden p-2.5 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl hover:from-blue-600 hover:to-blue-700 transition-all duration-300 shadow-md hover:shadow-lg"
                  >
                    <Filter className="w-5 h-5" />
                  </button>
                </div>
              </div>
            </div>

            {/* Loading State */}
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <Loader2 className="w-16 h-16 text-blue-600 animate-spin mx-auto mb-4" />
                  <p className="text-gray-600 text-lg">Loading consultants...</p>
                  <p className="text-gray-500 text-sm mt-2">Finding the best study abroad experts for you</p>
                </div>
              </div>
            ) : consultants.length === 0 ? (
              <div className="text-center py-16 bg-gradient-to-br from-white to-blue-50 rounded-2xl shadow-sm border border-gray-200/70">
                <div className="w-24 h-24 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-full flex items-center justify-center mx-auto mb-6">
                  <Search className="w-12 h-12 text-blue-400" />
                </div>
                <h3 className="text-2xl font-bold text-gray-900 mb-2">No Consultants Found</h3>
                <p className="text-gray-600 mb-6 max-w-md mx-auto">
                  {isFilterApplied 
                    ? 'Try adjusting your filters or search criteria to find more consultants'
                    : 'No consultants available at the moment. Please check back later.'
                  }
                </p>
                {isFilterApplied && (
                  <button
                    onClick={resetFilters}
                    className="px-8 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl hover:from-blue-700 hover:to-blue-800 transition-all duration-300 shadow-md hover:shadow-lg font-medium"
                  >
                    Reset Filters
                  </button>
                )}
              </div>
            ) : (
              <>
                {/* Grid/List View */}
                <div className={viewMode === 'grid' 
                  ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6' 
                  : 'space-y-6'
                }>
                  {consultants.map((consultant) => (
                    <ConsultantCard 
                      key={consultant.id} 
                      consultant={consultant} 
                      viewMode={viewMode} 
                    />
                  ))}
                </div>

                {/* Pagination */}
                <PaginationComponent />
              </>
            )}
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="bg-gradient-to-r from-[#0B6F78]/10 via-[#0a5c7a]/10 to-[#0a306b]/10 py-12 mt-12">
        <div className="container mx-auto px-4">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div className="bg-white rounded-2xl p-6 text-center shadow-lg border border-gray-200/70 hover:shadow-xl transition-shadow duration-300">
              <div className="text-3xl font-bold text-blue-600 mb-2">
                {pagination?.total || 250}+
              </div>
              <div className="text-gray-700 font-medium">Verified Consultants</div>
            </div>
            <div className="bg-white rounded-2xl p-6 text-center shadow-lg border border-gray-200/70 hover:shadow-xl transition-shadow duration-300">
              <div className="text-3xl font-bold text-emerald-600 mb-2">
                {consultants.filter(c => c.verified).length || 95}%
              </div>
              <div className="text-gray-700 font-medium">Verified Rate</div>
            </div>
            <div className="bg-white rounded-2xl p-6 text-center shadow-lg border border-gray-200/70 hover:shadow-xl transition-shadow duration-300">
              <div className="text-3xl font-bold text-purple-600 mb-2">
                {consultants.reduce((acc, c) => acc + (c.rating_count || 0), 0).toLocaleString()}+
              </div>
              <div className="text-gray-700 font-medium">Total Reviews</div>
            </div>
            <div className="bg-white rounded-2xl p-6 text-center shadow-lg border border-gray-200/70 hover:shadow-xl transition-shadow duration-300">
              <div className="text-3xl font-bold text-amber-600 mb-2">
                {(consultants.reduce((acc, c) => acc + (c.average_rating || 0), 0) / (consultants.length || 1)).toFixed(1)}
              </div>
              <div className="text-gray-700 font-medium">Avg. Rating</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Helper function for formatting fee
function getFormattedFee(fee: number, currency: string) {
  if (fee === 0) return 'Free';
  return `${currency}${fee.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
}