import React, { useState, useEffect } from "react"; import { supabase } from "../../lib/supabaseClient"; import useAuthStore from "../../store/authStore"; import useToastStore from "../../store/toastStore"; import { format } from "date-fns"; import { User, Mail, Phone, Briefcase, Building2, Globe, Users, Check, X, MoreVertical, ExternalLink, Calendar, Loader2, Info } from "lucide-react"; import { motion, AnimatePresence } from "framer-motion"; function PendingAdminRequests() { const [requests, setRequests] = useState([]); const [loading, setLoading] = useState(true); const [actionLoading, setActionLoading] = useState(null); // id of request being processed const { user: masterAdmin } = useAuthStore(); const { showToast } = useToastStore(); useEffect(() => { fetchRequests(); // Real-time subscription const channel = supabase .channel('admin_requests_changes') .on( 'postgres_changes', { event: '*', schema: 'public', table: 'admin_requests' }, () => fetchRequests() ) .subscribe(); return () => supabase.removeChannel(channel); }, []); const fetchRequests = async () => { setLoading(true); try { // Join with profiles to get admin details const { data, error } = await supabase .from('admin_requests') .select(` *, admin:profiles!admin_id (*) `) .eq('status', 'pending') .order('created_at', { ascending: false }); if (error) throw error; setRequests(data || []); } catch (err) { console.error("Error fetching admin requests:", err); } finally { setLoading(false); } }; const handleApprove = async (request) => { setActionLoading(request.id); try { // 1. Create or Resolve Company let company; const { data: existingCompany } = await supabase .from('companies') .select('*') .eq('name', request.admin.company) .single(); if (existingCompany) { console.log("Company already exists, reusing:", existingCompany.id); company = existingCompany; } else { const { data: newCompany, error: companyErr } = await supabase .from('companies') .insert([{ name: request.admin.company, status: 'active', admin_id: request.admin_id }]) .select() .single(); if (companyErr) throw companyErr; company = newCompany; } // 2. Update Admin Profile const { error: profileErr } = await supabase .from('profiles') .update({ status: 'active', company_id: company.id }) .eq('id', request.admin_id); if (profileErr) throw profileErr; // 3. Mark Request as Approved const { error: requestErr } = await supabase .from('admin_requests') .update({ status: 'approved', reviewed_by: masterAdmin.id, reviewed_at: new Date().toISOString() }) .eq('id', request.id); if (requestErr) throw requestErr; showToast(`Company protocol activated: ${request.admin.company} is now live.`, "success"); } catch (err) { console.error("Approval flow failed:", err); showToast("Approval failed: " + err.message, "error"); } finally { setActionLoading(null); } }; const handleReject = async (request) => { const reason = window.prompt("Reason for rejection (optional):"); if (reason === null) return; // User cancelled setActionLoading(request.id); try { // 1. Update Profile const { error: profileErr } = await supabase .from('profiles') .update({ status: 'rejected' }) .eq('id', request.admin_id); if (profileErr) throw profileErr; // 2. Mark Request as Rejected const { error: requestErr } = await supabase .from('admin_requests') .update({ status: 'rejected', reviewed_by: masterAdmin.id, reviewed_at: new Date().toISOString() }) .eq('id', request.id); if (requestErr) throw requestErr; showToast(`Administrator request for ${request.admin.full_name} rejected.`, "warning"); } catch (err) { console.error("Rejection flow failed:", err); showToast("Rejection failed: " + err.message, "error"); } finally { setActionLoading(null); } }; if (loading) { return (

Loading registration queue...

); } return (

Pending Admin Requests

Review and approve new company registration requests.

{requests.length} pending Review
{requests.length === 0 ? (

Queue is clear! No pending requests.

) : (
{requests.map((request) => ( {actionLoading === request.id && (
)}
{request.admin.full_name.charAt(0)}

{request.admin.full_name}

{request.admin.job_title || "Company Admin"}
Pending Review
{format(new Date(request.created_at), 'MMM d, yyyy')}
{request.admin.email}
{request.admin.phone || "No phone provided"}
{request.admin.company || "Unnamed Company"}
{request.admin.company_size || "Unknown Size"} • {request.admin.industry || "General Industry"}
{request.admin.website && ( {request.admin.website.replace(/^https?:\/\//, '')} )}
))}
)}
); } export default PendingAdminRequests;