'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 { createForgotPasswordSchema, createResetPasswordSchema, type ForgotPasswordInput } from '@/lib/auth-schemas';
import { AuthService } from '@/lib/auth-service';
import { useLanguage } from '@/lib/language-context';
import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowLeft, ArrowRight } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';

export default function ForgotPasswordPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [resetToken, setResetToken] = useState<string | null>(null);
  const [showResetForm, setShowResetForm] = useState(false);
  const { t, language } = useLanguage();

  const forgotPasswordSchema = useMemo(() => createForgotPasswordSchema(t), [t]);

  const forgotForm = useForm<ForgotPasswordInput>({
    resolver: zodResolver(forgotPasswordSchema),
    defaultValues: {
      email: '',
    },
  });

  const onForgotSubmit = async (data: ForgotPasswordInput) => {
    setIsLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const response = await AuthService.forgotPassword(data.email, language);

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

      // Store the reset token if provided (in development)
      if (response.resetToken) {
        setResetToken(response.resetToken);
        setShowResetForm(true);
      }

      setSuccess(response.message || t("auth.resetInstructionsSent"));
    } catch (err: any) {
      setError(t("auth.unexpectedError"));
    } finally {
      setIsLoading(false);
    }
  };

  if (showResetForm && resetToken) {
    return <ResetPasswordForm token={resetToken} />;
  }

  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>

      {/* Content */}
      <div className="relative z-10 w-full max-w-md px-4">
        {/* Card with glassmorphism effect */}
        <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-32 h-32 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>

          {/* Header */}
          <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.resetPassword")}
            </h1>
            <p className="text-gray-600">
              {t("auth.resetPasswordDescription")}
            </p>
          </div>

          {/* Error Alert */}
          {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 Alert */}
          {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>
          )}

          {/* Forgot Password Form */}
          <Form {...forgotForm}>
            <form
              onSubmit={forgotForm.handleSubmit(onForgotSubmit)}
              className="space-y-5"
            >
              {/* Email Field */}
              <FormField
                control={forgotForm.control}
                name="email"
                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.emailAddress")}</FormLabel>
                    <FormControl>
                      <Input
                        type="email"
                        placeholder={t("auth.emailPlaceholder")}
                        {...field}
                        disabled={isLoading}
                        className="h-12 px-4 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Submit Button */}
              <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">
                    <span className="inline-block animate-spin">⚡</span>
                    {t("auth.sendingLink")}
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2 flex-wrap text-center">
                    {t("auth.sendResetLink")}
                    <ArrowRight className="w-4 h-4" />
                  </span>
                )}
              </Button>
            </form>
          </Form>

          {/* Divider with OR */}
          <div className="my-8 flex items-center animate-in fade-in duration-500" style={{ animationDelay: '0.6s' }}>
            <div className="flex-grow border-t border-gray-200"></div>
            <span className="px-3 text-gray-400 text-sm font-medium">{t("auth.or")}</span>
            <div className="flex-grow border-t border-gray-200"></div>
          </div>

          {/* Back to Login */}
          <div className="text-center animate-in fade-in duration-500" style={{ animationDelay: '0.7s' }}>
            <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>

        {/* Tips (Optional, keeping styled nicely) */}
        {!success && (
          <div className="mt-8 p-6 bg-white/10 backdrop-blur-md rounded-xl border border-white/20 shadow-lg animate-in fade-in duration-700" style={{ animationDelay: '0.8s' }}>
            <h3 className="text-sm font-bold text-white mb-2 flex items-center gap-2">
              <span className="bg-white/20 p-1 rounded">💡</span>
              {t("auth.didNotReceiveEmail")}
            </h3>
            <ul className="text-sm text-blue-50 space-y-2 pl-2">
              <li className="flex items-start gap-2">
                <span className="text-cyan-200 mt-0.5">•</span>
                {t("auth.checkSpam")}
              </li>
              <li className="flex items-start gap-2">
                <span className="text-cyan-200 mt-0.5">•</span>
                {t("auth.enterCorrectEmail")}
              </li>
              <li className="flex items-start gap-2">
                <span className="text-cyan-200 mt-0.5">•</span>
                {t("auth.requestNewLink")}
              </li>
            </ul>
          </div>
        )}

      </div>
    </div>
  );
}

// Reset Password Form Component
function ResetPasswordForm({ token }: { token: string }) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const { t } = useLanguage();

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

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

  const onResetSubmit = async (data: any) => {
    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';
      }, 1500);
    } catch (err: any) {
      setError(t("auth.unexpectedError"));
    } finally {
      setIsLoading(false);
    }
  };

  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">
        <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-32 h-32 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>
                      <Input
                        type="password"
                        placeholder={t("auth.enterNewPassword")}
                        {...field}
                        disabled={isLoading}
                        className="h-12 px-4 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg"
                      />
                    </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>
                      <Input
                        type="password"
                        placeholder={t("auth.confirmNewPassword")}
                        {...field}
                        disabled={isLoading}
                        className="h-12 px-4 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg"
                      />
                    </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' }}
              >
                <span className="block w-full text-center">
                  {isLoading ? t("auth.resetting") : 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>
      </div>
    </div>
  );
}
