import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useAuth } from "@/context/AuthContext";
import { useProfileCompletion } from "@/hooks/useProfileCompletion";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { toast } from "sonner";
import { checkUserMembership } from "@/utils/membershipUtils";
import ProfileCompletionBanner from "@/components/dashboard/ProfileCompletionBanner";
import { initializeUserProjects } from "@/utils/projectUtils";
import ProfileHeader from "@/components/ProfileHeader";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { MessageSquare, Search, Users, Briefcase, TrendingUp, ExternalLink, BarChart3, Layout, ListChecks, User } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { useFounderActions } from "@/hooks/founder/useFounderActions";
import FounderTasksWidget from "@/components/founder/FounderTasksWidget";
import { FounderDashboardContent } from "@/components/features/founder/Dashboard";
import FounderDetailedProfile from '@/components/FounderDetailedProfile';
import { useFounderDashboard } from '@/hooks/founder/useFounderDashboard';

interface MarketInsight {
  id: string;
  title: string;
  description: string;
  source: string;
}

export default function FounderDashboard() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const tabFromUrl = searchParams.get('tab');
  const { profileCompletion, isLoading } = useProfileCompletion(user?.id);
  const [aiSearchQuery, setAiSearchQuery] = useState("");
  const [aiSearchResults, setAiSearchResults] = useState<MarketInsight[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [activeTab, setActiveTab] = useState(tabFromUrl || 'dashboard');
  const { data: dashboardData, isLoading: loadingDashboard, loadDashboardData } = useFounderDashboard();
  
  const { 
    handleProjectAction, 
    handleTaskAction,
    handleTeamAction 
  } = useFounderActions();
  
  // Load dashboard data when component mounts
  useEffect(() => {
    if (user?.id) {
      loadDashboardData();
    }
  }, [user?.id, loadDashboardData]);
  
  useEffect(() => {
    const checkAccess = async () => {
      if (!user) {
        toast.error("Please log in to access the founder dashboard");
        navigate('/login');
        return;
      }
      
      const userRoles = user?.user_metadata?.user_roles || [];
      if (!userRoles.includes('entrepreneur') && !userRoles.includes('founder')) {
        toast.error("Access denied. This page is for entrepreneurs only.");
        navigate('/dashboard');
        return;
      }
      
      try {
        const hasFounderPlan = await checkUserMembership(user.id, 'founder');
        if (!hasFounderPlan) {
          console.log("No founder membership found, but will allow access for demo purposes");
        }
      } catch (error) {
        console.error("Error checking membership:", error);
      }
    };
    
    checkAccess();
  }, [user, navigate]);

  const handleEditProfile = () => {
    navigate('/founder-onboarding', { state: { editMode: true } });
  };

  const handleFindContributors = () => {
    navigate('/contributors');
  };

  const handleConnectInvestors = () => {
    navigate('/investors');
  };

  const handleNewProject = () => {
    navigate('/projects/new');
  };

  const handleViewTasks = () => {
    handleTaskAction('view-all');
  };

  const handleAiSearch = async () => {
    if (!aiSearchQuery.trim()) {
      toast.error("Please enter a search query");
      return;
    }

    setIsSearching(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      setAiSearchResults([
        {
          id: 'result1',
          title: `Market Analysis: ${aiSearchQuery}`,
          description: `Comprehensive market analysis showing key trends, competitor landscape, and growth opportunities in ${aiSearchQuery} sector.`,
          source: 'AI Market Analysis'
        },
        {
          id: 'result2',
          title: `Investment Landscape: ${aiSearchQuery}`,
          description: `Recent funding activities, top investors, and market valuation metrics for ${aiSearchQuery} industry.`,
          source: 'Investment Insights'
        },
        {
          id: 'result3',
          title: `Growth Opportunities: ${aiSearchQuery}`,
          description: `Identified market gaps and potential areas for business expansion in ${aiSearchQuery} market.`,
          source: 'Growth Analysis'
        }
      ]);

      toast.success("Market insights generated successfully");
    } catch (error) {
      console.error("Error performing AI search:", error);
      toast.error("Failed to generate market insights. Please try again.");
    } finally {
      setIsSearching(false);
    }
  };

  const handleTabChange = (value: string) => {
    setActiveTab(value);
    navigate(`/founder-dashboard?tab=${value}`);
  };

  if (!user) {
    return null;
  }

  return (
    <div className="min-h-screen flex flex-col bg-white">
      <Navbar hideProfileAlert={true} />
      <main className="flex-grow pt-16 pb-16">
        <div className="container mx-auto px-4 py-8">
          <div className="flex justify-between items-center">
            <ProfileHeader
              title="Founder Dashboard"
              description="Manage your projects and get AI-powered market insights"
              onEdit={handleEditProfile}
              showEditButton={true}
            />
            <Button 
              onClick={handleViewTasks}
              className="flex items-center gap-2"
            >
              <ListChecks className="h-4 w-4" />
              My Tasks
            </Button>
          </div>
          
          {/* Profile completion banner */}
          {!profileCompletion?.isComplete && (
            <ProfileCompletionBanner
              isProfileCompleted={profileCompletion?.isComplete || false}
              onCompleteProfile={handleEditProfile}
              userRole="founder"
              message={profileCompletion?.message || "Complete your founder profile to access all features"}
              actionText="Complete Profile"
              showEditButton={true}
            />
          )}
          
          <div className="space-y-8 mt-6">
            <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
              <TabsList className="mb-6">
                <TabsTrigger value="dashboard">Dashboard</TabsTrigger>
                <TabsTrigger value="projects">Projects</TabsTrigger>
                <TabsTrigger value="profile">Profile</TabsTrigger>
              </TabsList>
              
              <TabsContent value="dashboard" className="space-y-8">
                <FounderDashboardContent />
              </TabsContent>
              
              <TabsContent value="projects" className="space-y-8">
                <FounderDashboardContent showProjectsOnly={true} />
              </TabsContent>
              
              <TabsContent value="profile" className="space-y-8">
                <FounderDetailedProfile />
              </TabsContent>
            </Tabs>
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
}
is it correct with all the founder profile, form, dashboard, editing, saving profile in supabase