import React, { useState, useEffect } from 'react';
import { Head, useForm, Link, router } from '@inertiajs/react';
import { toast } from 'sonner';
import AuthLayout from '@/Layouts/AuthLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import { KeyRound, ArrowLeft, Loader2, RefreshCw } from "lucide-react";
import { useTranslation } from '@/hooks/useTranslation';

export default function ResetPassword({ email, channel, status }) {
    const { t } = useTranslation();
    
    // Resend Timer State
    const [timeLeft, setTimeLeft] = useState(60);
    const [isResending, setIsResending] = useState(false);

    const { data, setData, post, processing, errors, reset } = useForm({
        email: email || '',
        otp: '',
        password: '',
        password_confirmation: '',
    });

    useEffect(() => {
        if (timeLeft > 0) {
            const timer = setTimeout(() => setTimeLeft(timeLeft - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [timeLeft]);

    const submit = (e) => {
        e.preventDefault();
        post(route('password.store'), {
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

    const handleResend = () => {
        if (timeLeft > 0 || isResending) return;
        setIsResending(true);
        
        router.post(route('password.resend'), { email, channel }, {
            preserveScroll: true,
            onSuccess: () => {
                setTimeLeft(60);
                toast.success(t('A new OTP has been sent!'));
            },
            onError: (err) => {
                toast.error(err.otp || t('Failed to resend OTP.'));
            },
            onFinish: () => setIsResending(false)
        });
    };

    return (
        <AuthLayout>
            <Head title={t('Reset Password')} />

            <Card className="w-full border-border/50 shadow-lg bg-card">
                <CardHeader className="space-y-1 text-center">
                    <div className="mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mb-2">
                        <KeyRound className="h-6 w-6" />
                    </div>
                    <CardTitle className="text-2xl font-bold">{t('Create New Password')}</CardTitle>
                    <CardDescription>
                        {t('Enter the 6-digit OTP code sent to your')} {channel === 'email' ? t('email') : t('phone')} {t('and create a new password.')}
                    </CardDescription>
                </CardHeader>

                <CardContent>
                    {status && (
                        <div className="mb-4 p-3 rounded-lg bg-green-500/10 text-green-600 text-sm font-bold border border-green-500/20 text-center">
                            {status}
                        </div>
                    )}

                    <form onSubmit={submit} className="space-y-4">
                        <input type="hidden" name="email" value={data.email} />

                        {/* OTP Verification Code with Resend Option */}
                        <div className="space-y-2">
                            <div className="flex justify-between items-center">
                                <Label htmlFor="otp">{t('6-Digit OTP Code')}</Label>
                                <button 
                                    type="button" 
                                    onClick={handleResend}
                                    disabled={timeLeft > 0 || isResending}
                                    className={`text-xs font-bold flex items-center gap-1 ${timeLeft > 0 ? 'text-muted-foreground cursor-not-allowed' : 'text-primary hover:underline'}`}
                                >
                                    {isResending ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
                                    {timeLeft > 0 ? `${t('Resend in')} ${timeLeft}s` : t('Resend OTP')}
                                </button>
                            </div>
                            <Input
                                id="otp"
                                type="text"
                                maxLength="6"
                                placeholder="123456"
                                value={data.otp}
                                onChange={(e) => setData('otp', e.target.value.replace(/[^0-9]/g, ''))}
                                className={`text-center tracking-[0.5em] font-mono text-xl h-12 ${errors.otp ? "border-destructive focus-visible:ring-destructive" : ""}`}
                                autoFocus
                                required
                            />
                            {errors.otp && <p className="text-xs text-destructive font-bold p-2 bg-red-500/10 rounded">{errors.otp}</p>}
                        </div>

                        {/* New Password */}
                        <div className="space-y-2 pt-2">
                            <Label htmlFor="password">{t('New Password')}</Label>
                            <Input
                                id="password"
                                type="password"
                                placeholder="••••••••"
                                value={data.password}
                                onChange={(e) => setData('password', e.target.value)}
                                className={errors.password ? "border-destructive focus-visible:ring-destructive" : ""}
                                required
                            />
                            {errors.password && <p className="text-xs text-destructive font-medium">{errors.password}</p>}
                        </div>

                        {/* Confirm Password */}
                        <div className="space-y-2">
                            <Label htmlFor="password_confirmation">{t('Confirm Password')}</Label>
                            <Input
                                id="password_confirmation"
                                type="password"
                                placeholder="••••••••"
                                value={data.password_confirmation}
                                onChange={(e) => setData('password_confirmation', e.target.value)}
                                required
                            />
                        </div>

                        <Button className="w-full gap-2 text-base font-bold shadow-md mt-4" type="submit" disabled={processing}>
                            {processing ? <Loader2 className="w-5 h-5 animate-spin" /> : null}
                            {processing ? t('Resetting Password...') : t('Reset Password')}
                        </Button>
                    </form>
                </CardContent>

                <CardFooter className="flex justify-center border-t py-4 bg-muted/20 rounded-b-xl">
                    <Link 
                        href={route('login')} 
                        className="flex items-center gap-2 text-sm text-muted-foreground hover:text-primary transition-colors font-bold"
                    >
                        <ArrowLeft className="h-4 w-4" />
                        {t('Back to login')}
                    </Link>
                </CardFooter>
            </Card>
        </AuthLayout>
    );
}