'use client';

import { AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { createResetPasswordSchema } from '@/lib/auth-schemas';
import { AuthService } from '@/lib/auth-service';
import { useLanguage } from '@/lib/language-context';
import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';

function ResetPasswordFormContent() {
    const searchParams = useSearchParams();
    const token = searchParams.get('token');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [showNewPassword, setShowNewPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    const { t } = useLanguage();

    const resetPasswordSchema = useMemo(() => createResetPasswordSchema(t), [t]);

    const resetForm = useForm({
        resolver: zodResolver(resetPasswordSchema),
        defaultValues: {
            token: token || '',
            newPassword: '',
            confirmPassword: '',
        },
    });

    // Update token in form if it changes in URL
    useEffect(() => {
        if (token) {
            resetForm.setValue('token', token);
        }
    }, [token, resetForm]);

    const onResetSubmit = async (data: any) => {
        if (!token) {
            setError(t("auth.resetTokenMissing"));
            return;
        }

        setIsLoading(true);
        setError(null);
        setSuccess(null);

        try {
            const response = await AuthService.resetPassword(
                token,
                data.newPassword,
                data.confirmPassword
            );

            if (!response.success) {
                setError(response.error || t("auth.failedResetPassword"));
                return;
            }

            setSuccess(t("auth.resetSuccessRedirect"));
            setTimeout(() => {
                window.location.href = '/login';
            }, 2000);
        } catch (err: any) {
            setError(t("auth.unexpectedError"));
        } finally {
            setIsLoading(false);
        }
    };

    if (!token) {
        return (
            <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 animate-in fade-in slide-in-from-bottom-4 text-center">
                <div className="flex justify-center mb-6">
                    <div className="relative w-32 h-32">
                        <Image src="/assets/logo-v4-fixed.png" alt={t('common.clinicLogo')} fill className="object-cover rounded-full border-4 border-white shadow-lg" />
                    </div>
                </div>
                <h1 className="text-2xl font-bold text-red-600 mb-4">{t("auth.invalidLink")}</h1>
                <p className="text-gray-600 mb-8">{t("auth.tokenMissingDescription")}</p>
                <Link
                    href="/forgot-password"
                    className="text-cyan-600 hover:text-cyan-700 font-medium inline-flex items-center gap-1"
                >
                    <ArrowLeft className="w-4 h-4" />
                    {t("auth.backToForgotPassword")}
                </Link>
            </div>
        );
    }

    return (
        <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 transform transition-all duration-500 hover:shadow-3xl animate-in fade-in slide-in-from-bottom-4">
            {/* Logo */}
            <div className="flex justify-center mb-6 animate-in fade-in duration-500" style={{ animationDelay: '0.1s' }}>
                <div className="relative w-24 h-24 transform transition-transform hover:scale-105">
                    <Image
                        src="/assets/logo-v4-fixed.png"
                        alt={t('common.clinicLogo')}
                        fill
                        className="object-cover rounded-full border-4 border-white shadow-lg"
                        priority
                    />
                </div>
            </div>

            <div className="text-center mb-8 animate-in fade-in duration-500" style={{ animationDelay: '0.2s' }}>
                <h1 className="text-3xl font-bold bg-linear-to-r from-cyan-600 to-blue-600 bg-clip-text text-transparent mb-2">
                    {t("auth.createNewPassword")}
                </h1>
                <p className="text-gray-600">{t("auth.enterNewPasswordBelow")}</p>
            </div>

            {error && (
                <div className="mb-6 animate-in fade-in duration-300 p-4 rounded-lg bg-red-50 border border-red-200">
                    <AlertDescription className="text-red-700 font-medium">{error}</AlertDescription>
                </div>
            )}

            {success && (
                <div className="mb-6 animate-in fade-in duration-300 p-4 rounded-lg bg-green-50 border border-green-200">
                    <AlertDescription className="text-green-700 font-medium">
                        {success}
                    </AlertDescription>
                </div>
            )}

            <Form {...resetForm}>
                <form
                    onSubmit={resetForm.handleSubmit(onResetSubmit)}
                    className="space-y-5"
                >
                    <FormField
                        control={resetForm.control}
                        name="newPassword"
                        render={({ field }) => (
                            <FormItem className="animate-in fade-in duration-500" style={{ animationDelay: '0.3s' }}>
                                <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.newPasswordLabel")}</FormLabel>
                                <FormControl>
                                    <div className="relative">
                                        <Input
                                            type={showNewPassword ? 'text' : 'password'}
                                            placeholder={t("auth.enterNewPassword")}
                                            {...field}
                                            disabled={isLoading}
                                            className="h-12 px-4 pr-12 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowNewPassword(v => !v)}
                                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                            tabIndex={-1}
                                        >
                                            {showNewPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                        </button>
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={resetForm.control}
                        name="confirmPassword"
                        render={({ field }) => (
                            <FormItem className="animate-in fade-in duration-500" style={{ animationDelay: '0.4s' }}>
                                <FormLabel className="text-gray-700 font-semibold text-sm">
                                    {t("auth.confirmPassword")}
                                </FormLabel>
                                <FormControl>
                                    <div className="relative">
                                        <Input
                                            type={showConfirmPassword ? 'text' : 'password'}
                                            placeholder={t("auth.confirmNewPassword")}
                                            {...field}
                                            disabled={isLoading}
                                            className="h-12 px-4 pr-12 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowConfirmPassword(v => !v)}
                                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                            tabIndex={-1}
                                        >
                                            {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                                        </button>
                                    </div>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <Button
                        type="submit"
                        disabled={isLoading}
                        className="w-full h-auto min-h-14 sm:min-h-16 whitespace-normal break-words bg-linear-to-r from-cyan-500 to-blue-600 hover:from-cyan-600 hover:to-blue-700 text-white font-semibold py-4 sm:py-5 px-4 rounded-lg transition-all duration-300 transform hover:shadow-lg active:scale-95 mt-6 text-base sm:text-lg leading-tight"
                        style={{ animation: 'fadeIn 500ms ease-in both', animationDelay: '0.5s' }}
                    >
                        {isLoading ? (
                            <span className="flex items-center justify-center gap-2 flex-wrap text-center">
                                <Loader2 className="w-5 h-5 animate-spin" />
                                {t("auth.resetting")}
                            </span>
                        ) : (
                            <span className="block w-full text-center">
                                {t("auth.resetPasswordBtn")}
                            </span>
                        )}
                    </Button>
                </form>
            </Form>

            <div className="mt-6 text-center animate-in fade-in duration-500" style={{ animationDelay: '0.6s' }}>
                <Link
                    href="/login"
                    className="text-cyan-600 hover:text-cyan-700 text-sm font-medium transition-colors duration-200 inline-flex items-center gap-1 group"
                >
                    <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform duration-200" />
                    {t("auth.backToLogin")}
                </Link>
            </div>

            <div className="mt-8 p-4 bg-gray-50 rounded-lg border border-gray-200 animate-in fade-in duration-500" style={{ animationDelay: '0.7s' }}>
                <h3 className="text-sm font-semibold text-gray-900 mb-2">
                    {t("auth.passwordRequirements")}
                </h3>
                <ul className="text-sm text-gray-600 space-y-1">
                    <li>✓ {t("auth.charMinimum")}</li>
                    <li>✓ {t("auth.passwordsMatch")}</li>
                </ul>
            </div>
        </div>
    );
}

export default function ResetPasswordPage() {
    return (
        <div className="min-h-screen bg-linear-to-br from-cyan-400 via-cyan-500 to-blue-600 overflow-hidden flex items-center justify-center relative">
            {/* Decorative circles */}
            <div className="absolute bottom-0 right-0 w-96 h-96 bg-yellow-300 rounded-full opacity-20 transform translate-x-32 translate-y-32 animate-pulse"></div>
            <div className="absolute top-0 left-0 w-72 h-72 bg-white rounded-full opacity-5 animate-pulse" style={{ animationDelay: '0.5s' }}></div>

            <div className="relative z-10 w-full max-w-md px-4">
                <Suspense fallback={
                    <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-8 flex items-center justify-center min-h-[400px]">
                        <Loader2 className="w-12 h-12 text-cyan-600 animate-spin" />
                    </div>
                }>
                    <ResetPasswordFormContent />
                </Suspense>
            </div>
        </div>
    );
}
