import { useEffect, useState } from 'react';
import GuestLayout from '@/Layouts/GuestLayout';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Checkbox } from '@/Components/ui/checkbox';
import { 
    Card, 
    CardContent, 
    CardDescription, 
    CardHeader, 
    CardTitle, 
    CardFooter 
} from '@/Components/ui/card';
import { User, Lock, Loader2, ArrowRight, Eye, EyeOff, ArrowLeft } from 'lucide-react';
import { toast } from 'sonner';
import useTranslation from '@/hooks/useTranslation'; 

export default function Login({ status, canResetPassword }) {
    const [showPassword, setShowPassword] = useState(false);
    const { t } = useTranslation(); 
    
    const { registration_enabled, dir } = usePage().props; 
    const isRtl = dir === 'rtl';

    const { data, setData, post, processing, errors, reset } = useForm({
        email: '', 
        password: '',
        remember: false,
    });

    useEffect(() => {
        return () => {
            reset('password');
        };
    }, []);

    const submit = (e) => {
        e.preventDefault();
        
        post(route('login'), {
            onSuccess: () => {
                toast.success(t('toast_welcome_back', "Welcome back!"), {
                    description: t('toast_login_success', "You have successfully logged in.")
                });
            },
            onError: (errors) => {
                if (errors.email) {
                    toast.error(t('toast_login_failed', "Login Failed"), { description: errors.email });
                } else {
                    toast.error(t('toast_error', "Error"), { description: t('toast_generic_error', "Something went wrong.") });
                }
            }
        });
    };

    return (
        <GuestLayout>
            <Head title={t('_login', 'Log in')} />

            <div className="flex items-center justify-center min-h-[80vh]">
                <Card className="w-full max-w-md shadow-xl border-0 sm:border bg-card">
                    
                    <CardHeader className="space-y-1 text-center">
                        <CardTitle className="text-2xl font-bold tracking-tight">
                            {t('_auth_welcome', 'Welcome back')}
                        </CardTitle>
                        <CardDescription>
                            {t('_auth_signin_desc', 'Sign in with your email or username')}
                        </CardDescription>
                    </CardHeader>

                    <CardContent>
                        {status && (
                            <div className="mb-4 p-3 rounded-md bg-green-50 text-green-600 text-sm font-medium border border-green-200">
                                {status}
                            </div>
                        )}

                        <form onSubmit={submit} className="space-y-4">
                            
                            {/* Email / Username Field */}
                            <div className="space-y-2">
                                <Label htmlFor="email">{t('_auth_email_username', 'Email or Username')}</Label>
                                <div className="relative">
                                    <User className="absolute start-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                    <Input
                                        id="email"
                                        type="text"
                                        name="email"
                                        placeholder="username or email@example.com"
                                        value={data.email}
                                        className="ps-9"
                                        autoComplete="username"
                                        autoFocus
                                        onChange={(e) => setData('email', e.target.value)}
                                    />
                                </div>
                                {errors.email && (
                                    <p className="text-sm font-medium text-destructive">
                                        {errors.email}
                                    </p>
                                )}
                            </div>

                            {/* Password Field */}
                            <div className="space-y-2">
                                <div className="flex items-center justify-between">
                                    <Label htmlFor="password">{t('_auth_password', 'Password')}</Label>
                                </div>
                                <div className="relative">
                                    <Lock className="absolute start-3 top-2.5 h-4 w-4 text-muted-foreground" />
                                    
                                    <Input
                                        id="password"
                                        type={showPassword ? "text" : "password"} 
                                        name="password"
                                        placeholder="••••••••"
                                        value={data.password}
                                        className="ps-9 pe-10" 
                                        autoComplete="current-password"
                                        onChange={(e) => setData('password', e.target.value)}
                                    />

                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute end-0 top-0 h-full px-3 py-2 hover:bg-transparent text-muted-foreground hover:text-foreground transition-colors"
                                    >
                                        {showPassword ? (
                                            <EyeOff className="h-4 w-4" />
                                        ) : (
                                            <Eye className="h-4 w-4" />
                                        )}
                                        <span className="sr-only">
                                            {showPassword ? 'Hide password' : 'Show password'}
                                        </span>
                                    </button>
                                </div>
                            </div>

                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <Checkbox 
                                        id="remember" 
                                        checked={data.remember}
                                        onCheckedChange={(checked) => setData('remember', checked)}
                                    />
                                    <label
                                        htmlFor="remember"
                                        className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                                    >
                                        {t('_auth_remember_me', 'Remember me')}
                                    </label>
                                </div>

                                {canResetPassword && (
                                    <Link
                                        href={route('password.request')}
                                        className="text-sm font-medium text-primary hover:underline underline-offset-4"
                                    >
                                        {t('_auth_forgot_password', 'Forgot password?')}
                                    </Link>
                                )}
                            </div>

                            <Button className="w-full mt-4" type="submit" disabled={processing}>
                                {processing ? (
                                    <>
                                        <Loader2 className="me-2 h-4 w-4 animate-spin" />
                                        {t('_signing_in', 'Signing in...')}
                                    </>
                                ) : (
                                    <>
                                        {t('_auth_sign_in', 'Sign In')}
                                        {isRtl ? <ArrowLeft className="ms-2 h-4 w-4" /> : <ArrowRight className="ms-2 h-4 w-4" />}
                                    </>
                                )}
                            </Button>
                        </form>
                    </CardContent>

                    <CardFooter className="flex justify-center border-t p-6 bg-muted/20">
                        {registration_enabled ? (
                            <div className="text-sm text-muted-foreground">
                                {t('_auth_no_account', "Don't have an account?")}{' '}
                                <Link 
                                    href={route('register')} 
                                    className="text-primary font-medium hover:underline underline-offset-4"
                                >
                                    {t('_signup', 'Sign up')}
                                </Link>
                            </div>
                        ) : (
                            <div className="text-sm text-muted-foreground">
                                {t('_reg_closed', 'Registration is currently closed.')}
                            </div>
                        )}
                    </CardFooter>
                </Card>
            </div>
        </GuestLayout>
    );
}