"use client";

import { useState, useEffect, useCallback } from "react";
import { 
  Eye, 
  Trash2, 
  Check, 
  X, 
  Users, 
  Mail, 
  Phone, 
  MapPin, 
  Calendar, 
  User, 
  Building, 
  Shield, 
  Globe, 
  MessageCircle, 
  Star,
  TrendingUp,
  Filter,
  Search,
  ExternalLink,
  ClipboardCheck,
  Target,
  GraduationCap,
  Briefcase,
  Home,
  Plane,
  Award,
  BadgeCheck,
  Clock,
  DollarSign,
  Monitor,
  BriefcaseBusiness,
  FileText,
  Languages as LangIcon,
  CheckCircle,
  Crown,
  TrendingUp as TrendingUpIcon,
  Award as AwardIcon
} from "lucide-react";
import Pagination from '../../components/Pagination';
import Swal from 'sweetalert2';
import Link from "next/link";

// Interface based on actual API response
interface ConsultantUser {
  id: number;
  first_name: string;
  last_name: string;
  name: string;
  email: string;
  phone: string;
  user_type: string;
  is_active: boolean;
  country: string;
  state: string;
  city: string;
  created_at: string | null;
  updated_at: string | null;
  featured: string;
  premium_featured: string | null; // New field
  consultant?: {
    id: number;
    user_id: number;
    name: string;
    company_name: string;
    state: string;
    city: string;
    address: string;
    email: string;
    phone: string;
    average_rating: number;
    rating_count: number;
    consultation_fee: number;
    response_time: string;
    digital_only: boolean;
    target_countries: string[];
    services: string[];
    languages: string[];
    specialization: string[];
    availability: string;
    active: string;
    comment: string;
    designation: string;
    employeeno: string;
    nationality: string;
    created_at: string | null;
    updated_at: string | null;
  };
}

interface ApiResponse {
  success: boolean;
  users: ConsultantUser[];
  meta: {
    page: number;
    limit: number;
    totalItems: number;
    totalPages: number;
    startIndex: number;
    endIndex: number;
  };
}

const ConsultantList = () => {
  const [consultants, setConsultants] = useState<ConsultantUser[]>([]);
  const [loading, setLoading] = useState(true);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [cityFilter, setCityFilter] = useState("");
  const [countryFilter, setCountryFilter] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [featuredFilter, setFeaturedFilter] = useState("");
  const [premiumFeaturedFilter, setPremiumFeaturedFilter] = useState(""); // New filter
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStatusFilter, setAppliedStatusFilter] = useState("");
  const [appliedCityFilter, setAppliedCityFilter] = useState("");
  const [appliedCountryFilter, setAppliedCountryFilter] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");
  const [appliedPremiumFeaturedFilter, setAppliedPremiumFeaturedFilter] = useState(""); // New applied filter

  const [selectedConsultant, setSelectedConsultant] = useState<ConsultantUser | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [showPremiumModal, setShowPremiumModal] = useState(false);
  const [currentPremiumId, setCurrentPremiumId] = useState<number | null>(null);
  const [premiumValue, setPremiumValue] = useState<string>("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Reset to first page when applied filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [appliedSearchTerm, appliedStatusFilter, appliedCityFilter, appliedCountryFilter, appliedStartDate, appliedEndDate, appliedPremiumFeaturedFilter]);

  const fetchConsultants = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
      });

      if (appliedSearchTerm) {
        params.append("search", appliedSearchTerm);
      }
      if (appliedStatusFilter) {
        params.append("is_active", appliedStatusFilter);
      }
      if (appliedCityFilter) {
        params.append("city", appliedCityFilter);
      }
      if (appliedCountryFilter) {
        params.append("country", appliedCountryFilter);
      }
      if (appliedStartDate) {
        params.append("start_date", appliedStartDate);
      }
      if (appliedEndDate) {
        params.append("end_date", appliedEndDate);
      }
      if (appliedPremiumFeaturedFilter) {
        params.append("premium_featured", appliedPremiumFeaturedFilter);
      }

      const response = await fetch(`/api/internal/consultants?${params.toString()}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch consultants');
      }
      
      const data: ApiResponse = await response.json();
      
      if (data.success) {
        setConsultants(data.users || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setConsultants([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (error) {
      console.error("Fetch error:", error);
      Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to fetch consultants",
      });
      setConsultants([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [currentPage, appliedSearchTerm, appliedStatusFilter, appliedCityFilter, appliedCountryFilter, appliedStartDate, appliedEndDate, appliedPremiumFeaturedFilter, itemsPerPage]);

  // Toggle featured status
  const toggleFeaturedStatus = async (id: number) => {
    try {
      const currentConsultant = consultants.find(s => s.id === id);
      if (!currentConsultant) return;
      
      const newStatus = currentConsultant.featured === '1' ? '0' : '1';
      const featuredText = newStatus === '1' ? 'featured' : 'unfeatured';
      
      const result = await Swal.fire({
        title: `Mark as Featured?`,
        text: `Do you want to ${featuredText} this consultant?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0B6D76',
        cancelButtonColor: '#d33',
        confirmButtonText: `Yes, mark as ${featuredText}!`,
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        // Check if consultant has a profile (consultant record)
        if (!currentConsultant.consultant) {
          Swal.fire({
            icon: 'warning',
            title: 'Profile Required',
            text: 'Consultant must have a profile setup before marking as featured.',
            confirmButtonColor: '#0B6D76',
          });
          return;
        }
        
        // Send both user_id and consultant_id to API
        const response = await fetch(`/api/internal/consultants`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ 
            id: currentConsultant.id, // user_id
            consultant_id: currentConsultant.consultant.id, // consultant_id
            featured: newStatus 
          }),
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || "Failed to update featured status");
        }
        
        await fetchConsultants();
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: `Consultant ${featuredText} successfully.`,
          confirmButtonColor: '#0B6D76',
        });
      }
    } catch (error) {
      console.error("Featured update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update featured status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  // Set premium featured status
  const handleSetPremiumFeatured = async () => {
    if (!currentPremiumId || !premiumValue) return;

    try {
      const currentConsultant = consultants.find(s => s.id === currentPremiumId);
      if (!currentConsultant) return;

      const result = await Swal.fire({
        title: `Set Premium Featured Position?`,
        text: `Set position ${premiumValue} for this consultant? (Set 0 to remove from premium)`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0B6D76',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, set position!',
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        // Check if consultant has a profile
        if (!currentConsultant.consultant) {
          Swal.fire({
            icon: 'warning',
            title: 'Profile Required',
            text: 'Consultant must have a profile setup before setting premium featured.',
            confirmButtonColor: '#0B6D76',
          });
          return;
        }

        const response = await fetch(`/api/internal/consultants`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ 
            id: currentConsultant.id,
            consultant_id: currentConsultant.consultant.id,
            premium_featured: premiumValue 
          }),
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || "Failed to update premium featured status");
        }
        
        await fetchConsultants();
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: `Premium featured position ${premiumValue === '0' ? 'removed' : 'set to ' + premiumValue} successfully.`,
          confirmButtonColor: '#0B6D76',
        });
        
        setShowPremiumModal(false);
        setCurrentPremiumId(null);
        setPremiumValue("");
      }
    } catch (error) {
      console.error("Premium featured update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update premium featured status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  // Open premium modal
  const openPremiumModal = (id: number, currentValue: string | null) => {
    setCurrentPremiumId(id);
    setPremiumValue(currentValue || "");
    setShowPremiumModal(true);
  };

  useEffect(() => {
    fetchConsultants();
  }, [fetchConsultants]);

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStatusFilter(statusFilter);
    setAppliedCityFilter(cityFilter);
    setAppliedCountryFilter(countryFilter);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setAppliedPremiumFeaturedFilter(premiumFeaturedFilter);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("");
    setCityFilter("");
    setCountryFilter("");
    setStartDate("");
    setEndDate("");
    setPremiumFeaturedFilter("");
    setAppliedSearchTerm("");
    setAppliedStatusFilter("");
    setAppliedCityFilter("");
    setAppliedCountryFilter("");
    setAppliedStartDate("");
    setAppliedEndDate("");
    setAppliedPremiumFeaturedFilter("");
  };

  const hasActiveFilters = appliedSearchTerm || appliedStatusFilter || appliedCityFilter || appliedCountryFilter || appliedStartDate || appliedEndDate || appliedPremiumFeaturedFilter;

  const formatDate = (dateString: string | null) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (e) {
      return 'N/A';
    }
  };

  const formatCurrency = (amount: number) => {
    if (!amount) return 'Free';
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 2
    }).format(amount);
  };

  const toggleConsultantStatus = async (id: number) => {
    try {
      const currentConsultant = consultants.find(s => s.id === id);
      if (!currentConsultant) return;
      
      const newStatus = !currentConsultant.is_active;
      
      const result = await Swal.fire({
        title: `Are you sure?`,
        text: `Do you want to ${newStatus ? 'activate' : 'deactivate'} this consultant?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0B6D76',
        cancelButtonColor: '#d33',
        confirmButtonText: `Yes, ${newStatus ? 'activate' : 'deactivate'} it!`,
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        const response = await fetch(`/api/internal/consultants/${id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ is_active: newStatus }),
        });
        
        if (!response.ok) throw new Error("Failed to update status");
        
        await fetchConsultants();
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: `Consultant ${newStatus ? 'activated' : 'deactivated'} successfully.`,
          confirmButtonColor: '#0B6D76',
        });
      }
    } catch (error) {
      console.error("Status update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update consultant status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  // Get unique cities and countries for filter dropdowns from consultant data
  const uniqueCities = Array.from(new Set(
    consultants
      .map(c => c.consultant?.city || c.city)
      .filter(Boolean)
  ));
  
  const uniqueCountries = Array.from(new Set(
    consultants
      .map(c => c.consultant?.nationality || c.country)
      .filter(Boolean)
  ));

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + consultants.length;

  // Calculate profile completion percentage based on filled fields
  const calculateProfileCompletion = (consultant: ConsultantUser) => {
    if (!consultant.consultant) return 0;
    
    const consultantData = consultant.consultant;
    const fields = [
      consultantData.company_name,
      consultantData.designation,
      consultantData.address,
      consultantData.employeeno,
      consultantData.nationality,
      consultantData.comment,
      consultantData.specialization?.length > 0,
      consultantData.target_countries?.length > 0,
      consultantData.services?.length > 0,
      consultantData.languages?.length > 0,
      consultantData.consultation_fee > 0
    ];
    
    const filledFields = fields.filter(Boolean).length;
    return Math.round((filledFields / fields.length) * 100);
  };

  // Get premium featured positions
  const getPremiumPositions = () => {
    const positions = new Set<string>();
    consultants.forEach(consultant => {
      if (consultant.premium_featured && consultant.premium_featured !== '0') {
        positions.add(consultant.premium_featured);
      }
    });
    return Array.from(positions).sort((a, b) => parseInt(a) - parseInt(b));
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-cyan-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-[#0B6D76] mx-auto mb-4"></div>
          <p className="text-gray-600">Loading consultants...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6 bg-gradient-to-br from-blue-50 via-white to-cyan-50 min-h-screen">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
        <div className="text-center md:text-left">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-gradient-to-r from-[#0B6D76] to-cyan-600 rounded-lg">
              <Users className="w-6 h-6 text-white" />
            </div>
            <h1 className="text-3xl font-bold text-gray-900">Consultant Management</h1>
          </div>
          <p className="text-gray-600 mt-2">Manage and monitor all consultant records</p>
          
          {/* Stats */}
          <div className="flex flex-wrap gap-4 mt-4">
            <div className="px-4 py-2 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border border-green-200">
              <div className="text-lg font-bold text-green-700">{totalItems}</div>
              <div className="text-sm text-green-600">Total Consultants</div>
            </div>
            <div className="px-4 py-2 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg border border-blue-200">
              <div className="text-lg font-bold text-blue-700">
                {consultants.filter(c => c.is_active).length}
              </div>
              <div className="text-sm text-blue-600">Active</div>
            </div>
            <div className="px-4 py-2 bg-gradient-to-r from-amber-50 to-yellow-50 rounded-lg border border-amber-200">
              <div className="text-lg font-bold text-amber-700">
                {consultants.filter(c => !c.is_active).length}
              </div>
              <div className="text-sm text-amber-600">Inactive</div>
            </div>
            <div className="px-4 py-2 bg-gradient-to-r from-purple-50 to-violet-50 rounded-lg border border-purple-200">
              <div className="text-lg font-bold text-purple-700">
                {consultants.filter(c => c.premium_featured && c.premium_featured !== '0').length}
              </div>
              <div className="text-sm text-purple-600">Premium Featured</div>
            </div>
          </div>
        </div>
        
        <div className="flex flex-col sm:flex-row gap-3">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-5 py-2.5 rounded-xl transition-all duration-300 flex items-center justify-center gap-2 font-medium ${
              isFilterOpen 
                ? 'bg-gradient-to-r from-[#0B6D76] to-cyan-600 text-white shadow-lg' 
                : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300 hover:border-gray-400 shadow-sm hover:shadow'
            }`}
          >
            <Filter className="w-4 h-4" />
            Filters
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-0.5 bg-white text-[#0B6D76] text-xs font-bold rounded-full">
                {[appliedSearchTerm, appliedStatusFilter, appliedCityFilter, appliedCountryFilter, appliedStartDate, appliedEndDate, appliedPremiumFeaturedFilter].filter(Boolean).length}
              </span>
            )}
          </button>
        </div>
      </div>

      {/* Filter Section */}
      {isFilterOpen && (
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-6 border border-gray-200">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-7 gap-4">
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Search className="w-3 h-3" />
                Search
              </label>
              <input
                type="text"
                placeholder="Name, email, phone..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
              />
            </div>
            
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Shield className="w-3 h-3" />
                Status
              </label>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Status</option>
                <option value="true">Active</option>
                <option value="false">Inactive</option>
              </select>
            </div>
            
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <MapPin className="w-3 h-3" />
                City
              </label>
              <select
                value={cityFilter}
                onChange={(e) => setCityFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Cities</option>
                {uniqueCities.map(city => (
                  <option key={city} value={city}>{city}</option>
                ))}
              </select>
            </div>
            
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Globe className="w-3 h-3" />
                Country
              </label>
              <select
                value={countryFilter}
                onChange={(e) => setCountryFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Countries</option>
                {uniqueCountries.map(country => (
                  <option key={country} value={country}>{country}</option>
                ))}
              </select>
            </div>
            
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Calendar className="w-3 h-3" />
                Start Date
              </label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Calendar className="w-3 h-3" />
                End Date
              </label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>

            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Star className="w-3 h-3" />
                Featured Status
              </label>
              <select
                value={featuredFilter}
                onChange={(e) => setFeaturedFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All</option>
                <option value="1">Featured</option>
                <option value="0">Not Featured</option>
              </select>
            </div>

            {/* Premium Featured Filter */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700 flex items-center gap-1">
                <Crown className="w-3 h-3" />
                Premium Featured
              </label>
              <select
                value={premiumFeaturedFilter}
                onChange={(e) => setPremiumFeaturedFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All</option>
                <option value="0">Not Premium</option>
                <option value="1">Position 1</option>
                <option value="2">Position 2</option>
                <option value="3">Position 3</option>
                <option value="4">Position 4</option>
                <option value="5">Position 5</option>
                <option value="custom">Custom Position</option>
              </select>
            </div>
          </div>
          
          <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6 pt-6 border-t border-gray-200">
            <div className="flex flex-wrap gap-2">
              <button
                onClick={handleSearch}
                className="px-5 py-2.5 bg-gradient-to-r from-[#0B6D76] to-cyan-600 text-white rounded-xl hover:shadow-lg transition-all duration-300 flex items-center gap-2 font-medium"
              >
                <Search className="w-4 h-4" />
                Apply Filters
              </button>
              
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="px-5 py-2.5 bg-gradient-to-r from-red-500 to-orange-500 text-white rounded-xl hover:shadow-lg transition-all duration-300 flex items-center gap-2 font-medium"
                >
                  <X className="w-4 h-4" />
                  Clear Filters
                </button>
              )}
            </div>
            
            {/* Active Filters Display */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2 items-center">
                <span className="text-sm font-medium text-gray-700">Active filters:</span>
                <div className="flex flex-wrap gap-2">
                  {appliedSearchTerm && (
                    <span className="px-3 py-1.5 bg-blue-100 text-blue-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Search className="w-3 h-3" />
                      {appliedSearchTerm}
                    </span>
                  )}
                  {appliedStatusFilter && (
                    <span className="px-3 py-1.5 bg-green-100 text-green-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Shield className="w-3 h-3" />
                      {appliedStatusFilter === 'true' ? 'Active' : 'Inactive'}
                    </span>
                  )}
                  {appliedCityFilter && (
                    <span className="px-3 py-1.5 bg-purple-100 text-purple-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      {appliedCityFilter}
                    </span>
                  )}
                  {appliedCountryFilter && (
                    <span className="px-3 py-1.5 bg-orange-100 text-orange-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Globe className="w-3 h-3" />
                      {appliedCountryFilter}
                    </span>
                  )}
                  {appliedStartDate && (
                    <span className="px-3 py-1.5 bg-cyan-100 text-cyan-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {new Date(appliedStartDate).toLocaleDateString()}
                    </span>
                  )}
                  {appliedEndDate && (
                    <span className="px-3 py-1.5 bg-amber-100 text-amber-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {new Date(appliedEndDate).toLocaleDateString()}
                    </span>
                  )}
                  {appliedPremiumFeaturedFilter && (
                    <span className="px-3 py-1.5 bg-gradient-to-r from-purple-100 to-pink-100 text-purple-800 rounded-full text-sm font-medium flex items-center gap-1">
                      <Crown className="w-3 h-3" />
                      {appliedPremiumFeaturedFilter === '0' ? 'Not Premium' : `Position ${appliedPremiumFeaturedFilter}`}
                    </span>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Premium Featured Positions Summary */}
          {getPremiumPositions().length > 0 && (
            <div className="mt-6 pt-6 border-t border-gray-200">
              <h4 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <Crown className="w-4 h-4 text-amber-600" />
                Current Premium Featured Positions
              </h4>
              <div className="flex flex-wrap gap-2">
                {getPremiumPositions().map(position => {
                  const consultantsWithPosition = consultants.filter(
                    c => c.premium_featured === position
                  );
                  return (
                    <div key={position} className="px-3 py-2 bg-gradient-to-r from-amber-50 to-yellow-50 rounded-lg border border-amber-200">
                      <div className="flex items-center gap-2">
                        <Crown className="w-4 h-4 text-amber-600" />
                        <span className="font-bold text-amber-800">Position {position}</span>
                        <span className="text-sm text-amber-700">
                          ({consultantsWithPosition.length} consultant{consultantsWithPosition.length !== 1 ? 's' : ''})
                        </span>
                      </div>
                      <div className="text-xs text-amber-600 mt-1">
                        {consultantsWithPosition.map(c => c.name).join(', ')}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-200">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[1200px]">
            <thead className="sticky top-0 bg-gradient-to-r from-[#0B6D76] to-cyan-600 z-10">
              <tr>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Consultant</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Contact</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Location</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Profile Details</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Status</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Created</th>
                <th className="px-6 py-4 text-center text-sm font-semibold text-white">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {consultants.map((consultant) => {
                const profile = consultant.consultant; // 🔑 shortcut
                const isPremiumFeatured = consultant.premium_featured && consultant.premium_featured !== '0';

                return (
                  <tr key={consultant.id} className={`hover:bg-gray-50 transition-colors ${isPremiumFeatured ? 'bg-gradient-to-r from-amber-50/50 to-yellow-50/50' : ''}`}>
                    
                    {/* Consultant Info */}
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 ${
                          isPremiumFeatured 
                            ? 'bg-gradient-to-br from-amber-100 to-yellow-100 border border-amber-200' 
                            : 'bg-gradient-to-br from-blue-100 to-cyan-100'
                        }`}>
                          {isPremiumFeatured ? (
                            <Crown className="w-5 h-5 text-amber-600" />
                          ) : (
                            <User className="w-5 h-5 text-[#0B6D76]" />
                          )}
                        </div>
                        <div>
                          <div className="font-semibold text-gray-900 flex items-center gap-2">
                            {consultant.first_name} {consultant.last_name}
                            {isPremiumFeatured && (
                              <span className="px-2 py-0.5 bg-gradient-to-r from-amber-500 to-yellow-500 text-white text-xs font-bold rounded-full flex items-center gap-1">
                                <Crown className="w-3 h-3" />
                                #{consultant.premium_featured}
                              </span>
                            )}
                          </div>

                          {profile?.company_name && (
                            <div className="text-sm text-gray-600 flex items-center gap-1">
                              <Building className="w-3 h-3" />
                              {profile.company_name}
                            </div>
                          )}
                        </div>
                      </div>
                    </td>

                    {/* Contact Info */}
                    <td className="px-6 py-4">
                      <div className="space-y-2">
                        <div className="flex items-center gap-2 text-sm">
                          <Mail className="w-3 h-3 text-gray-500 flex-shrink-0" />
                          <span className="text-gray-700 truncate max-w-[150px]">
                            {consultant.email}
                          </span>
                        </div>

                        {consultant.phone && (
                          <div className="flex items-center gap-2 text-sm">
                            <Phone className="w-3 h-3 text-gray-500 flex-shrink-0" />
                            <span className="text-gray-700">{consultant.phone}</span>
                          </div>
                        )}
                      </div>
                    </td>

                    {/* Location */}
                    <td className="px-6 py-4">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-sm">
                          <MapPin className="w-3 h-3 text-blue-600 flex-shrink-0" />
                          <span className="text-gray-700">
                            {consultant.city || 'N/A'}
                            {consultant.state && `, ${consultant.state}`}
                          </span>
                        </div>

                        {consultant.country && (
                          <div className="text-xs text-gray-500 flex items-center gap-1 ml-5">
                            <Globe className="w-3 h-3" />
                            {consultant.country}
                          </div>
                        )}
                      </div>
                    </td>

                    {/* Profile Stats */}
                    <td className="px-6 py-4">
                      {profile ? (
                        <div className="space-y-2">
                          
                          {/* Rating */}
                          <div className="flex items-center gap-2">
                            <Star className="w-3 h-3 text-amber-500 fill-current" />
                            <span className="text-sm font-medium text-gray-900">
                              {profile.average_rating.toFixed(1)}
                            </span>
                            {profile.rating_count > 0 && (
                              <span className="text-xs text-gray-500">
                                ({profile.rating_count})
                              </span>
                            )}
                          </div>

                          {/* Consultation Fee */}
                          <div className="flex items-center gap-2 text-sm">
                            <DollarSign className="w-3 h-3 text-green-600" />
                            <span className="text-gray-700">
                              {formatCurrency(profile.consultation_fee)}
                            </span>
                          </div>

                          {/* Response Time */}
                          <div className="flex items-center gap-2 text-sm">
                            <Clock className="w-3 h-3 text-blue-600" />
                            <span className={`px-2 py-0.5 rounded-full text-xs capitalize ${
                              profile.response_time === 'urgent'
                                ? 'bg-red-100 text-red-800'
                                : profile.response_time === 'fast'
                                ? 'bg-green-100 text-green-800'
                                : 'bg-blue-100 text-blue-800'
                            }`}>
                              {profile.response_time}
                            </span>
                          </div>

                          {/* Digital Only */}
                          {profile.digital_only && (
                            <div className="flex items-center gap-2 text-sm">
                              <Monitor className="w-3 h-3 text-purple-600" />
                              <span className="text-gray-700">Digital Only</span>
                            </div>
                          )}
                        </div>
                      ) : (
                        <div className="text-gray-500 italic text-sm">
                          No consultant profile
                        </div>
                      )}
                    </td>

                    {/* Status */}
                    <td className="px-6 py-4">
                      <div className="space-y-2">
                        <span className={`px-3 py-1.5 rounded-full text-xs font-semibold inline-flex items-center gap-1 ${
                          consultant.is_active
                            ? "bg-green-100 text-green-800"
                            : "bg-red-100 text-red-800"
                        }`}>
                          {consultant.is_active ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
                          {consultant.is_active ? 'Active' : 'Inactive'}
                        </span>
                        
                        {consultant.featured === '1' && (
                          <span className="px-3 py-1.5 bg-blue-100 text-blue-800 rounded-full text-xs font-semibold inline-flex items-center gap-1">
                            <Star className="w-3 h-3" />
                            Featured
                          </span>
                        )}
                      </div>
                    </td>

                    {/* Created Date */}
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {formatDate(consultant.created_at)}
                      </div>
                    </td>

                    {/* Actions */}
                    <td className="px-6 py-4">
                      <div className="flex justify-center gap-1">
                        {/* Premium Featured Button */}
                        <button
                          onClick={() => openPremiumModal(consultant.id, consultant.premium_featured)}
                          className={`p-2 rounded-lg transition-colors ${
                            isPremiumFeatured
                              ? 'text-amber-600 hover:bg-amber-50 bg-amber-50 border border-amber-200'
                              : 'text-gray-400 hover:bg-gray-50 hover:text-gray-600'
                          }`}
                          title={isPremiumFeatured ? `Premium Position ${consultant.premium_featured}` : 'Set Premium Featured'}
                        >
                          <Crown className={`w-4 h-4 ${isPremiumFeatured ? 'fill-current' : ''}`} />
                        </button>

                        {/* Regular Featured Button */}
                        <button
                          onClick={() => toggleFeaturedStatus(consultant.id)}
                          className={`p-2 rounded-lg transition-colors ${
                            consultant.featured === '1'
                              ? 'text-blue-600 hover:bg-blue-50 bg-blue-50'
                              : 'text-gray-400 hover:bg-gray-50 hover:text-gray-600'
                          }`}
                          title={consultant.featured === '1' ? 'Featured' : 'Mark as Featured'}
                        >
                          <Star className={`w-4 h-4 ${consultant.featured === '1' ? 'fill-current' : ''}`} />
                        </button>

                        <button
                          onClick={() => {
                            setSelectedConsultant(consultant);
                            setShowModal(true);
                          }}
                          className="p-2 text-[#0B6D76] hover:bg-blue-50 rounded-lg"
                        >
                          <Eye className="w-4 h-4" />
                        </button>

                        <Link
                          href={`/admin/consultant-students/${consultant.id}`}
                          className="p-2 text-green-600 hover:bg-green-50 rounded-lg"
                        >
                          <Users className="w-4 h-4" />
                        </Link>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {consultants.length === 0 && (
          <div className="text-center py-16">
            <div className="w-24 h-24 mx-auto mb-4 text-gray-300">
              <Users className="w-full h-full" />
            </div>
            <div className="text-gray-500 text-lg font-medium mb-2">
              {hasActiveFilters ? 'No consultants found' : 'No consultants available'}
            </div>
            <p className="text-gray-400 mb-6 max-w-md mx-auto">
              {hasActiveFilters 
                ? 'Try adjusting your search criteria or clear filters to see more results'
                : 'No consultant records have been created yet. Add your first consultant to get started.'
              }
            </p>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="px-6 py-2.5 bg-gradient-to-r from-[#0B6D76] to-cyan-600 text-white rounded-xl hover:shadow-lg transition-all duration-300 font-medium"
              >
                Clear all filters
              </button>
            )}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="border-t border-gray-200 p-4">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              totalItems={totalItems}
              startIndex={startIndex + 1}
              endIndex={endIndex}
            />
          </div>
        )}
      </div>

      {/* Premium Featured Modal */}
      {showPremiumModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl max-w-md w-full">
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-gradient-to-r from-amber-100 to-yellow-100 rounded-lg flex items-center justify-center">
                    <Crown className="w-5 h-5 text-amber-600" />
                  </div>
                  <div>
                    <h3 className="text-xl font-bold text-gray-900">Set Premium Featured Position</h3>
                    <p className="text-gray-600 text-sm">Assign a unique position number to display on top</p>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setShowPremiumModal(false);
                    setCurrentPremiumId(null);
                    setPremiumValue("");
                  }}
                  className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Position Number
                  </label>
                  <select
                    value={premiumValue}
                    onChange={(e) => setPremiumValue(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-amber-500 focus:border-transparent"
                  >
                    <option value="">Select position (0 to remove)</option>
                    <option value="0">Remove from premium</option>
                    <option value="1">Position 1 (Highest Priority)</option>
                    <option value="2">Position 2</option>
                    <option value="3">Position 3</option>
                    <option value="4">Position 4</option>
                    <option value="5">Position 5</option>
                    <option value="custom">Custom Position</option>
                  </select>
                </div>

                {premiumValue === 'custom' && (
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Custom Position Number
                    </label>
                    <input
                      type="number"
                      min="1"
                      max="999"
                      value={premiumValue === 'custom' ? '' : premiumValue}
                      onChange={(e) => setPremiumValue(e.target.value)}
                      placeholder="Enter custom position number"
                      className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-amber-500 focus:border-transparent"
                    />
                    <p className="text-sm text-gray-500 mt-1">
                      Lower numbers appear first. Use unique numbers for best results.
                    </p>
                  </div>
                )}

                {/* Current Positions Summary */}
                {getPremiumPositions().length > 0 && (
                  <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                    <h4 className="text-sm font-semibold text-amber-800 mb-2 flex items-center gap-2">
                      <Crown className="w-4 h-4" />
                      Current Positions in Use
                    </h4>
                    <div className="flex flex-wrap gap-2">
                      {getPremiumPositions().map(pos => (
                        <span key={pos} className="px-2 py-1 bg-white text-amber-700 text-xs font-medium rounded border border-amber-300">
                          #{pos}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div className="flex gap-3 mt-6">
                <button
                  onClick={() => {
                    setShowPremiumModal(false);
                    setCurrentPremiumId(null);
                    setPremiumValue("");
                  }}
                  className="flex-1 px-4 py-3 border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSetPremiumFeatured}
                  disabled={!premiumValue}
                  className={`flex-1 px-4 py-3 font-medium rounded-xl transition-all ${
                    premiumValue === '0'
                      ? 'bg-gradient-to-r from-red-500 to-orange-500 text-white hover:shadow-lg'
                      : 'bg-gradient-to-r from-amber-500 to-yellow-500 text-white hover:shadow-lg'
                  } ${!premiumValue ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  {premiumValue === '0' ? 'Remove Premium' : `Set Position ${premiumValue}`}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Consultant Details Modal */}
      {showModal && selectedConsultant && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl max-w-6xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            {/* Modal Header */}
            <div className="bg-gradient-to-r from-[#0B6D76] to-cyan-600 p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center">
                    <BriefcaseBusiness className="w-8 h-8 text-white" />
                  </div>
                  <div>
                    <h3 className="text-2xl font-bold text-white">
                      {selectedConsultant.name}
                    </h3>
                    <p className="text-white/90">
                      {selectedConsultant.consultant?.company_name || 'No company set'}
                      {selectedConsultant.consultant?.designation && ` • ${selectedConsultant.consultant.designation}`}
                    </p>
                    <div className="flex gap-3 mt-1">
                      <span className="text-xs bg-white/20 px-2 py-1 rounded">
                        User ID: {selectedConsultant.id}
                      </span>
                      {selectedConsultant.consultant && (
                        <span className="text-xs bg-white/20 px-2 py-1 rounded">
                          Consultant ID: {selectedConsultant.consultant.id}
                        </span>
                      )}
                      {selectedConsultant.premium_featured && selectedConsultant.premium_featured !== '0' && (
                        <span className="text-xs bg-gradient-to-r from-amber-500/30 to-yellow-500/30 px-2 py-1 rounded flex items-center gap-1">
                          <Crown className="w-3 h-3" />
                          Premium Position #{selectedConsultant.premium_featured}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
                <button
                  onClick={() => setShowModal(false)}
                  className="p-2 text-white/80 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>
            
            {/* Modal Content (existing content remains the same, just add premium featured info) */}
            <div className="flex-1 overflow-y-auto p-6">
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Column 1: Personal Information */}
                <div className="space-y-6">
                  {/* User Account Info - Add premium featured badge */}
                  <div className="bg-gray-50 rounded-xl p-5">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                        <User className="w-5 h-5 text-[#0B6D76]" />
                        User Account Information
                      </h4>
                      {selectedConsultant.premium_featured && selectedConsultant.premium_featured !== '0' && (
                        <button
                          onClick={() => openPremiumModal(selectedConsultant.id, selectedConsultant.premium_featured)}
                          className="px-3 py-1 bg-gradient-to-r from-amber-500 to-yellow-500 text-white text-sm font-medium rounded-lg hover:shadow flex items-center gap-1"
                        >
                          <Crown className="w-3 h-3" />
                          Position #{selectedConsultant.premium_featured}
                        </button>
                      )}
                    </div>
                    {/* Rest of the content remains the same */}
                    {/* ... */}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ConsultantList;