'use client';

import { useState, useEffect, use } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Image from 'next/image';
import Link from 'next/link';
import { useToast } from '@/components/ui/ToastContext';
import BidModal from '@/components/freelancer/BidModal';
import { BidFormData } from '@/types/bid';
import FreelancerLayout from '@/components/layout/FreelancerLayout';
import { getCountryDataByDomain } from '@/lib/countries';
import './my-projects.css';

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

interface Project {
  id: string;
  title: string;
  description: string;
  category: string;
  categoryIcon: string;
  budget: number;
  duration: number;
  status: 'RECOMMENDED' | 'PROPOSED' | 'AWARDED' | 'CANCELLED' | 'COMPLETED';
  bidsCount: number;
  myReviewIs:any;
  client: {
    id: string;
    name: string;
    profileImage: string;
    rating: number;
    reviewCount: number;
  };
  myBid?: {
    id: string;
    status: 'PENDING' | 'ACCEPTED' | 'REJECTED';
    amount: number;
    duration: number;
    proposal: string;
    createdAt: string;
  };
  createdAt: string;
  updatedAt: string;
}

interface ProfileData {
  id: string;
  firstName: string;
  lastName: string;
  profileImage: string;
  rating: number;
  reviewCount: number;
}

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

interface ProjectsData {
  projects: Project[];
  counts: {
    recommended: number;
    proposed: number;
    awarded: number;
    cancelled: number;
    completed: number;
  };
  pagination: {
    currentPage: number;
    totalPages: number;
    totalItems: number;
    itemsPerPage: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };
}

export default function FreelancerMyProjectsPage({ params }: MyProjectsPageProps) {
  const datacounter = getCountryDataByDomain();
  const { locale } = use(params);
  const router = useRouter();
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [projectsData, setProjectsData] = useState<ProjectsData | null>(null);
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [activeFilter, setActiveFilter] = useState<string>('recommended');
  const [isInitialized, setIsInitialized] = useState(false);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [categories, setCategories] = useState<Category[]>([]);
  const [isCategoriesLoading, setIsCategoriesLoading] = useState(true);
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1);

  // Bid modal states
  const [isBidModalOpen, setIsBidModalOpen] = useState(false);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [isUpdateBid, setIsUpdateBid] = useState(false);
  const [selectedBidForUpdate, setSelectedBidForUpdate] = useState<{projectId: string, bidId: string} | null>(null);

  // Error states
  const [error, setError] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);

  // Initialize filter from URL params and handle URL changes
  useEffect(() => {
    const checkUrlParams = () => {
      if (typeof window !== 'undefined') {
        const urlParams = new URLSearchParams(window.location.search);
        const statusParam = urlParams.get('status');
        const newFilter = statusParam && ['recommended', 'proposed', 'awarded', 'cancelled', 'completed'].includes(statusParam.toLowerCase()) 
          ? statusParam.toLowerCase() 
          : 'recommended';
        
        if (newFilter !== activeFilter || !isInitialized) {
          setActiveFilter(newFilter);
          setCurrentPage(1); // Reset to first page when filter changes
        }
        
        if (!isInitialized) {
          setIsInitialized(true);
        }
      }
    };

    // Check immediately
    checkUrlParams();

    // Listen for URL changes (back/forward buttons)
    const handlePopState = () => {
      checkUrlParams();
    };

    // Listen for focus events to catch navigation from sidebar
    const handleFocus = () => {
      checkUrlParams();
    };

    // Set up a periodic check to catch any missed URL changes
    const intervalCheck = setInterval(checkUrlParams, 1000);

    window.addEventListener('popstate', handlePopState);
    window.addEventListener('focus', handleFocus);
    
    return () => {
      window.removeEventListener('popstate', handlePopState);
      window.removeEventListener('focus', handleFocus);
      clearInterval(intervalCheck);
    };
  }, []); // Remove dependencies to avoid infinite loop

  // Separate effect to handle activeFilter changes and trigger data fetch
  useEffect(() => {   
    
    if(categoryFilter === "add_more"){
      router.push(`/${locale}/freelancer/membership`);      
    }else if (isInitialized && activeFilter) {
      fetchProjects();
    }
  }, [activeFilter, currentPage, debouncedSearchTerm, categoryFilter, isInitialized]);

  // Debounce search term to avoid spamming API
  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearchTerm(searchTerm.trim()), 300);
    return () => clearTimeout(t);
  }, [searchTerm]);

  useEffect(() => {
    if (status === 'loading' || !isInitialized) return;
    
    if (!session) {
      router.push(`/${locale}/login`);
      return;
    }

    fetchProfile();
    fetchCategories();
  }, [session, status, locale, router, isInitialized]);

  const fetchCategories = async () => {
    try {
      setIsCategoriesLoading(true);
      // Prefer freelancer's subscribed categories
      const response = await fetch('/api/freelancer/subscribed-categories');
      
      if (response.ok) {
        const data = await response.json();
        const list = Array.isArray(data)
          ? data
          : (data?.data ?? []);
        setCategories(list || []);
      } else {
        console.warn('Failed to fetch subscribed categories, using all categories fallback');
        // Fallback to all categories
        const all = await fetch('/api/categories');
        if (all.ok) {
          const allData = await all.json();
          setCategories(allData || []);
        }
      }
    } catch (error: any) {
      console.error('Error fetching categories:', error);
      const errorMessage = error instanceof TypeError && error.message.includes('fetch')
        ? 'Network error loading categories.'
        : 'Failed to load categories.';
      showError(errorMessage, 'Categories Load Error');
    } finally {
      setIsCategoriesLoading(false);
    }
  };

  const fetchProfile = async () => {
    try {
      const response = await fetch('/api/freelancer/profile', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch profile');
      }

      const data = await response.json();
      if (data.success) {
        setProfile(data.data);
      } else {
        console.warn('Failed to fetch profile:', data.error);
      }
    } catch (error: any) {
      console.error('Error fetching profile:', error);
    }
  };

  const fetchProjects = async (retry = false) => {
    if (retry) {
      setRetryCount(prev => prev + 1);
    } else {
      setRetryCount(0);
      setError(null);
    }
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: '12',
        status: activeFilter.toUpperCase(),
        ...(debouncedSearchTerm && { search: debouncedSearchTerm }),
        ...(categoryFilter && { category: categoryFilter }),
      });
       if(!datacounter?.id){
          setError('Country is missing');
          return false;
      }
      params.set('countryId', datacounter?.id);
      const response = await fetch(`/api/freelancer/my-projects?${params.toString()}`);
     
      if (!response.ok) {
        if (response.status === 404) {
          // Handle 404 gracefully - set empty data
          setProjectsData({
            projects: [],
            counts: {
              recommended: 0,
              proposed: 0,
              awarded: 0,
              cancelled: 0,
              completed: 0
            },
            pagination: {
              currentPage: 1,
              totalPages: 1,
              totalItems: 0,
              itemsPerPage: 12,
              hasNextPage: false,
              hasPrevPage: false
            }
          });
          return;
        }
        
        if (response.status === 401) {
          // Unauthorized - redirect to login
          router.push(`/${locale}/login`);
          return;
        }
        
        // Try to get error message from response
        let errorMessage = 'Failed to load projects';
        try {
          const errorData = await response.json();
          errorMessage = errorData.error || errorData.message || errorMessage;
        } catch {
          // If we can't parse the error response, use the default message
        }
        
        setError(errorMessage);
        if (retryCount === 0) {
          showError(errorMessage, 'Projects Load Failed');
        }
        setProjectsData({
          projects: [],
          counts: {
            recommended: 0,
            proposed: 0,
            awarded: 0,
            cancelled: 0,
            completed: 0
          },
          pagination: {
            currentPage: 1,
            totalPages: 1,
            totalItems: 0,
            itemsPerPage: 12,
            hasNextPage: false,
            hasPrevPage: false
          }
        });
        return;
      }
      
      const data = await response.json();
      
      // Check if response has success field and data
      if (data.success && data.data) {
        setProjectsData(data.data);
      } else if (data.error) {
        // API returned an error response
        const errorMessage = data.error || 'Failed to fetch projects';
        setError(errorMessage);
        if (retryCount === 0) {
          showError(errorMessage, 'API Error');
        }
        setProjectsData({
          projects: [],
          counts: {
            recommended: 0,
            proposed: 0,
            awarded: 0,
            cancelled: 0,
            completed: 0
          },
          pagination: {
            currentPage: 1,
            totalPages: 1,
            totalItems: 0,
            itemsPerPage: 12,
            hasNextPage: false,
            hasPrevPage: false
          }
        });
        return;
      } else {
        // Unexpected response format
        const errorMessage = 'Invalid response format from server';
        setError(errorMessage);
        if (retryCount === 0) {
          showError(errorMessage, 'Server Error');
        }
        setProjectsData({
          projects: [],
          counts: {
            recommended: 0,
            proposed: 0,
            awarded: 0,
            cancelled: 0,
            completed: 0
          },
          pagination: {
            currentPage: 1,
            totalPages: 1,
            totalItems: 0,
            itemsPerPage: 12,
            hasNextPage: false,
            hasPrevPage: false
          }
        });
        return;
      }
      setError(null); // Clear any previous errors
    } catch (error) {
      console.error('Error fetching projects:', error);
      
      let errorMessage = 'Failed to load projects';
      
      // Handle different types of errors
      if (error instanceof TypeError && error.message.includes('fetch')) {
        errorMessage = 'Network error. Please check your connection and try again.';
      } else if (error instanceof Error) {
        errorMessage = error.message;
      }
      
      setError(errorMessage);
      
      // Only show toast on first attempt, not retries
      if (retryCount === 0) {
        const errorTitle = error instanceof TypeError && error.message.includes('fetch') 
          ? 'Network Error' 
          : 'Projects Load Error';
        showError(errorMessage, errorTitle);
      }
      
      // Set empty data structure on error so UI doesn't break
      setProjectsData({
        projects: [],
        counts: {
          recommended: 0,
          proposed: 0,
          awarded: 0,
          cancelled: 0,
          completed: 0
        },
        pagination: {
          currentPage: 1,
          totalPages: 1,
          totalItems: 0,
          itemsPerPage: 12,
          hasNextPage: false,
          hasPrevPage: false
        }
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleFilterChange = (filter: string) => {
    setActiveFilter(filter);
    setCurrentPage(1);
    // Update URL to reflect the current filter
    const newUrl = new URL(window.location.href);
    newUrl.searchParams.set('status', filter);
    window.history.replaceState({}, '', newUrl.toString());
  };

  const handleOpenBidModal = (project: Project) => {
    setSelectedProject(project);
    setIsBidModalOpen(true);
  };

  const handleCloseBidModal = () => {
    setIsBidModalOpen(false);
    setSelectedProject(null);
    setIsUpdateBid(false);
    setSelectedBidForUpdate(null);
  };

  const handleBidUpdate = (project: Project) => {
    if (project.myBid) {
      setSelectedBidForUpdate({ projectId: project.id, bidId: project.myBid.id });
      setSelectedProject(project);
      setIsUpdateBid(true);
      setIsBidModalOpen(true);
    }
  };


  const handleBidSubmitted = async (bidData: BidFormData) => {
    try {
      const url = isUpdateBid && selectedBidForUpdate 
        ? `/api/projects/${selectedBidForUpdate.projectId}/bid/${selectedBidForUpdate.bidId}`
        : `/api/projects/${selectedProject?.id}/bid`;
      
      const method = isUpdateBid ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'x-toast-controlled': 'true',
        },
        body: JSON.stringify({
          amount: bidData.price,
          deliveryTime: bidData.days,
          proposal: bidData.description,
          ...(isUpdateBid ? {} : { projectId: selectedProject?.id })
        }),
      });

      const responseClone = response.clone();
      
      if (!response.ok) {
        let errorMessage = 'Failed to submit bid';
        let errorBody: any = null;
        let errorText: string | null = null;

        try {
          errorBody = await response.json();
        } catch {
          // ignore
        }

        // If body is empty object or not helpful, try reading as text
        if (!errorBody || (typeof errorBody === 'object' && Object.keys(errorBody).length === 0)) {
          try {
            const text = await responseClone.text();
            errorText = text && text.trim().length > 0 ? text : null;
            // Try parse text as JSON if it looks like JSON
            if (errorText && (errorText.startsWith('{') || errorText.startsWith('['))) {
              try {
                const parsed = JSON.parse(errorText);
                errorBody = parsed;
                errorText = null;
              } catch {
                // keep text
              }
            }
          } catch {
            // ignore
          }
        }

        // Derive friendly message
        if (errorBody) {
          const candidate = (errorBody.message || errorBody.error || errorBody.details);
          if (typeof candidate === 'string' && candidate.trim().length > 0) {
            errorMessage = candidate;
          } else if (Array.isArray(errorBody.errors)) {
            errorMessage = errorBody.errors.join(', ');
          }
        } else if (errorText) {
          errorMessage = errorText;
        } else if (response.statusText) {
          errorMessage = `${response.status} ${response.statusText}`;
        }

        const errorTitle = response.status === 400 ? 'Validation Error' : 'Submission Failed';
        
        console.error('Bid submission failed:', {
          status: response.status,
          body: errorBody ?? errorText ?? null,
        });
        showError(errorMessage, errorTitle);
        return;
      }

      const result = await response.json().catch(() => ({}));

      // Handle API responses that return success flag
      if (typeof result.success === 'boolean' && !result.success) {
        const msg = result.message || result.error || 'Failed to submit bid';
        const title = 'Submission Failed';
        showError(msg, title);
        return;
      }
      
      // Refresh projects data
      fetchProjects();
      handleCloseBidModal();
      
      const successMessage = isUpdateBid 
        ? (result.message || 'Bid updated successfully!')
        : (result.message || 'Bid submitted successfully! You will be notified when the client responds.');
      const successTitle = isUpdateBid ? 'Bid Updated' : 'Bid Submitted';
      showSuccess(successMessage, successTitle);
      
    } catch (error: any) {
      console.error('Error submitting bid:', error);
      const errorMessage = error?.message || 'An unexpected error occurred while submitting your bid. Please check your connection and try again.';
      const errorTitle = (error instanceof TypeError && String(error.message || '').includes('fetch')) ? 'Network Error' : 'Submission Failed';
      showError(errorMessage, errorTitle);
    }
  };

  const getStatusBadgeClass = (status: string) => {
    switch (status.toLowerCase()) {
      case 'recommended': return 'badge-recommended';
      case 'proposed': return 'badge-proposed';
      case 'awarded': return 'badge-awarded';
      case 'cancelled': return 'badge-cancelled';
      case 'completed': return 'badge-completed';
      default: return 'badge-recommended';
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

    const handleShareProject = async (project: Project) => {
    const shareUrl = `${window.location.origin}/${locale}/projects/${project.id}`;
    const shareData = {
      title: project.title,
      text: `Check out this project: ${project.title}`,
      url: shareUrl
    };

    try {
      // Try native Web Share API first (mobile)
      if (navigator.share) {
        await navigator.share(shareData);
        showSuccess('Project shared successfully!');
      } else {
        // Fallback to clipboard
        await navigator.clipboard.writeText(shareUrl);
        showSuccess('Project link copied to clipboard!');
      }
    } catch (err) {
      // Final fallback - create temporary textarea
      try {
        const textArea = document.createElement('textarea');
        textArea.value = shareUrl;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showSuccess('Project link copied to clipboard!');
      } catch (fallbackErr) {
        showError('Failed to share project');
      }
    }
  };

  const renderStars = (rating: number) => {
    return (
      <div className="star-display">
        {/* {[1, 2, 3, 4, 5].map((star) => (
          <svg
            key={star}
            width="13"
            height="12"
            viewBox="0 0 13 12"
            fill={star <= rating ? "#FB6107" : "none"}
            stroke="#FB6107"
            strokeWidth="1"
          >
            <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"/>
          </svg>
        ))} */}
        <svg
            key={1}
            width="13"
            height="12"
            viewBox="0 0 13 12"
            fill={"#FB6107"}
            stroke="#FB6107"
            strokeWidth="1"
          >
            <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"/>
          </svg>
      </div>
    );
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!projectsData && error) {
    return (
      <section className="profile-wrapper client-wrapper py-60">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <Image src="/assets/image/error.svg" alt="Error" width={200} height={150} />
                <h2>Unable to load projects</h2>
                <p>{error}</p>
                <div className="error-actions">
                  <button 
                    onClick={() => fetchProjects(true)} 
                    className="custom-btn primary-fill"
                    disabled={isLoading}
                  >
                    {isLoading ? 'Retrying...' : retryCount > 0 ? `Retry (${retryCount + 1})` : 'Retry'}
                  </button>
                  <Link href={`/${locale}/dashboard`} className="custom-btn secondary-outline">
                    Back to Dashboard
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

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

      unreadMessagesCount={0}
    >
      <div className="content-box">
        <div className="filter-head" id="filterTabs">
          <div 
            className={`filter-card primary ${activeFilter === 'recommended' ? 'active' : ''}`} 
            onClick={() => handleFilterChange('recommended')}
          >
            <div className="filter-inner">
              <div className="filter-top">
                <div className="count">{projectsData?.counts.recommended}</div> 
                <div className="filter-icon">
                  <Image src="/assets/image/recommended.svg" alt="recommended" width={24} height={24} />
                </div>
              </div>
              <div className="filter-title">Recommended</div>
              <div className="filter-label">Projects</div>
            </div>
            <div className="bg-shap"></div>
          </div>
          
          <div 
            className={`filter-card proposed ${activeFilter === 'proposed' ? 'active' : ''}`} 
            onClick={() => handleFilterChange('proposed')}
          >
            <div className="filter-inner">
              <div className="filter-top">
                <div className="count">{projectsData?.counts.proposed}</div> 
                <div className="filter-icon">
                  <Image src="/assets/image/proposed.svg" alt="proposed" width={24} height={24} />
                </div>
              </div>
              <div className="filter-title">Proposed</div>
              <div className="filter-label">Projects</div>
            </div>
            <div className="bg-shap"></div>
          </div>
          
          <div 
            className={`filter-card awarded ${activeFilter === 'awarded' ? 'active' : ''}`} 
            onClick={() => handleFilterChange('awarded')}
          >
            <div className="filter-inner">
              <div className="filter-top">
                <div className="count">{projectsData?.counts.awarded}</div> 
                <div className="filter-icon">
                  <Image src="/assets/image/awarded.svg" alt="awarded" width={24} height={24} />
                </div>
              </div>
              <div className="filter-title">Awarded</div>
              <div className="filter-label">Projects</div>
            </div>
            <div className="bg-shap"></div>
          </div>
          
          <div 
            className={`filter-card cancelled ${activeFilter === 'cancelled' ? 'active' : ''}`} 
            onClick={() => handleFilterChange('cancelled')}
          >
            <div className="filter-inner">
              <div className="filter-top">
                <div className="count">{projectsData?.counts.cancelled}</div> 
                <div className="filter-icon">
                  <Image src="/assets/image/cancelled.svg" alt="cancelled" width={24} height={24} />
                </div>
              </div>
              <div className="filter-title">Cancelled</div>
              <div className="filter-label">Projects</div>
            </div>
            <div className="bg-shap"></div>
          </div>
          
          <div 
            className={`filter-card completed ${activeFilter === 'completed' ? 'active' : ''}`} 
            onClick={() => handleFilterChange('completed')}
          >
            <div className="filter-inner">
              <div className="filter-top">
                <div className="count">{projectsData?.counts.completed}</div> 
                <div className="filter-icon">
                  <Image src="/assets/image/completed.svg" alt="completed" width={24} height={24} />
                </div>
              </div>
              <div className="filter-title">Completed</div>
              <div className="filter-label">Projects</div>
            </div>
            <div className="bg-shap"></div>
          </div>
        </div>

        <div className="project-section active">
          <div className="tab-title">
            <h5>
              {activeFilter.charAt(0).toUpperCase() + activeFilter.slice(1)} Projects ({projectsData?.projects.length})
            </h5>
            <div className="project-filter">
              <div 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"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <div className="custom-select shadow-none">
                <select value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)}>
                  <option value="">All Categories</option>
                  {categories.map((category) => (
                    <option key={category.id} value={category.slug}>
                      {category.name}
                    </option>
                  ))}
                  <option value="add_more" className='add-category'>+ Add Category</option>
                </select>
              </div>
            </div>
          </div>
          
          <div className="project-card-outer">
            {projectsData?.projects.length === 0 ? (
              <div className="no-projects-container">
                <div className="no-projects-content">
                  <Image src="/assets/image/no-freelancer.svg" alt="No projects" width={200} height={150} />
                  <h3>No Projects Found</h3>
                  <p>
                    {activeFilter === 'recommended' && 'No new projects available that match your profile.'}
                    {activeFilter === 'proposed' && 'You haven\'t submitted any project proposals yet.'}
                    {activeFilter === 'awarded' && 'You don\'t have any awarded projects yet.'}
                    {activeFilter === 'cancelled' && 'No cancelled or rejected projects.'}
                    {activeFilter === 'completed' && 'You haven\'t completed any projects yet.'}
                  </p>
                  {activeFilter === 'recommended' && (
                    <Link href={`/${locale}/find-projects`} className="custom-btn primary-fill">
                      Browse All Projects
                    </Link>
                  )}
                  {error && (
                    <button 
                      onClick={() => fetchProjects(true)} 
                      className="custom-btn secondary-outline"
                      disabled={isLoading}
                    >
                      {isLoading ? 'Refreshing...' : 'Refresh'}
                    </button>
                  )}
                </div>
              </div>
            ) : (
              projectsData?.projects.map((project) => (
                <div key={project.id} className="project-card">
                  <div>
                    <div className="work-outer">
                      <div className="work-profile">
                        <Image src={project.categoryIcon} alt={project.category} width={20} height={20} />
                        <span>{project.category}</span>
                      </div>
                      <div className="work-time">
                        <Image src="/assets/image/timer.svg" alt="timer" width={16} height={16} />
                        <span>Work duration- {project.duration} days</span>
                      </div>
                    </div>                  
                    <div className="project-info">
                      <div className="project-title">{project.title}</div>
                      <div className="project-user">
                        <div className="pu-profile d-flex align-items-center">
                          <div className="pu-img">
                            <Image 
                              src={project.client.profileImage} 
                              alt="Client Profile" 
                              width={40} 
                              height={40} 
                            />
                          </div>
                          <div className="pu-content">
                            <h5>{project.client.name}</h5>                       
                            <div className="d-flex align-items-center gap-1">
                              { (project.client.rating || project.client.reviewCount)
                                  ?
                                    (<>
                                      <div className='d-flex align-items-center gap-1'>
                                        <span className="star-icon">
                                          {renderStars(project.client.rating)}
                                        </span> 
                                        {project.client.rating} ({project.client.reviewCount}+ Reviews)
                                      </div>
                                    </>)
                                  :
                                    (
                                      <>
                                        <svg 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>                            
                                        No reviews yet
                                      </>
                                    )
                              }
                            </div>
                          </div>
                        </div>
                        <div className="pu-share">
                          <div className="view-bid">
                            <Image src="/assets/image/noto_fire.svg" alt="bids" width={16} height={16} />
                            {project.bidsCount} Bids
                          </div>
                          {activeFilter === 'proposed' && project.myBid && (
                            <div className="deal-price-outer">
                              <div className="deal-price">
                                <div className="mybid">My Bid</div>
                                <span className="price-b">
                                  {datacounter?.currencySymbol ?? ''} {project.myBid.amount}
                                  <span className="days">{project.myBid.duration} days</span>
                                </span>
                              </div>
                            </div>
                          )}
                          {/* <button className="share-profile">
                            <svg width="21" height="21" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                              <path d="M15.5 13.8993C14.8667 13.8993 14.3 14.1494 13.8667 14.541L7.925 11.0827C7.96667 10.891 8 10.6993 8 10.4993C8 10.2993 7.96667 10.1077 7.925 9.91602L13.8 6.49102C14.25 6.90768 14.8417 7.16602 15.5 7.16602C16.8833 7.16602 18 6.04935 18 4.66602C18 3.28268 16.8833 2.16602 15.5 2.16602C14.1167 2.16602 13 3.28268 13 4.66602C13 4.86602 13.0333 5.05768 13.075 5.24935L7.2 8.67435C6.75 8.25768 6.15833 7.99935 5.5 7.99935C4.11667 7.99935 3 9.11602 3 10.4993C3 11.8827 4.11667 12.9993 5.5 12.9993C6.15833 12.9993 6.75 12.741 7.2 12.3243L13.1333 15.791C13.0917 15.966 13.0667 16.1493 13.0667 16.3327C13.0667 17.6743 14.1583 18.766 15.5 18.766C16.8417 18.766 17.9333 17.6743 17.9333 16.3327C17.9333 14.991 16.8417 13.8993 15.5 13.8993Z" fill="#EF7310"/>
                            </svg>
                          </button> */}

                          <button 
                              type="button"
                              onClick={() => handleShareProject(project)}
                              className="share-profile"
                              title="Share project"
                            >
                              <Image 
                                src="/assets/image/share.svg" 
                                alt="share"
                                width={0}
                                height={0}
                                sizes="100vw"
                                style={{ width: '16px', height: '16px' }}
                              />
                            </button>

                        </div>
                      </div>
                      <div 
                        className="project-dis"
                        dangerouslySetInnerHTML={{ __html: project.description }}
                      />
                    </div>
                  </div>
                  <div className="project-bid-oter">
                    <div className="project-price">
                      <Image src="/assets/image/wallet.svg" alt="wallet" width={20} height={20} />
                      {datacounter?.currencySymbol ?? ''} {project.budget}
                    </div>
                    <div className="project-bid">
                      {activeFilter === 'recommended' && (
                        <button 
                          className="custom-btn primary-outline"
                          onClick={() => handleOpenBidModal(project)}
                        >
                          <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M8.5 12H16.5" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                            <path d="M12.5 16V8" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                            <path d="M9.5 22H15.5C20.5 22 22.5 20 22.5 15V9C22.5 4 20.5 2 15.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22Z" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                          Bid
                        </button>
                      )}
                      
                      {activeFilter === 'proposed' && project.myBid && (
                        <>
                          <button 
                            className="custom-btn primary-outline"
                            onClick={() => handleBidUpdate(project)}
                          >
                            <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                              <path d="M11.5 2H9.5C4.5 2 2.5 4 2.5 9V15C2.5 20 4.5 22 9.5 22H15.5C20.5 22 22.5 20 22.5 15V13" stroke="#EF7310" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                              <path d="M16.54 3.02L8.66 10.9C8.35 11.21 8.04 11.82 7.98 12.25L7.52 15.24C7.36 16.26 8.12 17.02 9.14 16.86L12.13 16.4C12.56 16.34 13.17 16.03 13.48 15.72L21.36 7.84C22.6 6.6 23.18 5.13 21.36 3.31C19.54 1.49 18.07 2.07 16.54 3.02Z" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                              <path d="M15.41 4.15C16.01 6.54 17.96 8.49 20.35 9.09" stroke="#EF7310" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                            Update Bid
                          </button>
                        </>
                      )}

                       {activeFilter === 'cancelled' && (
                        <>
                          <span className="custom-btn cancelled">Cancelled</span>
                        </>
                        )}
                       {activeFilter === 'completed' && (
                        <>
                        {
                          project?.myReviewIs > 0 ?(
                            <>
                              <div className='d-flex align-items-center gap-1'>
                                <span className="star-icon">
                                  {renderStars(project?.myReviewIs)}
                                </span> 
                                {project?.myReviewIs} Review
                              </div>
                            </>
                          ):(
                              <>
                                <Link 
                                    href={`/${locale}/freelancer/projects/review/${project.id}`} 
                                    className="custom-btn primary-outline"
                                  >
                                    <Image
                                      src="/assets/image/star.svg"
                                      alt="review"
                                      width={0}
                                      height={0}
                                      sizes="100vw"
                                      style={{ width: '20px', height: '20px',filter: 'brightness(0)'  }}
                                    />
                                    Write Review
                                  </Link>
                                </>
                              )}  
                          </>
                        )}
                      
                      <Link href={`/${locale}/freelancer/projects/${project.id}`} className="custom-btn secondary-outline">
                        <svg width="25" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M14.5249 6.94141L19.5832 11.9997L14.5249 17.0581" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M5.4165 12H19.4415" stroke="#0E9493" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                        View
                      </Link>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
          
          {/* Pagination */}
          {/* {projectsData?.pagination?.totalPages && projectsData.pagination.totalPages > 1 && ( */}
          {(projectsData?.pagination?.totalPages ?? 0) > 1 && (
            <div className="pagination-container">
              <div className="pagination-info">
                Showing {((projectsData?.pagination?.currentPage || 1) - 1) * (projectsData?.pagination?.itemsPerPage || 10) + 1} to {Math.min((projectsData?.pagination?.currentPage || 1) * (projectsData?.pagination?.itemsPerPage || 10), projectsData?.pagination?.totalItems || 0)} of {projectsData?.pagination?.totalItems || 0} projects
              </div>
              <div className="pagination-buttons">
                {projectsData?.pagination?.hasPrevPage && (
                  <button
                    onClick={() => setCurrentPage(currentPage - 1)}
                    className="pagination-btn"
                  >
                    Previous
                  </button>
                )}
                <span className="page-info">
                  Page {projectsData?.pagination.currentPage} of {projectsData?.pagination.totalPages}
                </span>
                {projectsData?.pagination?.hasNextPage && (
                  <button
                    onClick={() => setCurrentPage(currentPage + 1)}
                    className="pagination-btn"
                  >
                    Next
                  </button>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
      
      {/* Bid Modal */}
      <BidModal
        isOpen={isBidModalOpen}
        onClose={handleCloseBidModal}
        projectTitle={selectedProject?.title}
        onSubmit={handleBidSubmitted}
        isUpdateMode={isUpdateBid}
        initialBidData={isUpdateBid && selectedProject?.myBid ? {
          amount: selectedProject.myBid.amount.toString(),
          deliveryTime: selectedProject.myBid.duration.toString(),
          proposal: selectedProject.myBid.proposal
        } : undefined}
      />
    </FreelancerLayout>
  );
}
