Files
pwa/src/pages/Auth/Login/LoginPage.tsx
T
2026-01-05 14:59:18 +03:30

391 lines
14 KiB
TypeScript

import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Card, CardContent, CardDescription, 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 { useAuth } from '@/hooks/useAuth';
import { useTheme } from '@/hooks/useTheme';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Mail, Phone, LogIn, Moon, Sun } from 'lucide-react';
export default function LoginPage() {
const navigate = useNavigate();
const { signIn, signInWithGoogle, signInWithPhone, verifyOTP } = useAuth();
const { toggleTheme, isDark } = useTheme();
const { toast } = useToast();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [phone, setPhone] = useState('');
const [otp, setOtp] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [otpSent, setOtpSent] = useState(false);
const [authMethod, setAuthMethod] = useState<'email' | 'phone' | 'google'>('email');
const handleEmailLogin = async (e: React.FormEvent) => {
e.preventDefault();
if (!email || !password) {
toast({
title: 'خطا',
description: 'لطفا ایمیل و رمز عبور را وارد کنید',
variant: 'destructive'
});
return;
}
setIsLoading(true);
try {
await signIn(email, password);
toast({
title: 'موفق',
description: 'با موفقیت وارد شدید'
});
navigate('/account');
} catch (error: any) {
console.error('Login error:', error);
let errorMessage = 'خطا در ورود';
if (error) {
const errorMsg = error.message || error.error?.message || String(error);
if (errorMsg.includes('Invalid login credentials') || errorMsg.includes('invalid_credentials')) {
errorMessage = 'ایمیل یا رمز عبور اشتباه است. لطفا دوباره تلاش کنید یا ثبت نام کنید.';
} else if (errorMsg.includes('Email not confirmed') || errorMsg.includes('email_not_confirmed')) {
errorMessage = 'لطفا ابتدا ایمیل خود را تأیید کنید.';
} else if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg || 'خطا در ورود. لطفا دوباره تلاش کنید.';
}
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
} finally {
setIsLoading(false);
}
};
const handleGoogleLogin = async () => {
setIsLoading(true);
try {
await signInWithGoogle();
// Redirect happens automatically
} catch (error: any) {
console.error('Google login error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'خطا در ورود با گوگل';
toast({
title: 'خطا',
description: errorMsg.includes('Supabase not configured')
? 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.'
: errorMsg,
variant: 'destructive'
});
setIsLoading(false);
}
};
const handleSendOTP = async (e: React.FormEvent) => {
e.preventDefault();
if (!phone) {
toast({
title: 'خطا',
description: 'لطفا شماره تلفن را وارد کنید',
variant: 'destructive'
});
return;
}
setIsLoading(true);
try {
await signInWithPhone(phone);
setOtpSent(true);
toast({
title: 'موفق',
description: 'کد تأیید ارسال شد'
});
} catch (error: any) {
console.error('Phone OTP error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'خطا در ارسال کد';
let errorMessage = 'خطا در ارسال کد';
if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Invalid phone number') || errorMsg.includes('invalid_phone')) {
errorMessage = 'شماره تلفن نامعتبر است. لطفا شماره را با فرمت صحیح وارد کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg;
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
} finally {
setIsLoading(false);
}
};
const handleVerifyOTP = async (e: React.FormEvent) => {
e.preventDefault();
if (!otp) {
toast({
title: 'خطا',
description: 'لطفا کد تأیید را وارد کنید',
variant: 'destructive'
});
return;
}
setIsLoading(true);
try {
await verifyOTP(phone, otp);
toast({
title: 'موفق',
description: 'با موفقیت وارد شدید'
});
navigate('/account');
} catch (error: any) {
console.error('OTP verification error:', error);
const errorMsg = error?.message || error?.error?.message || String(error) || 'کد تأیید نامعتبر است';
let errorMessage = 'کد تأیید نامعتبر است';
if (errorMsg.includes('Supabase not configured')) {
errorMessage = 'Supabase تنظیم نشده است. لطفا فایل .env را بررسی کنید.';
} else if (errorMsg.includes('Invalid OTP') || errorMsg.includes('invalid_token')) {
errorMessage = 'کد تأیید نامعتبر است. لطفا دوباره تلاش کنید.';
} else if (errorMsg.includes('expired')) {
errorMessage = 'کد تأیید منقضی شده است. لطفا کد جدید درخواست کنید.';
} else if (errorMsg.includes('Network') || errorMsg.includes('fetch')) {
errorMessage = 'خطا در اتصال به سرور. لطفا اتصال اینترنت خود را بررسی کنید.';
} else {
errorMessage = errorMsg;
}
toast({
title: 'خطا',
description: errorMessage,
variant: 'destructive'
});
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted p-4 relative">
{/* Dark Mode Toggle Button */}
<button
onClick={toggleTheme}
className="absolute top-4 left-4 p-2 rounded-lg bg-background/80 backdrop-blur-sm border border-input hover:bg-accent transition-colors"
aria-label={isDark ? 'تغییر به حالت روشن' : 'تغییر به حالت تاریک'}
>
{isDark ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)}
</button>
<Card className="w-full max-w-sm">
<CardHeader className="space-y-1">
<div className="flex justify-center mb-4">
<LogIn className="h-12 w-12 text-primary" />
</div>
<CardTitle className="text-2xl text-center">ورود</CardTitle>
<CardDescription className="text-center">
به حساب کاربری خود وارد شوید
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Auth Method Selector */}
<div className="flex gap-2">
<Button
type="button"
variant={authMethod === 'email' ? 'default' : 'outline'}
className="flex-1"
onClick={() => {
setAuthMethod('email');
setOtpSent(false);
}}
>
<Mail className="ml-2 h-4 w-4" />
ایمیل
</Button>
<Button
type="button"
variant={authMethod === 'phone' ? 'default' : 'outline'}
className="flex-1"
onClick={() => {
setAuthMethod('phone');
setOtpSent(false);
}}
>
<Phone className="ml-2 h-4 w-4" />
تلفن
</Button>
</div>
{/* Email Login */}
{authMethod === 'email' && (
<form onSubmit={handleEmailLogin} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">ایمیل</Label>
<Input
id="email"
type="email"
placeholder="example@email.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLoading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">رمز عبور</Label>
<Input
id="password"
type="password"
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={isLoading}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ورود...
</>
) : (
'ورود'
)}
</Button>
</form>
)}
{/* Phone OTP Login */}
{authMethod === 'phone' && (
<>
{!otpSent ? (
<form onSubmit={handleSendOTP} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="phone">شماره تلفن</Label>
<Input
id="phone"
type="tel"
placeholder="09123456789"
value={phone}
onChange={(e) => setPhone(e.target.value)}
disabled={isLoading}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ارسال...
</>
) : (
'ارسال کد تأیید'
)}
</Button>
</form>
) : (
<form onSubmit={handleVerifyOTP} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="otp">کد تأیید</Label>
<Input
id="otp"
type="text"
placeholder="123456"
value={otp}
onChange={(e) => setOtp(e.target.value)}
disabled={isLoading}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال تأیید...
</>
) : (
'تأیید کد'
)}
</Button>
<Button
type="button"
variant="ghost"
className="w-full"
onClick={() => setOtpSent(false)}
disabled={isLoading}
>
تغییر شماره
</Button>
</form>
)}
</>
)}
{/* Google Login */}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t" />
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-card px-2 text-muted-foreground">یا</span>
</div>
</div>
<Button
type="button"
variant="outline"
className="w-full"
onClick={handleGoogleLogin}
disabled={isLoading}
>
<svg className="ml-2 h-4 w-4" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
/>
<path
fill="currentColor"
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
/>
<path
fill="currentColor"
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
/>
<path
fill="currentColor"
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
/>
</svg>
ورود با گوگل
</Button>
<div className="text-center text-sm">
حساب کاربری ندارید؟{' '}
<Link to="/signup" className="text-primary hover:underline">
ثبت نام
</Link>
</div>
</CardContent>
</Card>
</div>
);
}