'use client' import { useState, useEffect, useCallback } from 'react' import { useSession } from 'next-auth/react' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Badge } from '@/components/ui/badge' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { User, Mail, Phone, MapPin, Calendar, Shield, Key, Save, Eye, EyeOff } from 'lucide-react' import { motion } from 'framer-motion' import { toast } from 'sonner' import { DashboardHeader } from '@/components/dashboard/DashboardHeader' interface UserProfile { id: string name: string email: string phone?: string address?: string joinedAt: string role: string referralCode: string isActive: boolean } interface PasswordData { currentPassword: string newPassword: string confirmPassword: string } export default function ProfilePage() { const { data: session } = useSession() const [profile, setProfile] = useState(null) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [passwordData, setPasswordData] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' }) const [showPasswords, setShowPasswords] = useState({ current: false, new: false, confirm: false }) const fetchProfile = useCallback(async () => { try { const response = await fetch('/api/user/profile') if (!response.ok) { throw new Error('Failed to fetch profile') } const data = await response.json() // Transform the data to match our interface const transformedProfile: UserProfile = { id: data.id, name: data.name || session?.user?.name || '', email: data.email || session?.user?.email || '', phone: data.phone || '', address: data.address || '', joinedAt: data.createdAt || new Date().toISOString(), role: session?.user?.role || 'CUSTOMER', referralCode: session?.user?.referralCode || '', isActive: data.isActive !== undefined ? data.isActive : true } setProfile(transformedProfile) } catch (error) { console.error('Error fetching profile:', error) // Fallback to session data if API fails if (session?.user) { const fallbackProfile: UserProfile = { id: session.user.id || '', name: session.user.name || '', email: session.user.email || '', phone: '', address: '', joinedAt: new Date().toISOString(), role: session.user.role || 'CUSTOMER', referralCode: session.user.referralCode || '', isActive: true } setProfile(fallbackProfile) } else { toast.error('Failed to load profile') } } finally { setLoading(false) } }, [session]) useEffect(() => { if (session) { fetchProfile() } else { setLoading(false) } }, [fetchProfile, session]) const handleProfileUpdate = async (e: React.FormEvent) => { e.preventDefault() if (!profile) return setSaving(true) try { const response = await fetch('/api/user/profile', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: profile.name, phone: profile.phone, address: profile.address }) }) if (!response.ok) { const errorData = await response.json() throw new Error(errorData.error || 'Failed to update profile') } const updatedData = await response.json() setProfile(prev => prev ? { ...prev, ...updatedData } : null) toast.success('Profile updated successfully') } catch (error) { console.error('Error updating profile:', error) toast.error('Failed to update profile') } finally { setSaving(false) } } const handlePasswordChange = async (e: React.FormEvent) => { e.preventDefault() if (passwordData.newPassword !== passwordData.confirmPassword) { toast.error('New passwords do not match') return } if (passwordData.newPassword.length < 6) { toast.error('Password must be at least 6 characters long') return } setSaving(true) try { const response = await fetch('/api/user/change-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(passwordData) }) if (!response.ok) throw new Error('Failed to change password') toast.success('Password changed successfully') setPasswordData({ currentPassword: '', newPassword: '', confirmPassword: '' }) } catch (error) { toast.error('Failed to change password') } finally { setSaving(false) } } const copyReferralCode = () => { if (profile?.referralCode) { navigator.clipboard.writeText(profile.referralCode) toast.success('Referral code copied to clipboard!') } } if (loading) { return (
) } if (!session || !profile) { return (

Profile not found

Please try refreshing the page or signing in again.

) } return (
{/* Header */} } /> {/* Profile Overview */}

{profile.name || 'User'}

{profile.email}

{profile.isActive ? 'Active' : 'Inactive'} {profile.role}
Member since {profile.joinedAt ? new Date(profile.joinedAt).toLocaleDateString() : 'Invalid Date'}

Referral Code

{profile.referralCode || 'N/A'}
{/* Profile Management */} Personal Information Security Settings Personal Information
setProfile(prev => prev ? {...prev, name: e.target.value} : null)} className="pl-10" placeholder="Enter your full name" />
setProfile(prev => prev ? {...prev, phone: e.target.value} : null)} className="pl-10" placeholder="Enter your phone number" />