'use client';

import { useState, useEffect, useCallback, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
import { FilterModal, FilterState, FilterField } from '@/components/profiles/FilterModal';
import { agentsService, AgentType, PublicAgentProfile, SearchAgentsParams } from '@/services/agents.service';
import { profileSectionsService, FilterableField } from '@/services/profile-sections.service';
import { uploadService } from '@/services/upload.service';

interface FilterSectionProps {
  title: string;
  options: { label: string; value: string }[];
  selectedOptions: string[];
  onToggle: (optionValue: string) => void;
  showMore?: boolean;
}

function FilterSection({ title, options, selectedOptions, onToggle, showMore }: FilterSectionProps) {
  const [expanded, setExpanded] = useState(false);
  const displayOptions = expanded ? options : options.slice(0, 6);

  return (
    <div className="pb-4 mb-4">
      <div className="flex items-center justify-between mb-3">
        <h3 className="font-fractul font-semibold text-[14px] text-[#00293d]">{title}</h3>
        <button className="text-[#00293d]">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M2 4L6 8L10 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>
      <div className="space-y-2">
        {displayOptions.map((option) => (
          <label key={option.value} className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={selectedOptions.includes(option.value)}
              onChange={() => onToggle(option.value)}
              className="w-4 h-4 rounded border-2 border-[#00293d]/30 appearance-none cursor-pointer checked:bg-[#e58625] checked:border-[#e58625] checked:bg-[url('data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%2016%2016%22%20fill%3D%22white%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M12.207%204.793a1%201%200%20010%201.414l-5%205a1%201%200%2001-1.414%200l-2-2a1%201%200%20011.414-1.414L6.5%209.086l4.293-4.293a1%201%200%20011.414%200z%22%2F%3E%3C%2Fsvg%3E')] checked:bg-center checked:bg-no-repeat focus:ring-2 focus:ring-[#e58625]/50"
            />
            <span className="font-serif text-[13px] text-[#00293d]">{option.label}</span>
          </label>
        ))}
      </div>
      {showMore && options.length > 6 && (
        <button
          onClick={() => setExpanded(!expanded)}
          className="mt-2 font-serif text-[13px] text-[#e58625] hover:underline"
        >
          {expanded ? 'Show Less' : 'Show More'}
        </button>
      )}
    </div>
  );
}

interface ProfileCardProps {
  profile: PublicAgentProfile;
  resolvedAvatarUrl?: string | null;
}

function ProfileCard({ profile, resolvedAvatarUrl }: ProfileCardProps) {
  const [showFullBio, setShowFullBio] = useState(false);
  const [showAllTags, setShowAllTags] = useState(false);
  const getProfileImageUrl = (): string | null => {
    if (resolvedAvatarUrl) return resolvedAvatarUrl;
    if (profile.avatar?.startsWith('/')) return profile.avatar;
    return null;
  };

  // Format member since date
  const formatMemberSince = (dateString?: string) => {
    if (!dateString) return 'Member';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
    } catch {
      return 'Member';
    }
  };

  // Get location string - check dynamic field values first, then fallback to legacy columns
  const getLocation = () => {
    let cityValue: string | null = null;
    let stateValue: string | null = null;

    // Helper to format snake_case to Title Case
    const formatValue = (v: string) => v.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');

    // First, check fieldValues for state and city (dynamic profile fields)
    if (profile.fieldValues && profile.fieldValues.length > 0) {
      const stateField = profile.fieldValues.find(fv => fv.field.slug === 'state');
      const cityField = profile.fieldValues.find(fv => fv.field.slug === 'city');

      if (stateField && stateField.jsonValue) {
        const value = stateField.jsonValue;
        if (Array.isArray(value) && value.length > 0) {
          // For multiselect, join all selected values
          stateValue = value.map(v => formatValue(String(v))).join(', ');
        } else if (typeof value === 'string' && value.trim()) {
          stateValue = formatValue(value);
        }
      }

      if (cityField && cityField.jsonValue) {
        const value = cityField.jsonValue;
        if (Array.isArray(value) && value.length > 0) {
          // For multiselect, join all selected values
          cityValue = value.map(v => formatValue(String(v))).join(', ');
        } else if (typeof value === 'string' && value.trim()) {
          cityValue = formatValue(value);
        }
      }
    }

    // Fallback to legacy profile columns if dynamic fields not found
    if (!cityValue && profile.city) {
      cityValue = profile.city;
    }
    if (!stateValue && profile.state) {
      stateValue = profile.state;
    }

    // Build location string
    if (cityValue && stateValue) {
      return `${cityValue}, ${stateValue}`;
    }
    if (cityValue && profile.country) {
      return `${cityValue}, ${profile.country}`;
    }
    if (stateValue && profile.country) {
      return `${stateValue}, ${profile.country}`;
    }
    if (cityValue) {
      return cityValue;
    }
    if (stateValue) {
      return stateValue;
    }
    if (profile.country) {
      return profile.country;
    }
    if (profile.serviceAreas && profile.serviceAreas.length > 0) {
      return profile.serviceAreas[0];
    }
    return null;
  };

  // Extract expertise tags from fieldValues - only include expertise-related fields
  const getExpertiseTags = (): string[] => {
    const tags: string[] = [];

    // Only include expertise-related field slugs (matching profileDataMapper.ts)
    const expertiseFieldSlugs = [
      'about_me_expertise',
      'expertise_areas',
      'specializations',
      'areas_of_expertise',
      'expertise',
    ];

    // Add from fieldValues - only expertise-related fields
    if (profile.fieldValues && profile.fieldValues.length > 0) {
      profile.fieldValues.forEach((fv) => {
        // Only include expertise-related fields
        if (!expertiseFieldSlugs.includes(fv.field.slug)) {
          return;
        }

        const value = fv.jsonValue;
        if (Array.isArray(value)) {
          // For multi-select fields, add all selected values
          value.forEach((v) => {
            if (typeof v === 'string' && v.trim()) {
              // Convert snake_case to Title Case for display
              const displayValue = v
                .split('_')
                .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
                .join(' ');
              if (!tags.includes(displayValue)) {
                tags.push(displayValue);
              }
            }
          });
        } else if (typeof value === 'string' && value.trim()) {
          if (!tags.includes(value)) {
            tags.push(value);
          }
        }
      });
    }

    // Add from specializations array (legacy field)
    if (profile.specializations && profile.specializations.length > 0) {
      profile.specializations.forEach((spec) => {
        if (!tags.includes(spec)) {
          tags.push(spec);
        }
      });
    }

    // Add from languages array
    if (profile.languages && profile.languages.length > 0) {
      profile.languages.forEach((lang) => {
        if (!tags.includes(lang)) {
          tags.push(lang);
        }
      });
    }

    return tags;
  };

  // Get description from fieldValues (description field) or fallback to profile.bio
  const getDescription = (): string | null => {
    if (profile.fieldValues && profile.fieldValues.length > 0) {
      const descField = profile.fieldValues.find(fv => fv.field.slug === 'description');
      if (descField && descField.textValue) {
        return descField.textValue;
      }
    }
    return profile.bio;
  };

  const location = getLocation();
  const expertiseTags = getExpertiseTags();
  const description = getDescription();
  const truncatedDescription = description && description.length > 200
    ? description.slice(0, 200) + '...'
    : description || '';

  return (
    <div className="bg-white rounded-[20px] p-4 sm:p-5 flex flex-col sm:flex-row gap-4 sm:gap-5 shadow-[0px_10px_20px_rgba(217,217,217,0.5)]">
      {/* Profile Image & View Profile Button */}
      <div className="flex-shrink-0 flex flex-col items-center">
        <div className="relative w-full sm:w-[200px] h-[200px] rounded-[15px] overflow-hidden bg-[#e8e8e8]">
          {getProfileImageUrl() ? (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img
              src={getProfileImageUrl()!}
              alt={`${profile.firstName} ${profile.lastName}`}
              className="w-full h-full object-cover"
              onError={(e) => {
                const target = e.target as HTMLImageElement;
                target.style.display = 'none';
              }}
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <Image
                src="/assets/icons/user-placeholder-icon.svg"
                alt={`${profile.firstName} ${profile.lastName}`}
                width={64}
                height={64}
                className="opacity-40"
              />
            </div>
          )}
        </div>
        <Link href={`/user/profile/${profile.id}`} className="mt-4">
          <button className="w-[113px] py-2.5 bg-[#e58625] hover:bg-[#d47720] text-[#00293d] font-fractul font-bold text-[14px] rounded-[15px] transition-colors">
            View Profile
          </button>
        </Link>
      </div>

      {/* Profile Info */}
      <div className="flex-1 min-w-0">
        {/* Header Row - Name, Verified, Match Badge */}
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-2">
          <div>
            {/* Name and Verified Badge */}
            <div className="flex items-center gap-2 flex-wrap">
              <h3 className="font-fractul text-[18px] text-[#00293d]">
                <span className="font-bold">{profile.firstName}</span>{' '}
                <span className="font-normal">{profile.lastName}</span>
              </h3>
              {profile.isVerified && (
                <>
                  <Image
                    src="/assets/icons/verified-expert-badge.svg"
                    alt="Verified"
                    width={14}
                    height={15}
                  />
                  <span className="font-serif font-medium text-[14px] text-[#638559]">
                    (Verified Expert)
                  </span>
                </>
              )}
            </div>
            {/* Agent Type */}
            <p className="font-serif text-[14px] text-[#00293d] mt-1">
              {profile.agentType?.name || 'Real Estate Professional'}
            </p>
          </div>

          {/* Match Badge */}
          <div className="bg-[#7d917d] text-white px-4 py-1.5 rounded-full font-serif text-[14px] whitespace-nowrap self-start">
            95% Match
          </div>
        </div>

        {/* Location & Member Since */}
        <div className="flex flex-wrap items-center gap-3 sm:gap-4 mt-3">
          {location && (
            <div className="flex items-center gap-2">
              <Image
                src="/assets/icons/location-pin-icon.svg"
                alt="Location"
                width={16}
                height={15}
              />
              <span className="font-serif font-bold text-[14px] text-[#00293d]">
                {location}
              </span>
            </div>
          )}
          <div className="flex items-center gap-2">
            <Image
              src="/assets/icons/calendar-icon.svg"
              alt="Member Since"
              width={18}
              height={18}
            />
            <span className="font-serif font-medium text-[13px] text-[#00293d]">
              Member Since {formatMemberSince(profile.createdAt)}
            </span>
          </div>
        </div>

        {/* Description */}
        {description && (
          <div className="mt-3">
            <p className="font-serif text-[13px] text-[#00293d] leading-[20px]">
              {showFullBio ? description : truncatedDescription}
              {description.length > 200 && (
                <>
                  {' '}
                  <button
                    onClick={() => setShowFullBio(!showFullBio)}
                    className="font-serif font-bold text-[13px] text-[#00293d] underline"
                  >
                    {showFullBio ? 'Show Less.' : 'Show More.'}
                  </button>
                </>
              )}
            </p>
          </div>
        )}

        {/* Expertise Tags */}
        {expertiseTags.length > 0 && (
          <div className="mt-3">
            <p className="font-fractul font-bold text-[14px] text-[#00293d] mb-2">Expertise:</p>
            <div className="flex flex-wrap gap-2 items-center">
              {(showAllTags ? expertiseTags : expertiseTags.slice(0, 8)).map((tag, index) => (
                <span
                  key={index}
                  className="border border-[#00293d] rounded-[15px] px-3 py-1 font-serif text-[14px] text-[#00293d]"
                >
                  {tag}
                </span>
              ))}
              {expertiseTags.length > 8 && (
                <button
                  onClick={() => setShowAllTags(!showAllTags)}
                  className="font-serif font-bold text-[14px] text-[#00293d] underline ml-1"
                >
                  {showAllTags ? 'Show Less' : `+${expertiseTags.length - 8} more`}
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ProfilesPageContent() {
  const searchParams = useSearchParams();

  // Get URL params directly for use in effects
  const typeFromUrl = searchParams.get('type');
  const nameFromUrl = searchParams.get('name') || '';
  const locationFromUrl = searchParams.get('location') || '';

  // State for API data
  const [agents, setAgents] = useState<PublicAgentProfile[]>([]);
  const [avatarUrls, setAvatarUrls] = useState<Record<string, string>>({});
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [filterFields, setFilterFields] = useState<FilterField[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [totalPages, setTotalPages] = useState(1);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalResults, setTotalResults] = useState(0);

  // State for search and filters - initialize from URL params
  const [searchQuery, setSearchQuery] = useState(nameFromUrl);
  const [activeTypeId, setActiveTypeId] = useState<string | null>(typeFromUrl);
  const [listingType, setListingType] = useState<'agents' | 'lenders'>('agents');
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
  const [filters, setFilters] = useState<FilterState>({});

  // Sync state when URL params change (e.g., browser back/forward, client-side navigation)
  useEffect(() => {
    setActiveTypeId(typeFromUrl);
    setSearchQuery(nameFromUrl);
  }, [typeFromUrl, nameFromUrl]);

  // Fetch agent types and filter fields on mount
  useEffect(() => {
    const fetchInitialData = async () => {
      try {
        const [types, fields] = await Promise.all([
          agentsService.getAgentTypes(),
          profileSectionsService.getFilterableFields(),
        ]);
        setAgentTypes(types);

        // Convert FilterableField to FilterField format
        const filterFieldsData: FilterField[] = fields.map((f: FilterableField) => ({
          slug: f.slug,
          name: f.name,
          fieldType: f.fieldType,
          options: f.options,
        }));
        setFilterFields(filterFieldsData);
      } catch (error) {
        console.error('Failed to fetch initial data:', error);
      }
    };
    fetchInitialData();
  }, []);

  // Fetch agents based on filters
  const fetchAgents = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params: SearchAgentsParams = {
        page: currentPage,
        limit: 10,
        sortBy: 'createdAt',
        sortOrder: 'desc',
      };

      // Add search query
      if (searchQuery) {
        params.search = searchQuery;
      }

      // Add agent type filter
      if (activeTypeId) {
        params.agentTypeId = activeTypeId;
      }

      // Add location search (searches city, state, country, and dynamic field values)
      if (locationFromUrl) {
        params.location = locationFromUrl;
      }

      // Add dynamic profile field filters
      const activeFilters = Object.entries(filters).reduce((acc, [key, values]) => {
        if (values && values.length > 0) {
          acc[key] = values;
        }
        return acc;
      }, {} as Record<string, string[]>);

      if (Object.keys(activeFilters).length > 0) {
        params.filters = activeFilters;
      }

      const response = await agentsService.searchAgents(params);

      // Resolve all avatar URLs via presigned-download-url API
      const urlMap: Record<string, string> = {};
      const avatarPromises = response.data.map(async (agent) => {
        if (agent.avatar && !agent.avatar.startsWith('http') && !agent.avatar.startsWith('/')) {
          try {
            const presignedUrl = await uploadService.getPresignedDownloadUrl(agent.avatar);
            urlMap[agent.id] = presignedUrl;
          } catch {
            // Skip failed URLs, card will show placeholder
          }
        } else if (agent.avatar) {
          urlMap[agent.id] = agent.avatar;
        }
      });
      await Promise.all(avatarPromises);

      setAvatarUrls(urlMap);
      setAgents(response.data);
      setTotalPages(response.totalPages);
      setTotalResults(response.total);
    } catch (err) {
      console.error('Failed to fetch agents:', err);
      setError('Failed to load agents. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [currentPage, searchQuery, activeTypeId, locationFromUrl, filters]);

  // Fetch agents when filters change
  useEffect(() => {
    fetchAgents();
  }, [fetchAgents]);

  const toggleFilter = (fieldSlug: string, optionValue: string) => {
    setFilters(prev => {
      const currentValues = prev[fieldSlug] || [];
      const newValues = currentValues.includes(optionValue)
        ? currentValues.filter(v => v !== optionValue)
        : [...currentValues, optionValue];
      return { ...prev, [fieldSlug]: newValues };
    });
  };

  const clearAllFilters = () => {
    setFilters({});
  };

  const applyFilters = () => {
    setIsFilterModalOpen(false);
    setCurrentPage(1); // Reset to first page when applying filters
    // Filters are applied via the fetchAgents effect
  };

  const handleSearch = () => {
    setCurrentPage(1);
    fetchAgents();
  };

  const handleTypeChange = (typeId: string | null) => {
    setActiveTypeId(typeId);
    setCurrentPage(1);
    // Sync listing type sidebar with agent type tab selection
    if (typeId) {
      const matchedType = agentTypes.find(t => t.id === typeId);
      if (matchedType?.name === 'Lender') {
        setListingType('lenders');
      } else {
        setListingType('agents');
      }
    }
  };

  const handleListingTypeChange = (type: 'agents' | 'lenders') => {
    setListingType(type);
    // Map listing type to the corresponding agent type and filter
    const typeName = type === 'agents' ? 'Professional' : 'Lender';
    const matchedType = agentTypes.find(t => t.name === typeName);
    setActiveTypeId(matchedType?.id || null);
    setCurrentPage(1);
  };

  // Get filter field by slug for sidebar
  const getFilterFieldBySlug = (slug: string): FilterField | undefined => {
    return filterFields.find(f => f.slug === slug);
  };

  // Define which fields to show in sidebar (main filter categories)
  const sidebarFilterSlugs = ['client_specialization', 'loan_type', 'property_type', 'price_point'];

  return (
    <div className="min-h-screen bg-white">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="flex gap-6">
          {/* Left Sidebar - hidden on mobile */}
          <div className="hidden lg:block w-[220px] flex-shrink-0">
            {/* Listing Type */}
            <div className="mb-6">
              <h2 className="font-fractul font-bold text-[14px] text-[#00293d] mb-3">Listing Type</h2>
              <div className="space-y-2">
                <button
                  onClick={() => handleListingTypeChange('agents')}
                  className={`block font-serif text-[14px] ${listingType === 'agents' ? 'text-[#00293d] font-medium' : 'text-[#00293d]/70'
                    }`}
                >
                  Agents
                </button>
                <button
                  onClick={() => handleListingTypeChange('lenders')}
                  className={`block font-serif text-[14px] ${listingType === 'lenders' ? 'text-[#00293d] font-medium' : 'text-[#00293d]/70'
                    }`}
                >
                  Lenders
                </button>
              </div>
            </div>

            {/* Filters */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <h2 className="font-fractul font-bold text-[14px] text-[#00293d]">Filters</h2>
                <button
                  onClick={() => setIsFilterModalOpen(true)}
                  className="text-[#00293d] hover:opacity-70"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path d="M3 6H21M7 12H17M11 18H13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                  </svg>
                </button>
              </div>

              {/* Dynamic Filter Sections */}
              {sidebarFilterSlugs.map(slug => {
                const field = getFilterFieldBySlug(slug);
                if (!field) return null;
                return (
                  <FilterSection
                    key={field.slug}
                    title={field.name}
                    options={field.options}
                    selectedOptions={filters[field.slug] || []}
                    onToggle={(optionValue) => toggleFilter(field.slug, optionValue)}
                    showMore={field.options.length > 6}
                  />
                );
              })}

              {filterFields.length === 0 && (
                <div className="py-4">
                  <p className="font-serif text-[13px] text-[#00293d]/50">Loading filters...</p>
                </div>
              )}
            </div>
          </div>

          {/* Main Content */}
          <div className="flex-1 min-w-0">
            {/* Mobile Filter Button - visible only on mobile */}
            <div className="flex lg:hidden items-center justify-between mb-4">
              <h2 className="font-fractul font-bold text-[16px] text-[#00293d]">Agent Profiles</h2>
              <button
                onClick={() => setIsFilterModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 border border-[#00293d]/20 rounded-[10px] font-serif text-[13px] text-[#00293d]"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <path d="M3 6H21M7 12H17M11 18H13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                </svg>
                Filters
              </button>
            </div>

            {/* Search Bar */}
            <div className="mb-4">
              <div className="relative">
                <input
                  type="text"
                  placeholder="Search Agents"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                  className="w-full h-[44px] px-4 pr-12 rounded-[10px] border border-[#00293d]/20 bg-white font-serif text-[14px] text-[#00293d] placeholder:text-[#00293d]/50 focus:outline-none focus:border-[#e58625]"
                />
                <button
                  onClick={handleSearch}
                  className="absolute right-2 top-1/2 -translate-y-1/2 w-[36px] h-[36px] bg-[#e58625] rounded-[8px] flex items-center justify-center"
                >
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path d="M21 21L16.65 16.65M19 11C19 15.4183 15.4183 19 11 19C6.58172 19 3 15.4183 3 11C3 6.58172 6.58172 3 11 3C15.4183 3 19 6.58172 19 11Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
              </div>
            </div>

            {/* Agent Type Tabs */}
            <div className="flex gap-2 mb-6 overflow-x-auto pb-2 scrollbar-hide flex-nowrap sm:flex-wrap">
              <button
                onClick={() => handleTypeChange(null)}
                className={`px-4 py-2 rounded-full font-serif text-[13px] border transition-colors whitespace-nowrap flex-shrink-0 ${activeTypeId === null
                    ? 'bg-[#00293d] text-white border-[#00293d]'
                    : 'bg-white text-[#00293d] border-[#00293d]/20 hover:border-[#00293d]/40'
                  }`}
              >
                All Types
              </button>
              {agentTypes.map((type) => (
                <button
                  key={type.id}
                  onClick={() => handleTypeChange(type.id)}
                  className={`px-4 py-2 rounded-full font-serif text-[13px] border transition-colors whitespace-nowrap flex-shrink-0 ${activeTypeId === type.id
                      ? 'bg-[#00293d] text-white border-[#00293d]'
                      : 'bg-white text-[#00293d] border-[#00293d]/20 hover:border-[#00293d]/40'
                    }`}
                >
                  {type.name}
                </button>
              ))}
            </div>

            {/* Loading State */}
            {loading && (
              <div className="flex items-center justify-center py-12">
                <div className="flex flex-col items-center gap-4">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#E58625]"></div>
                  <p className="text-[14px] font-serif text-[#00293D]/70">Loading agents...</p>
                </div>
              </div>
            )}

            {/* Error State */}
            {error && !loading && (
              <div className="bg-red-50 border border-red-200 rounded-[15px] p-6 text-center">
                <p className="text-red-600 font-serif text-[14px]">{error}</p>
                <button
                  onClick={fetchAgents}
                  className="mt-4 px-6 py-2 bg-[#E58625] rounded-full text-[14px] font-semibold font-serif text-white hover:bg-[#E58625]/90 transition-colors"
                >
                  Try Again
                </button>
              </div>
            )}

            {/* Empty State */}
            {!loading && !error && agents.length === 0 && (
              <div className="bg-gray-50 rounded-[15px] p-12 text-center">
                <div className="w-16 h-16 bg-[#E58625]/10 rounded-full flex items-center justify-center mx-auto mb-4">
                  <svg className="w-8 h-8 text-[#E58625]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
                <h3 className="font-fractul font-bold text-[18px] text-[#00293d] mb-2">No agents found</h3>
                <p className="font-serif text-[14px] text-[#00293d]/70">
                  Try adjusting your search criteria or filters
                </p>
              </div>
            )}

            {/* Profile Cards */}
            {!loading && !error && agents.length > 0 && (
              <div className="space-y-4">
                {agents.map((profile) => (
                  <ProfileCard key={profile.id} profile={profile} resolvedAvatarUrl={avatarUrls[profile.id]} />
                ))}
              </div>
            )}

            {/* Pagination */}
            {!loading && !error && totalPages > 1 && (
              <div className="flex justify-center items-center gap-2 mt-8 flex-wrap">
                <button
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="px-4 py-2 rounded-[10px] border border-[#00293d]/20 font-serif text-[13px] text-[#00293d] disabled:opacity-50 disabled:cursor-not-allowed hover:border-[#00293d]/40 transition-colors"
                >
                  Previous
                </button>
                <span className="px-4 py-2 font-serif text-[13px] text-[#00293d]">
                  Page {currentPage} of {totalPages}
                </span>
                <button
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="px-4 py-2 rounded-[10px] border border-[#00293d]/20 font-serif text-[13px] text-[#00293d] disabled:opacity-50 disabled:cursor-not-allowed hover:border-[#00293d]/40 transition-colors"
                >
                  Next
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Filter Modal */}
      <FilterModal
        isOpen={isFilterModalOpen}
        onClose={() => setIsFilterModalOpen(false)}
        filters={filters}
        filterFields={filterFields}
        onToggleFilter={toggleFilter}
        onClearAll={clearAllFilters}
        onApply={applyFilters}
      />
    </div>
  );
}

export default function ProfilesPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#E58625]"></div>
          <p className="text-[14px] font-serif text-[#00293D]/70">Loading...</p>
        </div>
      </div>
    }>
      <ProfilesPageContent />
    </Suspense>
  );
}
