import React, { useState, useRef, useEffect } from 'react'; import { User, Mail, Shield, Bell, Lock, Globe, Camera, ShieldCheck, Key, Smartphone, History, Activity, CheckCircle2, AlertCircle, Copy, LogOut, Eye, Save, X, Edit2, Download } from 'lucide-react'; import useAuthStore from '../../store/authStore'; import useToastStore from '../../store/toastStore'; import { supabase } from "../../lib/supabaseClient"; import BugReportWidget from "../../components/shared/BugReportWidget"; const AdminProfile = () => { const { user, profile: adminProfile } = useAuthStore(); const { showToast } = useToastStore(); const [isEditingProfile, setIsEditingProfile] = useState(false); const [profileForm, setProfileForm] = useState({ name: adminProfile?.full_name || '', email: adminProfile?.email || '', profile_picture: adminProfile?.profile_picture || null }); useEffect(() => { if (adminProfile) { setProfileForm({ name: adminProfile.full_name || '', email: adminProfile.email || '', profile_picture: adminProfile.profile_picture || null }); } }, [adminProfile]); const [isAdmin2FAEnabled, setIsAdmin2FAEnabled] = useState(false); const [showPasswordModal, setShowPasswordModal] = useState(false); const [passwordForm, setPasswordForm] = useState({ newPassword: '', confirmPassword: '' }); const [passwordLoading, setPasswordLoading] = useState(false); const fileInputRef = useRef(null); const [activityLog, setActivityLog] = useState([]); useEffect(() => { const fetchActivity = async () => { if (!adminProfile?.company) return; try { const { data, error } = await supabase .from('tickets') .select('id, subject, status, created_at') .eq('company', adminProfile.company) .order('created_at', { ascending: false }) .limit(5); if (error) throw error; const formatted = (data || []).map(t => ({ id: t.id, action: `Ticket ${t.status?.toUpperCase() || 'UPDATED'}`, target: `#TKT-${t.id.slice(0, 4)}`, timestamp: new Date(t.created_at).toLocaleString(), status: "Success" })); setActivityLog(formatted); } catch (err) { console.error("Failed to fetch activity log:", err); } }; fetchActivity(); }, [adminProfile?.company]); const handleImageUpload = async (e) => { const file = e.target.files?.[0]; if (!file) return; try { const userId = user?.id || adminProfile?.id; const fileExt = file.name.split('.').pop(); const fileName = `${userId}/${Date.now()}.${fileExt}`; const { error: uploadError } = await supabase.storage .from('profile-pics').upload(fileName, file, { upsert: true, contentType: file.type || 'image/jpeg' }); if (uploadError) throw uploadError; const { data } = supabase.storage.from('profile-pics').getPublicUrl(fileName); setProfileForm(prev => ({ ...prev, profile_picture: data?.publicUrl })); await supabase.from('profiles').update({ profile_picture: data?.publicUrl }).eq('id', userId); await useAuthStore.getState().getProfile(user); showToast("Profile picture updated.", "success"); } catch (err) { showToast(`Upload failed: ${err.message}`, "error"); } }; const handleSaveProfile = async () => { try { const { error } = await supabase.from('profiles').update({ full_name: profileForm.name, email: profileForm.email, profile_picture: profileForm.profile_picture }).eq('id', adminProfile.id); if (error) throw error; setIsEditingProfile(false); await useAuthStore.getState().getProfile(useAuthStore.getState().user); showToast("Profile updated successfully.", "success"); } catch (err) { showToast("Save failed: " + err.message, "error"); } }; const handleDownloadArchive = () => { const data = { admin_id: adminProfile.id, email: adminProfile.email, role: adminProfile.role, activity_logs: activityLog }; const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `admin_archive_${adminProfile.id}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }; const handleLogout = async () => { await useAuthStore.getState().logout(); }; const handlePasswordChange = async () => { if (!passwordForm.newPassword || passwordForm.newPassword.length < 6) { showToast("Password must be at least 6 characters.", "error"); return; } if (passwordForm.newPassword !== passwordForm.confirmPassword) { showToast("Passwords do not match", "error"); return; } setPasswordLoading(true); try { const { error } = await supabase.auth.updateUser({ password: passwordForm.newPassword }); if (error) throw error; showToast("Password updated successfully", "success"); setShowPasswordModal(false); setPasswordForm({ newPassword: '', confirmPassword: '' }); } catch (err) { showToast("Failed: " + err.message, "error"); } finally { setPasswordLoading(false); } }; const cs = { card: { background: '#fff', borderRadius: '24px', border: '1px solid #f0fdf4', boxShadow: '0 4px 24px rgba(0,0,0,0.06)', padding: '36px 40px' } }; return (
{/* 1. Profile Hero */}
{isEditingProfile && profileForm.profile_picture ? ( Profile ) : adminProfile?.profile_picture ? ( Profile ) : ( isEditingProfile ? (profileForm.name?.charAt(0) || '?') : (adminProfile?.full_name?.charAt(0) || '?') )}
{isEditingProfile && ( <> )}
{!isEditingProfile ? ( <>

{adminProfile?.full_name || 'Admin Agent'} {adminProfile?.role === 'master_admin' ? 'Master Admin' : 'Admin'}

User ID: {adminProfile?.id}

) : (
setProfileForm({ ...profileForm, name: e.target.value })} className="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-lg font-bold focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 transition-all outline-none" placeholder="Admin Name" /> setProfileForm({ ...profileForm, email: e.target.value })} className="w-full bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-sm font-medium focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 transition-all outline-none" placeholder="Admin Email" />
)}
{!isEditingProfile ? ( ) : (
)}
{[ { label: 'Email Address', val: adminProfile?.email }, { label: 'Company', val: adminProfile?.company || 'Universal Hub' }, { label: 'Last Login', val: user?.last_sign_in_at ? new Date(user.last_sign_in_at).toLocaleString() : 'Just Now' } ].map((m, i) => (
{m.val}
))}
{/* 2. Security */}

SECURITY SETTINGS

{/* Password */}

Password

Update your administrative password to keep your account secure.

{/* 2FA */}

Two-Factor Authentication (2FA)

Enforce extra verification for secure admin actions.

{/* Bug Report */}

Bug Report

Submit a detailed system bug report with attachments.

Report Bug } />
{/* 3. Activity Audit */}

ACTIVITY LOG

{['Action', 'Target', 'Time', 'Status'].map((h, i) => ( ))} {activityLog.map((log) => ( ))}
{h}
{log.action} {log.target} {log.timestamp} {log.status}

End of Activity Log

{/* Password Modal */} {showPasswordModal && (

Update Password

{[{ label: 'New Password', key: 'newPassword', ph: 'Enter new password' }, { label: 'Confirm Password', key: 'confirmPassword', ph: 'Confirm password' }].map((f, i) => (
setPasswordForm({ ...passwordForm, [f.key]: e.target.value })} />
))}
)}
); }; export default AdminProfile;