import { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Button } from '../ui/button'; import { Input } from '../ui/input'; import { Label } from '../ui/label'; import { Textarea } from '../ui/textarea'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'; import { Alert, AlertDescription } from '../ui/alert'; import { CheckCircle2, User, DollarSign, Award, FileText } from 'lucide-react'; import { useAuth } from '../../lib/authContext'; import { useLanguage } from '../../lib/languageContext'; import { LanguageSwitcher } from '../LanguageSwitcher'; import { getApiBaseUrl } from '../../lib/api/config'; export function CompleteProfile() { const { user, updateProfile } = useAuth(); const { language } = useLanguage(); const navigate = useNavigate(); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [submitted, setSubmitted] = useState(false); const parseErrorResponse = async (res: Response) => { let errorMsg = language === 'ar' ? 'فشل الإرسال' : 'Submission failed'; try { const json = await res.clone().json(); if (json?.message) return json.message; if (json?.error) return json.error; if (Array.isArray(json?.errors) && json.errors.length > 0) { return json.errors.map((err: any) => err.defaultMessage || err.message || String(err)).join(', '); } if (json?.errors) return JSON.stringify(json.errors); } catch { // ignore invalid JSON } try { const text = await res.text(); if (text) return text; } catch { // ignore text read errors } return errorMsg; }; // Student fields const [quranLevel, setQuranLevel] = useState(''); const [preferredLanguage, setPreferredLanguage] = useState(''); const [preferredAccent, setPreferredAccent] = useState(''); const [profilePhotoUrl, setProfilePhotoUrl] = useState(''); // Sheikh fields const [bio, setBio] = useState(''); const [specialization, setSpecialization] = useState(''); const [yearsOfExperience, setYearsOfExperience] = useState(''); const [hourlyRate, setHourlyRate] = useState(''); const [certificateUrl, setCertificateUrl] = useState(''); const [sheikhProfilePhotoUrl, setSheikhProfilePhotoUrl] = useState(''); // const t = translations[language].auth; const isRTL = language === 'ar'; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setError(null); try { const token = localStorage.getItem('authToken'); if (!token) { throw new Error( language === 'ar' ? 'لا يوجد رمز مصادقة' : 'No authentication token found' ); } const BASE_URL = getApiBaseUrl(); if (user?.role === 'student') { // Validate student fields if (!quranLevel || !preferredLanguage || !preferredAccent) { setError( language === 'ar' ? 'يرجى ملء جميع الحقول المطلوبة' : 'Please fill in all required fields' ); setLoading(false); return; } const payload = { quranLevel, preferredLanguage, preferredAccent, profilePhotoUrl: profilePhotoUrl || '' }; const res = await fetch(`${BASE_URL}/api/student/profile/complete`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(payload), }); if (!res.ok) { const errorMsg = await parseErrorResponse(res); throw new Error(errorMsg); } // Update context and navigate updateProfile({ profileCompleted: true }); navigate('/student/dashboard'); } else if (user?.role === 'sheikh') { // Validate sheikh fields if (!bio || !specialization || !yearsOfExperience || !hourlyRate) { setError( language === 'ar' ? 'يرجى ملء جميع الحقول المطلوبة (السيرة الذاتية، التخصص، سنوات الخبرة، السعر بالساعة)' : 'Please fill in all required fields (Bio, Specialization, Years of Experience, Hourly Rate)' ); setLoading(false); return; } const payload = { bio, specialization, yearsOfExperience: parseInt(yearsOfExperience), hourlyRate: parseFloat(hourlyRate), certificateUrl: certificateUrl || '', profilePhotoUrl: sheikhProfilePhotoUrl || '' }; const res = await fetch(`${BASE_URL}/api/sheikh/profile/complete`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(payload), }); if (!res.ok) { const errorMsg = await parseErrorResponse(res); throw new Error(errorMsg); } // Show success screen for sheikh setSubmitted(true); } } catch (err: any) { console.error('Profile submission error:', err); setError(err.message || ( language === 'ar' ? 'حدث خطأ أثناء الإرسال. حاول مرة أخرى.' : 'Error submitting profile. Please try again.' )); } finally { setLoading(false); } }; // Success screen for sheikh if (user?.role === 'sheikh' && submitted) { return (
{language === 'ar' ? 'تم إرسال الطلب بنجاح!' : 'Application Submitted Successfully!'} {language === 'ar' ? 'ملفك الشخصي قيد المراجعة من قبل فريق الإدارة' : 'Your profile is under review by our admin team'}
{language === 'ar' ? 'تم إرسال طلبك وهو حاليًا في حالة الموافقة المعلقة. سيقوم فريق الإدارة بمراجعة بياناتك خلال 3-5 أيام عمل. سوف تتلقى إشعارًا عبر البريد الإلكتروني بمجرد الموافقة على طلبك.' : 'Your application has been submitted and is currently in PENDING approval status. Our admin team will review your credentials within 3-5 business days. You will receive an email notification once your application is approved.'}
); } // Main form return (
{language === 'ar' ? 'أكمل ملفك الشخصي' : 'Complete Your Profile'} {user?.role === 'student' ? (language === 'ar' ? 'أخبرنا عن نفسك لتخصيص تجربة التعلم الخاصة بك' : 'Tell us about yourself to personalize your learning experience') : (language === 'ar' ? 'قدم بياناتك وقم برفع الملفات المطلوبة لبدء التدريس' : 'Provide your credentials and upload required files to start teaching')}
{/* STUDENT FIELDS */} {user?.role === 'student' ? ( <> {/* Quran Level */}
{/* Preferred Language */}
{/* Preferred Accent */}
{/* Profile Photo URL */}
setProfilePhotoUrl(e.target.value)} className={isRTL ? 'pr-10 text-right' : 'pl-10'} dir="ltr" />
) : ( /* SHEIKH FIELDS */ <> {/* Specialization */}
setSpecialization(e.target.value)} className={isRTL ? 'pr-10 text-right' : 'pl-10'} required />
{/* Years of Experience */}
setYearsOfExperience(e.target.value)} className={isRTL ? 'text-right' : ''} required />
{/* Hourly Rate */}
setHourlyRate(e.target.value)} className={isRTL ? 'pr-10 text-right' : 'pl-10'} dir="ltr" required />
{/* Bio */}