diff --git a/src/app/(community)/explore-community/page.tsx b/src/app/(community)/explore-community/page.tsx index 4583406..dad497c 100644 --- a/src/app/(community)/explore-community/page.tsx +++ b/src/app/(community)/explore-community/page.tsx @@ -1,7 +1,424 @@ -import React from "react"; +"use client"; +import React, { useState, useEffect, useMemo } from "react"; +import { useSession } from "@supabase/auth-helpers-react"; +import { supabase } from "../../../utils/supabase"; +import { toast } from "sonner"; +import Pagination from "../../../components/Pagination"; +import Loading from "../../../components/loading"; +import { useUserDetails } from "../../../hooks/useUserDetails"; +import Link from "next/link"; +import { motion } from "framer-motion"; +import { SearchIcon, TrashIcon } from '@heroicons/react/solid'; // Import the search icon +import { LocationMarkerIcon } from '@heroicons/react/solid'; -function page() { - return
page
; +const Page: React.FC = () => { + // Define types + interface Community { + id: string; + community_name: string; + community_description: string; + community_location: string; + community_category: string; + community_members_count: number; + community_image: string; + community_creation_date: string; + is_approved: boolean; } -export default page; + // State hooks + const [loading, setLoading] = useState(true); + const [communities, setCommunities] = useState([]); + const [currentPage, setCurrentPage] = useState(1); + const [itemsPerPage, setItemsPerPage] = useState(9); + const [searchTerm, setSearchTerm] = useState(""); + const [category, setCategory] = useState(""); + const [sortByLikes, setSortByLikes] = useState(""); + const [showAddCommunityForm, setShowAddCommunityForm] = useState(false); // To toggle the form visibility + const [newCommunity, setNewCommunity] = useState({ + community_name: "", + community_description: "", + community_location: "", + community_category: "", + community_image: "", + }); + const [editingCommunityId, setEditingCommunityId] = useState(null); // To track the community being edited + + const [joinFormData, setJoinFormData] = useState({ + name: "", + email: "", + contact: "", + }); + + const session = useSession(); + const { user } = useUserDetails(); + + useEffect(() => { + async function fetchCommunities() { + const { data, error } = await supabase.from("communities").select("*"); + if (error) { + console.error("Error fetching communities:", error); + toast.error("Failed to load communities. Please try again later."); + } else { + setCommunities(data || []); // Set default to empty array if data is null + } + setLoading(false); + } + + fetchCommunities(); + }, []); + + const handleSearchClick = () => { + // Perform search action here + console.log("Search clicked!"); + }; + + const handleFormSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + const { community_name, community_description, community_location, community_category, community_image } = newCommunity; + + if (editingCommunityId) { + // Update the community + const { data, error } = await supabase + .from("communities") + .update({ + community_name, + community_description, + community_location, + community_category, + community_image, + }) + .eq("id", editingCommunityId); + + if (error) { + toast.error("Failed to update community."); + console.error("Error updating community:", error); + } else { + toast.success("Community updated successfully!"); + setShowAddCommunityForm(false); + setEditingCommunityId(null); // Reset editingCommunityId + // Optionally, update the state locally to reflect the change + setCommunities((prev) => + prev.map((community) => + community.id === editingCommunityId + ? { ...community, ...newCommunity } + : community + ) + ); + } + } else { + // Insert new community (as before) + const { data, error } = await supabase + .from("communities") + .insert([{ + community_name, + community_description, + community_location, + community_category, + community_image, + community_members_count: 0, + community_creation_date: new Date().toISOString(), + is_approved: false + }]); + + if (error) { + toast.error("Failed to create community."); + console.error("Error creating community:", error); + } else { + toast.success("Community created successfully!"); + setShowAddCommunityForm(false); + setNewCommunity({ + community_name: "", + community_description: "", + community_location: "", + community_category: "", + community_image: "", + }); + if (Array.isArray(data)) { + setCommunities((prev) => [...prev, ...data]); + } + } + } + }; + + const handleCancel = () => { + setNewCommunity({ + community_name: "", + community_description: "", + community_location: "", + community_category: "", + community_image: "", + }); + setShowAddCommunityForm(false); // Close the form modal + }; + + const handleDeleteCommunity = async (communityId: string) => { + const confirmation = window.confirm("Are you sure you want to delete this community?"); + if (!confirmation) return; + + try { + // Step 1: Delete all members in the community + const { error: deleteMembersError } = await supabase + .from("community_members") + .delete() + .eq("community_id", communityId); + + if (deleteMembersError) { + toast.error("Failed to delete community members."); + console.error("Error deleting community members:", deleteMembersError); + return; + } + + // Step 2: Delete the community + const { error } = await supabase + .from("communities") + .delete() + .eq("id", communityId); + + if (error) { + toast.error("Failed to delete community."); + console.error("Error deleting community:", error); + } else { + toast.success("Community deleted successfully!"); + setCommunities((prev) => prev.filter((community) => community.id !== communityId)); + } + } catch (error) { + toast.error("An unexpected error occurred."); + console.error("Unexpected error deleting community:", error); + } + }; + + const handleViewEditCommunity = (community: Community) => { + setNewCommunity({ + community_name: community.community_name, + community_description: community.community_description, + community_location: community.community_location, + community_category: community.community_category, + community_image: community.community_image, + }); + setEditingCommunityId(community.id); // Set the community ID being edited + setShowAddCommunityForm(true); // Show the form to edit + }; + + const handleJoinFormChange = (e: React.ChangeEvent) => { + const { name, value } = e.target; + setJoinFormData({ ...joinFormData, [name]: value }); + }; + + const filteredAndSortedCommunities = useMemo(() => { + return communities + .filter((community) => { + const matchesCategory = category ? community.community_category === category : true; + const matchesSearchTerm = + community.community_name.toLowerCase().includes(searchTerm.toLowerCase()) || + community.community_location.toLowerCase().includes(searchTerm.toLowerCase()); + return matchesCategory && matchesSearchTerm; + }) + .sort((a, b) => { + if (sortByLikes === "high") { + return b.community_members_count - a.community_members_count; + } else if (sortByLikes === "low") { + return a.community_members_count - b.community_members_count; + } + return 0; + }); + }, [communities, searchTerm, category, sortByLikes]); + + const indexOfLastItem = currentPage * itemsPerPage; + const indexOfFirstItem = indexOfLastItem - itemsPerPage; + const currentCommunities = filteredAndSortedCommunities.slice(indexOfFirstItem, indexOfLastItem); + + const totalPages = Math.ceil(filteredAndSortedCommunities.length / itemsPerPage); + + if (loading) { + return ; + } + + return ( +
+
+ Explore Communities +
+ +
+ {/* Button to Show Add Community Form */} +
+ +
+ +
+
+
+ setSearchTerm(e.target.value)} + /> +
+ +
+
+ + +
+
+ +
+ {currentCommunities.map((community) => ( + + {/* Trash Icon for Delete */} + + {community.community_name} +

{community.community_name}

+

+ + {community.community_location} +

+
+ +
+
+ ))} +
+ +
+ setCurrentPage(page)} + /> +
+
+ + {/* Add or Edit Community Form Modal */} + {showAddCommunityForm && ( +
+
+

{editingCommunityId ? "Edit Community" : "Add New Community"}

+
+
+ + setNewCommunity({ ...newCommunity, community_name: e.target.value })} + required + /> +
+
+ +