'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import { getCountryDataByDomain } from '@/lib/countries';

// Debounce utility function
function debounce(func: Function, wait: number) {
  let timeout: NodeJS.Timeout;
  return function executedFunction(...args: any[]) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

interface FreelancersListProps {
  freelancers: any[];
  categories: any[];
  countries: any[];
  currentPage: number;
  totalPages: number;
  totalCount: number;
  currentCategory?: string;
  currentSearch?: string;
  currentLocation?: string;
  currentRating?: string;
  currentSort?: string;
  locale: string;
}

export default function FreelancersList({
  freelancers: initialFreelancers,
  categories,
  countries,
  currentPage: initialCurrentPage,
  totalPages: initialTotalPages,
  totalCount: initialTotalCount,
  currentCategory,
  currentSearch,
  currentLocation,
  currentRating,
  currentSort,
  locale
}: FreelancersListProps) {
  const router = useRouter();
  const datacounter =    getCountryDataByDomain();

  useEffect(() => {
    const paramss = new URLSearchParams(window.location.search);
    const locationGet = paramss.get("location");
    if(!locationGet){
        const params = new URLSearchParams(searchParams.toString());
        if(datacounter?.id){
          params.set('location', datacounter?.id??'');
        } 
        router.replace(`/${locale}/freelancers?${params.toString()}`, { scroll: false });
    }
  },[router])

  const { data: session } = useSession();
  const searchParams = useSearchParams();
  const { showInfo } = useToast();
  const [freelancers, setFreelancers] = useState(initialFreelancers);
  const [currentPage, setCurrentPage] = useState(initialCurrentPage);
  const [totalPages, setTotalPages] = useState(initialTotalPages);
  const [totalCount, setTotalCount] = useState(initialTotalCount);
  const [loading, setLoading] = useState(false);

  const [searchTerm, setSearchTerm] = useState(currentSearch || '');
  const [selectedCategory, setSelectedCategory] = useState(currentCategory || '');
  const [selectedLocation, setSelectedLocation] = useState(currentLocation || '');
  const [selectedRating, setSelectedRating] = useState(currentRating || '');
  const [selectedSort, setSelectedSort] = useState(currentSort || 'newest');

  // Define fetchFreelancersWithFilters before using it in debouncedSearch
  const fetchFreelancersWithFilters = useCallback(async (filterUpdates: any = {}) => {
    try {
      setLoading(true);
      const params = new URLSearchParams(searchParams.toString());
      
      // Apply filter updates
      Object.keys(filterUpdates).forEach(key => {
        if (filterUpdates[key]) {
          params.set(key, filterUpdates[key]);
        } else {
          params.delete(key);
        }
      });
      
      // Reset to page 1 if filters change
      if (Object.keys(filterUpdates).some(key => key !== 'page')) {
        params.set('page', '1');
      }
     
      if(datacounter?.id){
        params.set('location', datacounter?.id??'');
      }    
      
      console.log('Fetching freelancers with params:', params.toString());
      
      const res = await fetch(`/api/freelancers?${params.toString()}`);
      if (res.ok) {
        const data = await res.json();
        console.log('API response:', data);
        setFreelancers(data.freelancers);
        setCurrentPage(data.currentPage);
        setTotalPages(data.totalPages);
        setTotalCount(data.totalCount);
        
        // Update URL without causing page reload
        router.replace(`/${locale}/freelancers?${params.toString()}`, { scroll: false });
      }
    } catch (error) {
      console.error('Error fetching freelancers:', error);
    } finally {
      setLoading(false);
    }
  }, [searchParams, router, locale]);

  // Debounced search function
  const debouncedSearch = useCallback(
    debounce(async (searchValue: string) => {
      if (searchValue !== searchParams.get('search')) {
        await fetchFreelancersWithFilters({ search: searchValue, page: 1 });
      }
    }, 500),
    [fetchFreelancersWithFilters, searchParams]
  );

  // Handle search input change with debouncing
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    debouncedSearch(value);
  };

  // Update filter states when URL parameters change
  useEffect(() => {
    setSearchTerm(searchParams.get('search') || '');
    setSelectedCategory(searchParams.get('category') || '');
    setSelectedLocation(searchParams.get('location') || '');
    setSelectedRating(searchParams.get('rating') || '');
    setSelectedSort(searchParams.get('sort') || 'newest');
  }, [searchParams]);

  // Handle URL filters on mount and changes
  useEffect(() => {
    const currentSearch = searchParams.get('search') || '';
    const currentCategory = searchParams.get('category') || '';
    const currentLocation = searchParams.get('location') || '';
    const currentRating = searchParams.get('rating') || '';
    const currentSort = searchParams.get('sort') || 'newest';
    
    const hasUrlFilters = currentSearch || currentCategory || currentLocation || currentRating || (currentSort !== 'newest');
    
    // Only fetch if we have URL filters (don't override initial server data if no filters)
    if (hasUrlFilters) {
      console.log('Loading with URL filters:', { currentSearch, currentCategory, currentLocation, currentRating, currentSort });
      fetchFreelancersWithFilters({
        search: currentSearch,
        category: currentCategory, 
        location: currentLocation,
        rating: currentRating,
        sort: currentSort,
        page: 1
      });
    }
  }, [searchParams]); // Only depend on searchParams

  // Remove unused updateUrl function

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    await fetchFreelancersWithFilters({ search: searchTerm, page: 1 });
  };

  const handleSearchInput = async (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      await fetchFreelancersWithFilters({ search: searchTerm, page: 1 });
    }
  };


  const handleFilterChange = async (filterType: string, value: string) => {
    console.log('Filter change:', filterType, value);
    
    // Update local state immediately for better UX
    if (filterType === 'category') setSelectedCategory(value);
    if (filterType === 'location') setSelectedLocation(value);
    if (filterType === 'rating') setSelectedRating(value);
    if (filterType === 'sort') setSelectedSort(value);
    
    // Call API immediately
    await fetchFreelancersWithFilters({ [filterType]: value, page: 1 });
  };

  const handleLoadMore = async () => {
    if (currentPage >= totalPages || loading) return;
    
    try {
      setLoading(true);
      const params = new URLSearchParams(searchParams.toString());
      params.set('page', (currentPage + 1).toString());
      
      const res = await fetch(`/api/freelancers?${params.toString()}`);
      if (res.ok) {
        const data = await res.json();
        setFreelancers(prev => [...prev, ...data.freelancers]);
        setCurrentPage(data.currentPage);
        setTotalPages(data.totalPages);
        setTotalCount(data.totalCount);
      }
    } catch (error) {
      console.error('Error loading more freelancers:', error);
    } finally {
      setLoading(false);
    }
  };

  const getAverageRating = (reviews: any[]) => {
    if (!reviews || reviews.length === 0) return 0;
    const total = reviews.reduce((sum, review) => sum + review.rating, 0);
    return (total / reviews.length);
  };

  const renderStars = (rating: number) => {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    const stars = [];

    for (let i = 0; i < fullStars; i++) {
      stars.push(
        <svg key={i} width="13" height="12" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M10.2062 12L6.5 9.96162L2.79241 12L3.50213 7.67959L0.5 4.62053L4.64478 3.99059L6.5 0L8.35522 3.99059L12.5 4.62053L9.49787 7.68107L10.2062 12Z" fill="#FB6107"/>
        </svg>
      );
    }

    if (hasHalfStar) {
      stars.push(
        <svg key="half" width="13" height="12" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M10.2062 12L6.5 9.96162L2.79241 12L3.50213 7.67959L0.5 4.62053L4.64478 3.99059L6.5 0L8.35522 3.99059L12.5 4.62053L9.49787 7.68107L10.2062 12Z" fill="#FB6107" opacity="0.5"/>
        </svg>
      );
    }

    return stars;
  };

  return (
    <section className="freelancers-page py-60">
      <div className="container">
        <div className="row g-3 align-items-center">
          {/* Search */}
          <div className="col-lg-6 col-12">
            <form onSubmit={handleSearch} className="search-wrapper">
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19.7291 18.4686L15.035 13.7755C16.3955 12.1421 17.074 10.047 16.9292 7.92618C16.7844 5.80531 15.8275 3.82191 14.2576 2.38859C12.6877 0.955257 10.6256 0.18235 8.50037 0.23065C6.37511 0.27895 4.3503 1.14474 2.84713 2.64791C1.34396 4.15108 0.478169 6.1759 0.429869 8.30115C0.381569 10.4264 1.15448 12.4885 2.5878 14.0584C4.02113 15.6283 6.00453 16.5852 8.12539 16.73C10.2463 16.8748 12.3413 16.1963 13.9747 14.8358L18.6678 19.5299C18.7375 19.5995 18.8202 19.6548 18.9113 19.6925C19.0023 19.7302 19.0999 19.7497 19.1985 19.7497C19.297 19.7497 19.3946 19.7302 19.4856 19.6925C19.5767 19.6548 19.6594 19.5995 19.7291 19.5299C19.7988 19.4602 19.854 19.3775 19.8918 19.2864C19.9295 19.1954 19.9489 19.0978 19.9489 18.9992C19.9489 18.9007 19.9295 18.8031 19.8918 18.7121C19.854 18.621 19.7988 18.5383 19.7291 18.4686ZM1.94846 8.49924C1.94846 7.16421 2.34434 5.85917 3.08604 4.74914C3.82774 3.63911 4.88194 2.77394 6.11534 2.26305C7.34874 1.75216 8.70594 1.61849 10.0153 1.87894C11.3247 2.13939 12.5274 2.78226 13.4714 3.72627C14.4154 4.67027 15.0583 5.87301 15.3188 7.18238C15.5792 8.49175 15.4455 9.84895 14.9346 11.0823C14.4238 12.3158 13.5586 13.37 12.4486 14.1117C11.3385 14.8534 10.0335 15.2492 8.69846 15.2492C6.90885 15.2473 5.19312 14.5355 3.92768 13.27C2.66224 12.0046 1.95044 10.2888 1.94846 8.49924Z" fill="#EF7310"/>
              </svg>
              <input
                type="text"
                className="form-control shadow-none p-0"
                placeholder="Search freelancers..."
                value={searchTerm}
                onChange={(e) => handleSearchChange(e.target.value)}
                onKeyDown={handleSearchInput}
              />
              <button type="submit" style={{ display: 'none' }} />
            </form>
          </div>
          <div className="col-lg col-6">
            <div className="custom-select shadow-none">
              <select
                value={selectedCategory}
                onChange={(e) => handleFilterChange('category', e.target.value)}
              >
                <option value="">Category</option>
                {categories.map((category: any) => (
                  <option key={category.id} value={category.slug}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>
          </div>
          {/* <div className="col-lg col-6">
            <div className="custom-select shadow-none">
              <select
                value={selectedLocation}
                onChange={(e) => handleFilterChange('location', e.target.value)}
              >
                <option value="">Location</option>
                {countries.map((country: any) => (
                  <option key={country.id} value={country.name}>
                    {country.name}
                  </option>
                ))}
              </select>
            </div>
          </div> */}
          <div className="col-lg col-6">
            <div className="custom-select shadow-none">
              <select
                value={selectedRating}
                onChange={(e) => handleFilterChange('rating', e.target.value)}
              >
                <option value="">Rating</option>
                <option value="5">5 Stars</option>
                <option value="4">4+ Stars</option>
                <option value="3">3+ Stars</option>
              </select>
            </div>
          </div>
          <div className="col-lg col-6">
            <div className="custom-select shadow-none">
              <select
                value={selectedSort}
                onChange={(e) => handleFilterChange('sort', e.target.value)}
              >
                <option value="">Sort by</option>
                <option value="newest">Newest</option>
                <option value="oldest">Oldest</option>
              </select>
            </div>
          </div>
        </div>
        <div className="row">
          <div className="col-12">
            <div className="freelancers-listing">
              {freelancers.map((freelancer: any) => {
                const avgRating = getAverageRating(freelancer.receivedReviews);
                const reviewCount = freelancer.receivedReviews?.length || 0;
                return (
                  <div key={freelancer.id} className="freelancers-card">
                    <div className="fc-detail">
                      <div className="fc-profile d-flex align-items-center">
                        <div className="fc-img">
                          {freelancer.profileImage || freelancer.profile?.profileImage ? (
                            <img src={freelancer.profileImage || freelancer.profile?.profileImage} alt="Profile" />
                          ) : (
                            <img src="/assets/image/user.png" alt="Profile" />
                          )}
                        </div>
                        <div className="fc-content">
                          <h5>
                            {freelancer.name || `${freelancer.profile?.firstName || ''} ${freelancer.profile?.lastName || ''}`.trim() || freelancer.email || 'User'}
                          </h5>
                          <div className="d-flex align-items-center">
                            <span className="star-icon">
                              {renderStars(avgRating)}
                            </span>
                            {
                              (avgRating > 0 ||  reviewCount > 0)? (
                                <>
                                 {avgRating.toFixed(1)} ({reviewCount}+ Reviews)
                                 </>
                              ):(
                                <>
                                  No review yet 
                                </>
                              )
                            }
                           
                          </div>
                        </div>
                      </div>
                      <div className="fc-dis">
                        <p>
                          {freelancer.profile?.title || freelancer.profile?.bio?.substring(0, 60) || 'Creative Professional'}
                        </p>
                      </div>
                      <div className="divider"></div>
                      <ul className="fc-contact">
                        <li className="fc-text">
                          <div className="icon">
                            <img src="/assets/image/gmail.svg" alt="gmail" />
                          </div>
                          {freelancer.email}
                        </li>
                        {freelancer.profile?.phone && (
                          <li className="fc-text">
                            <div className="icon">
                              <img src="/assets/image/call.svg" alt="call" />
                            </div>
                            {freelancer.profile.phone}
                          </li>
                        )}
                        <li className="fc-text">
                          <div className="icon">
                            <img src="/assets/image/location.svg" alt="location" />
                          </div>
                          {freelancer.profile?.country?.name || 'Location not specified'}
                        </li>
                      </ul>
                    </div>
                    <div className="freelancers-action button-group d-flex gap-2 flex-wrap">
                      <Link href={`/${locale}/freelancers/${freelancer.id}`} className="custom-btn primary-outline col text-nowrap">
                        View Profile
                      </Link>
                      {/* Hide hire button if logged in user is a freelancer */}
                      {session?.user?.role !== 'FREELANCER' && (
                        <button type="button" className="custom-btn secondary-outline col" onClick={() => showInfo('Contact feature coming soon!', 'Coming soon')}>
                          Hire
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
            {/* Loading indicator */}
            {loading && freelancers.length === 0 && (
              <div className="d-flex justify-content-center py-4">
                <div className="text-muted">Loading freelancers...</div>
              </div>
            )}
            {/* Load More Button */}
            {totalPages > 1 && currentPage < totalPages && !loading && (
              <div className="loadmore button-group d-flex justify-content-center">
                <button
                  className="custom-btn primary-outline"
                  onClick={handleLoadMore}
                  disabled={loading}
                >
                  {loading ? 'Loading...' : 'Load More'}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
