"use client"; import React, { useEffect, useState, useCallback } from "react"; import { useRouter } from "next/navigation"; import axios from "axios"; import { ApiServerBaseUrl } from "@/utils/baseurl.utils"; import { getSocialAuthStatus } from "@/utils/commonFunction.utils"; import { Instagram, CheckCircle, XCircle, Link2, Users, Image as ImageIcon, Globe, BarChart3, Shield, Zap, ArrowRight, ExternalLink, RefreshCw } from "lucide-react"; import Link from "next/link"; interface Channel { _id: string; name: string; id?: string; has_linked_account: boolean; } const SocialMediaChannels = () => { const router = useRouter(); const [channels, setChannels] = useState([]); const [loading, setLoading] = useState(true); const [openModal, setOpenModal] = useState(false); const [successMsg, setSuccessMsg] = useState(""); const [connectedChannel, setConnectedChannel] = useState(null); const [accountData, setAccountData] = useState(null); const [refreshing, setRefreshing] = useState(false); // --------------------------------------------- // VALIDATE USER ACCESS // --------------------------------------------- useEffect(() => { async function validate() { const userEmail = localStorage.getItem("user_email"); if (!userEmail) { router.push("/social-media-connect"); return; } const storedUser = localStorage.getItem("userDetails"); if (!storedUser) { router.push("/social-media-connect"); return; } const user = JSON.parse(storedUser); const role = user?.role; if (role === "customer") { const session = localStorage.getItem("payment_session"); if (!session) { router.push("/pricing"); return; } } const res = await getSocialAuthStatus(userEmail); if (!res?.connected) { router.push("/social-media-connect"); return; } } validate(); }, [router]); // --------------------------------------------- // FETCH CHANNELS // --------------------------------------------- const loadChannels = useCallback(async () => { try { const user = localStorage.getItem("user_email"); const res = await axios.get(`${ApiServerBaseUrl}/social/channels?userId=${user}`); const data: Channel[] = res.data || []; setChannels(data); } catch (err) { console.error("Failed to load channels", err); } finally { setLoading(false); } }, []); // --------------------------------------------- // FETCH ACCOUNT DETAILS // --------------------------------------------- const loadAccountDetails = useCallback(async () => { try { const user = localStorage.getItem("user_email"); const connected = localStorage.getItem("connectedChannel"); if (!user || !connected) return; const res = await axios.get(`${ApiServerBaseUrl}/social/account?userId=${user}`); setAccountData(res.data || null); } catch (err: any) { if (err.response?.data?.error !== "Connect a channel first") { console.error("Failed to load account details", err); } setAccountData(null); } }, []); useEffect(() => { loadChannels(); const saved = localStorage.getItem("connectedChannel"); if (saved) { setConnectedChannel(saved); loadAccountDetails(); } }, [loadChannels, loadAccountDetails]); // --------------------------------------------- // CONNECT CHANNEL // --------------------------------------------- const handleConnectChannel = async (channelId: string, channelName: string) => { try { const user = localStorage.getItem("user_email"); const res = await axios.post( `${ApiServerBaseUrl}/social/connect?userId=${user}`, { channel_id: channelId } ); const savedId = res.data?.data?.channel_id || channelId; localStorage.setItem("connectedChannel", savedId); setConnectedChannel(savedId); setSuccessMsg(`${channelName} connected successfully!`); setOpenModal(false); await loadAccountDetails(); } catch (err: any) { setSuccessMsg(err.response?.data?.error || `Failed to connect ${channelName}`); } }; // --------------------------------------------- // REMOVE CHANNEL // --------------------------------------------- const handleRemoveChannel = () => { localStorage.removeItem("connectedChannel"); setConnectedChannel(null); setAccountData(null); setSuccessMsg("Channel removed successfully!"); }; // --------------------------------------------- // REFRESH DATA // --------------------------------------------- const handleRefresh = async () => { setRefreshing(true); await loadAccountDetails(); setTimeout(() => setRefreshing(false), 1000); }; return (
{/* Floating background bubbles */}
{/* Success Message */} {successMsg && (
{successMsg.includes("success") ? ( ) : ( )} {successMsg}
)} {/* Main Container */}
{/* Header */}
{connectedChannel && (
)}

Instagram Channels

Manage and connect your Instagram accounts

{/* Action Buttons */}
{connectedChannel && accountData && ( )} {!connectedChannel && ( )}
{/* Main Content */} {connectedChannel && accountData ? (
{/* Left Column - Profile */}
{/* Profile Card */}
{/* Profile Image */}
{accountData.username
{/* Profile Info */}

{accountData.username}

{accountData.name && (

{accountData.name}

)}
Connected
{/* Stats */}
{accountData.media_count}
Posts
{accountData.followers_count}
Followers
{accountData.follows_count}
Following
{/* Bio */} {accountData.biography && (

Bio

{accountData.biography}

)} {/* Website */} {accountData.website && ( {accountData.website} )}
{/* Quick Actions */}

Quick Actions

Media Library

View and manage your posts

Comments

Manage comments & engagement

Insights

View performance analytics

{/* Right Column - Settings & Info */}
{/* Connection Status */}

Channel Status

Instagram Account
Connected
Media Access ✓ Available
Comment Access ✓ Available
Insights Access ✓ Available

This will revoke Social Buddy's access to this account

{/* Info Card */}

Channel Information

  • All data is synced securely
  • Manual management only
  • Real-time data updates
) : ( /* No Channel Connected State */

No Channel Connected

Connect an Instagram account to access media management, insights, and comment tools.

)}
{/* Channel Selection Modal */} {openModal && (
{/* Modal Header */}

Connect Instagram Channel

Select an Instagram account to connect

{/* Modal Content */}
{loading ? (
) : channels.length === 0 ? (

No Instagram channels available

Make sure your Instagram account is linked to Facebook

) : (
{channels.map((channel) => (

{channel.name}

{channel.has_linked_account ? ( <> Ready to connect ) : ( <> Requires authorization )}

{channel.has_linked_account ? "Connect this Instagram account to access media, insights, and comments." : "This account needs to be authorized through Facebook first." }

))}
)}
{/* Modal Footer */}

{channels.length} channel{channels.length !== 1 ? 's' : ''} available

)} {/* Animation Styles */}
); }; export default SocialMediaChannels;