import React, { useState ,useContext } from 'react'; import { TextField, Button, Typography, Stack, Box, IconButton, InputAdornment } from '@mui/material'; import { useTheme } from '@mui/material/styles'; import VisibilityOffOutlinedIcon from '@mui/icons-material/VisibilityOffOutlined'; import { VisibilityOutlined } from '@mui/icons-material'; import SidePanel from './SidePanel'; import { Link, useNavigate } from 'react-router-dom'; import authService from '../../../services/authService'; import { UserContext } from '../../../contexts/UserContext'; // import { useGoogleRegister } from '@react-oauth/google'; const generateStrongPassword = () => { const length = 12; const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"; let password = ""; for (let i = 0, n = charset.length; i < length; ++i) { password += charset.charAt(Math.floor(Math.random() * n)); } return password; }; const Register = () => { const theme = useTheme(); const navigate = useNavigate(); const [showPassword, setShowPassword] = useState(false); const [showConfirmPassword, setShowConfirmPassword] = useState(false); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [successMessage, setSuccessMessage] = useState(''); const [snackbarOpen, setSnackbarOpen] = useState(false); const { setUser } = useContext(UserContext); // تفعيل/تعطيل إظهار كلمة السر const handleTogglePassword = () => { setShowPassword((prev) => !prev); }; const handleToggleConfirmPassword = () => { setShowConfirmPassword((prev) => !prev); }; const handleRegister = async () => { setLoading(true); setError(''); setSuccessMessage(''); const result = await authService.register(email, password, confirmPassword); if (!result.success) { if (result.errors) { const firstError = Object.values(result.errors)[0][0]; setError(firstError); } else if (result.message && result.message.includes('Duplicate entry')) { setError('The email has already been taken.'); } else { setError(result.message || 'Registration failed'); } setLoading(false); return; } // تسجيل ناجح localStorage.setItem('token', result.data.token); localStorage.setItem('refresh_token', result.data.refresh_token); // ✅ تحديث الـ User Context مباشرة بعد التسجيل setUser({ email: email, token: result.data.token, refresh_token: result.data.refresh_token, adminData: result.data.Admin || null, }); setTimeout(() => { navigate('/restaurant', { replace: true }); setLoading(false); }, 500); }; const handleGoogleSuccess = async (tokenResponse) => { try { const res = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: `Bearer ${tokenResponse.access_token}`, }, }); const userInfo = await res.json(); console.log('Google User Info:', userInfo); if (userInfo.email) { const generatedPassword = generateStrongPassword(); // كلمة مرور مقترحة setEmail(userInfo.email); setPassword(generatedPassword); setConfirmPassword(generatedPassword); setError(''); setTimeout(() => { setSuccessMessage(''); }, 5000); } else { setError('Google Register failed: No email found'); } } catch (e) { console.error('Google Register failed:', e); setError('Google Register failed'); } }; const handleGoogleError = () => { setError('Google Register failed'); }; const handleSnackbarClose = (event, reason) => { if (reason === 'clickaway') { return; } setSnackbarOpen(false); }; // // تهيئة تسجيل الدخول عبر جوجل باستخدام useGoogleRegister // const RegisterWithGoogle = useGoogleRegister({ // onSuccess: handleGoogleSuccess, // onError: handleGoogleError, // }); return ( {/* logo */} logo Register Please fill out the registration form with accurate information to create your account successfully. {/* حقل الايميل */} Email setEmail(e.target.value)} sx={{ '& input': { fontWeight: 500, fontSize: '15px' }, '& input::placeholder': { color: '#969BA7' }, '& .MuiOutlinedInput-root': { borderRadius: '10px', transition: '0.3s', '&.Mui-focused fieldset': { borderColor: theme.palette.primary.main, boxShadow: '0 0 0 2px rgba(255, 145, 77, 0.2)', }, }, '& .MuiOutlinedInput-root.Mui-focused': { borderColor: '#3f51b5', boxShadow: '0 0 0 2px rgba(63,81,181,0.1)', }, }} /> {/* حقل كلمة المرور */} Password setPassword(e.target.value)} sx={{ '& input': { fontWeight: 500, fontSize: '15px' }, '& input::placeholder': { color: '#969BA7' }, '& .MuiOutlinedInput-root': { borderRadius: '10px', transition: '0.3s', '&.Mui-focused fieldset': { borderColor: theme.palette.primary.main, boxShadow: '0 0 0 2px rgba(255, 145, 77, 0.2)', }, }, '& .MuiOutlinedInput-root.Mui-focused': { borderColor: '#3f51b5', boxShadow: '0 0 0 2px rgba(63,81,181,0.1)', }, '& input::-ms-reveal, & input::-ms-clear': { display: 'none', }, }} InputProps={{ endAdornment: ( {showPassword ? : } ), }} /> {/* حقل التاكيد لكلمة المرور */} Confirm Password setConfirmPassword(e.target.value)} sx={{ '& input': { fontWeight: 500, fontSize: '15px' }, '& input::placeholder': { color: '#969BA7' }, '& .MuiOutlinedInput-root': { borderRadius: '10px', transition: '0.3s', '&.Mui-focused fieldset': { borderColor: '#FF914D', boxShadow: '0 0 0 2px rgba(255, 145, 77, 0.2)', }, }, '& .MuiOutlinedInput-root.Mui-focused': { borderColor: '#3f51b5', boxShadow: '0 0 0 2px rgba(63,81,181,0.1)', }, '& input::-ms-reveal, & input::-ms-clear': { display: 'none', }, }} InputProps={{ endAdornment: ( {showConfirmPassword ? : } ), }} /> {/* Error & Success Message */} {error && ( {error} )} {successMessage && ( {successMessage} )} {/* زر التسجيل */} {/* Divider */} Or {/* زر التسجيل عبر جوجل */} {/* */} {/* زر فيسبوك - فقط للعرض (لم تُضاف وظيفة) */} {/* */} Already have an account?{' '} Login By logging in, I agree to the{' '} window.open('/terms', 'TermsOfService')} > Terms of Service {' '} and{' '} window.open('/privacy', 'PrivacyPolicy')} > Privacy Policy . ); }; export default Register;