'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 { createLoginSchema, type LoginInput } from '@/lib/auth-schemas';
import { AuthService } from '@/lib/auth-service';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowRight, Eye, EyeOff } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';

export default function LoginPage() {
  const router = useRouter();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const { token, hasActiveSubscription, user } = useAuthStore();
  const isRedirectingRef = useRef(false);

  const loginSchema = useMemo(() => createLoginSchema(t), [t]);

  useEffect(() => {
    if (isRedirectingRef.current) return;
    if (token && (hasActiveSubscription || user?.userType === 'admin')) {
      isRedirectingRef.current = true;
      router.replace('/dashboard');
    }
  }, [token, hasActiveSubscription, user, router]);

  const form = useForm<LoginInput>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
    },
  });

  const onSubmit = async (data: LoginInput) => {
    setIsLoading(true);
    setError(null);
    setSuccess(null);

    try {
      const result = await AuthService.login(data.email, data.password);

      if (!result.success) {
        setError(result.error || t('errors.loginFailed'));
        return;
      }

      setSuccess(t('messages.loginSuccess'));
      if (!isRedirectingRef.current) {
        isRedirectingRef.current = true;
        const target = (result.hasActiveSubscription || result.user?.userType === 'admin')
          ? '/dashboard'
          : '/#pricing';
        router.replace(target);
      }
    } catch {
      setError(t('errors.serverError'));
    } 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>

      {/* Content */}
      <div className="relative z-10 w-full max-w-lg px-4">
        {/* Card with glassmorphism effect */}
        <div className="backdrop-blur-sm bg-white/95 rounded-2xl shadow-2xl p-10 transform transition-all duration-500 hover:shadow-3xl animate-in fade-in slide-in-from-bottom-4">
          {/* Logo */}
          <div className="flex justify-center mb-8 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-10 animate-in fade-in duration-500" style={{ animationDelay: '0.2s' }}>
            <h1 className="text-5xl font-bold bg-linear-to-r from-cyan-600 to-blue-600 bg-clip-text text-transparent mb-3">{t('messages.welcome')}</h1>
            <p className="text-gray-600 text-lg">{t('auth.signIn')}</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>
          )}

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

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

              {/* Submit Button */}
              <Button
                type="submit"
                disabled={isLoading}
                className="w-full min-h-16 bg-linear-to-r from-cyan-500 to-blue-600 hover:from-cyan-600 hover:to-blue-700 text-white font-semibold py-5 px-4 rounded-lg transition-all duration-300 transform hover:shadow-lg active:scale-95 mt-6 text-lg"
                style={{ animation: 'fadeIn 500ms ease-in both', animationDelay: '0.5s' }}
              >
                {isLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="inline-block animate-spin">⚡</span>
                    {t('common.loading')}
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    {t('auth.signIn')}
                    <ArrowRight className="w-4 h-4" />
                  </span>
                )}
              </Button>
            </form>
          </Form>

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

          {/* Register Link */}
          <div className="text-center mt-4 animate-in fade-in duration-500" style={{ animationDelay: '0.7s' }}>
            <p className="text-gray-600 text-sm">
              {t('auth.dontHaveAccount')}{' '}
              <Link
                href="/register"
                className="text-cyan-600 hover:text-cyan-700 font-semibold transition-colors duration-200 inline-flex items-center gap-1 group"
              >
                {t('auth.register')}
                <ArrowRight className="w-3 h-3 group-hover:translate-x-1 transition-transform duration-200" />
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
