import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import { useProjects } from '@/hooks/useProjects';
import { Button } from '@/components/ui/button';
import { Plus, Loader2 } from 'lucide-react';
import ProjectsList from '@/components/projects/ProjectsList';
import EmptyProjects from '@/components/projects/EmptyProjects';
import useRoleDetection from '@/hooks/useRoleDetection';
import SearchBar from '@/components/SearchBar';
import { useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
import Footer from '@/components/Footer';

const ProjectsPage = () => {
  const [searchParams] = useSearchParams();
  const searchQuery = searchParams.get('search') || '';
  const { projects, isLoading, error, refetchProjects } = useProjects();
  const { user } = useAuth();
  const navigate = useNavigate();
  const { isFounder, isContributor, isInvestor } = useRoleDetection();

  // Filter projects client-side based on search query if needed
  const filteredProjects = searchQuery 
    ? projects.filter(project => 
        project.title?.toLowerCase().includes(searchQuery.toLowerCase()) || 
        project.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        project.category?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    : projects;
  
  // Pre-fetch projects on initial render if empty
  useEffect(() => {
    if (projects.length === 0 && !isLoading) {
      refetchProjects();
    }
  }, []);
  
  const handleCreateProject = () => {
    if (user) {
      navigate('/projects/new');
    } else {
      navigate('/login', { state: { returnUrl: '/projects/new' } });
    }
  };
  
  const handleClearFilters = () => {
    refetchProjects();
    toast.success('Filters cleared');
  };
  
  const handleProjectClick = (projectId: string) => {
    navigate(`/projects/${projectId}`);
  };

  const handleSearch = (term: string) => {
    navigate(`/projects?search=${encodeURIComponent(term)}`);
  };

  return (
    <div className="min-h-screen flex flex-col">
      <div className="container mx-auto px-4 py-8 mt-16 flex-grow">
        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
          <div>
            <h1 className="text-3xl font-bold">Projects</h1>
            <p className="text-muted-foreground mt-1">Discover innovative projects or start your own</p>
          </div>

          <div className="w-full md:w-auto flex flex-col md:flex-row gap-3">
            <div className="w-full md:w-64">
              <SearchBar 
                placeholder="Search projects..." 
                onSearch={handleSearch}
                showResultsInline={false}
              />
            </div>
            {user && isFounder ? (
              <Button onClick={handleCreateProject} className="flex items-center gap-2">
                <Plus className="h-4 w-4" />
                New Project
              </Button>
            ) : user ? null : (
              <Button onClick={handleCreateProject} className="flex items-center gap-2">
                <Plus className="h-4 w-4" />
                Sign in to create
              </Button>
            )}
          </div>
        </div>
        
        {isLoading ? (
          <div className="flex justify-center items-center h-64">
            <Loader2 className="h-10 w-10 animate-spin text-primary" />
          </div>
        ) : filteredProjects.length === 0 ? (
          <EmptyProjects 
            clearFilters={handleClearFilters}
            isFounder={Boolean(user && isFounder)}
            showCreateButton={Boolean(user && isFounder)}
            searchQuery={searchQuery} 
          />
        ) : (
          <ProjectsList
            projects={filteredProjects}
            isLoading={false}
            error={null}
            onProjectClick={handleProjectClick}
            isContributor={Boolean(user && isContributor)}
            isInvestor={Boolean(user && isInvestor)}
            showCreateButton={Boolean(user && isFounder)}
            onDeleteSuccess={() => {
              refetchProjects();
              toast.success('Project deleted successfully');
            }}
          />
        )}
      </div>
      <Footer />
    </div>
  );
};

export default ProjectsPage;