'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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { createRegisterSchema } 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, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

export default function RegisterPage() {
  const router = useRouter();
  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 [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const { t, language } = useLanguage();
  const { token, hasActiveSubscription, user } = useAuthStore();

  const registerSchema = useMemo(() => createRegisterSchema(t), [t]);
  type RegisterInput = z.infer<typeof registerSchema>;

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

  const form = useForm<RegisterInput>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: '',
      userType: 'doctor',
      isDentist: false, // Default to false
    },
  });

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

    try {
      const result = await AuthService.register({
        ...data,
        language,
      });

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

      setSuccess(t('auth.registrationSuccessEmail'));
      setTimeout(() => {
        router.push('/login');
      }, 2000);
    } 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 py-8">
      {/* 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-2xl 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-4xl font-bold bg-linear-to-r from-cyan-600 to-blue-600 bg-clip-text text-transparent mb-2">{t("auth.createAccount")}</h1>
            <p className="text-gray-600">{t("auth.joinSystem")}</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>
          )}

          {/* Registration Form */}
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
              {/* Name Fields */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 animate-in fade-in duration-500" style={{ animationDelay: '0.3s' }}>
                <FormField
                  control={form.control}
                  name="firstName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.firstName")}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder={t("auth.firstNamePlaceholder")}
                          {...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={form.control}
                  name="lastName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.lastName")}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder={t("auth.lastNamePlaceholder")}
                          {...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>
                  )}
                />
              </div>

              {/* Email Field */}
              <FormField
                control={form.control}
                name="email"
                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.email")}</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>
                )}
              />

              {/* Password Fields */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 animate-in fade-in duration-500" style={{ animationDelay: '0.5s' }}>
                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.password")}</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showPassword ? 'text' : 'password'}
                            placeholder={t("auth.password")}
                            {...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={() => 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>
                  )}
                />

                <FormField
                  control={form.control}
                  name="confirmPassword"
                  render={({ field }) => (
                    <FormItem>
                      <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.confirmPassword")}
                            {...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>
                  )}
                />
              </div>

              {/* User Type Field */}
              <FormField
                control={form.control}
                name="userType"
                render={({ field }) => (
                  <FormItem className="animate-in fade-in duration-500" style={{ animationDelay: '0.6s' }}>
                    <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.userType")}</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      disabled={isLoading}
                    >
                      <FormControl>
                        <SelectTrigger className="h-12 border-gray-300 focus:border-cyan-500 focus:ring-cyan-500 transition-all duration-300 rounded-lg">
                          <SelectValue placeholder={t("auth.selectUserType")} />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="doctor">{t("auth.doctor")}</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Dentist Question - Only for Doctors */}
              {form.watch('userType') === 'doctor' && (
                <FormField
                  control={form.control}
                  name="isDentist"
                  render={({ field }) => (
                    <FormItem className="space-y-3">
                      <div className="animate-in fade-in slide-in-from-top-2 duration-300">
                        <FormLabel className="text-gray-700 font-semibold text-sm">{t("auth.areYouDentist")}</FormLabel>
                        <FormControl>
                          <div className="flex gap-4 mt-2">
                            <label className={`flex-1 relative border rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition-all ${field.value === true ? 'border-cyan-500 bg-cyan-50 ring-1 ring-cyan-500' : 'border-gray-200'}`}>
                              <input
                                type="radio"
                                className="sr-only"
                                checked={field.value === true}
                                onChange={() => field.onChange(true)}
                              />
                              <div className="flex items-center justify-center gap-2">
                                <span className={`font-medium ${field.value === true ? 'text-cyan-700' : 'text-gray-600'}`}>{t("common.yes")}</span>
                              </div>
                            </label>
                            <label className={`flex-1 relative border rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition-all ${field.value === false ? 'border-cyan-500 bg-cyan-50 ring-1 ring-cyan-500' : 'border-gray-200'}`}>
                              <input
                                type="radio"
                                className="sr-only"
                                checked={field.value === false}
                                onChange={() => field.onChange(false)}
                              />
                              <div className="flex items-center justify-center gap-2">
                                <span className={`font-medium ${field.value === false ? 'text-cyan-700' : 'text-gray-600'}`}>{t("common.no")}</span>
                              </div>
                            </label>
                          </div>
                        </FormControl>
                        <FormMessage />
                      </div>
                    </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 animate-in fade-in text-lg"
                style={{ animationDelay: '0.7s', animationDuration: '500ms' }}
              >
                {isLoading ? (
                  <span className="flex items-center gap-2">
                    <span className="inline-block animate-spin">⚡</span>
                    {t("auth.creatingAccount")}
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    {t('auth.createAccount')}
                    <ArrowRight className="w-4 h-4" />
                  </span>
                )}
              </Button>
            </form>
          </Form>

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