import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { X, Eye, EyeOff, UserPlus, Loader2, Mail, Lock, User, Phone, CheckCircle2, XCircle } from 'lucide-react';
import useAuthStore from '../../store/useAuthStore';
import { registerSchema, RegisterFormData } from '../../utils/validationSchemas';
import { useCompanySettings } from '../../contexts/CompanySettingsContext';
import { useAuthModal } from '../../contexts/AuthModalContext';
import { toast } from 'react-toastify';
import Recaptcha from '../common/Recaptcha';
import { recaptchaService } from '../../services/api/systemSettingsService';

const PasswordRequirement: React.FC<{ met: boolean; text: string }> = ({ met, text }) => (
  <div className="flex items-center gap-1.5 sm:gap-2 text-[10px] sm:text-xs font-light">
    {met ? (
      <CheckCircle2 className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-[#d4af37] flex-shrink-0" />
    ) : (
      <XCircle className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-gray-300 flex-shrink-0" />
    )}
    <span className={met ? 'text-[#c9a227] font-medium' : 'text-gray-500'}>
      {text}
    </span>
  </div>
);

const RegisterModal: React.FC = () => {
  const { closeModal, openModal } = useAuthModal();
  const { register: registerUser, isLoading, error, clearError, isAuthenticated } = useAuthStore();
  const { settings } = useCompanySettings();

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState<string | null>(null);

  useEffect(() => {
    if (!isLoading && isAuthenticated) {
      closeModal();
    }
  }, [isLoading, isAuthenticated, closeModal]);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<RegisterFormData>({
    resolver: yupResolver(registerSchema),
    defaultValues: {
      name: '',
      email: '',
      password: '',
      confirmPassword: '',
      phone: '',
    },
  });

  const password = watch('password');

  const getPasswordStrength = (pwd: string) => {
    if (!pwd) return { strength: 0, label: '', color: '' };

    let strength = 0;
    if (pwd.length >= 8) strength++;
    if (/[a-z]/.test(pwd)) strength++;
    if (/[A-Z]/.test(pwd)) strength++;
    if (/\d/.test(pwd)) strength++;
    if (/[@$!%*?&]/.test(pwd)) strength++;

    const labels = [
      { label: 'Very Weak', color: 'bg-red-500' },
      { label: 'Weak', color: 'bg-orange-500' },
      { label: 'Medium', color: 'bg-yellow-500' },
      { label: 'Strong', color: 'bg-blue-500' },
      { label: 'Very Strong', color: 'bg-green-500' },
    ];

    return { strength, ...labels[strength] };
  };

  const passwordStrength = getPasswordStrength(password || '');

  const onSubmit = async (data: RegisterFormData) => {
    try {
      clearError();
      
      if (recaptchaToken) {
        try {
          const verifyResponse = await recaptchaService.verifyRecaptcha(recaptchaToken);
          if (verifyResponse.status === 'error' || !verifyResponse.data.verified) {
            toast.error('reCAPTCHA verification failed. Please try again.');
            setRecaptchaToken(null);
            return;
          }
        } catch (error) {
          toast.error('reCAPTCHA verification failed. Please try again.');
          setRecaptchaToken(null);
          return;
        }
      }
      
      await registerUser({
        name: data.name,
        email: data.email,
        password: data.password,
        phone: data.phone,
      });

      setRecaptchaToken(null);
    } catch (error) {
      console.error('Register error:', error);
      setRecaptchaToken(null);
    }
  };

  // Handle escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        closeModal();
      }
    };
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [closeModal]);

  return (
    <div 
      className="fixed inset-0 z-[9999] flex items-center justify-center p-3 sm:p-4 md:p-6"
      onClick={(e) => {
        if (e.target === e.currentTarget) {
          closeModal();
        }
      }}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
      
      {/* Modal */}
      <div className="relative w-full max-w-md max-h-[95vh] overflow-y-auto bg-gradient-to-br from-gray-50 via-white to-gray-50 rounded-lg shadow-2xl border border-[#d4af37]/20">
        {/* Close button */}
        <button
          onClick={closeModal}
          className="absolute top-3 right-3 z-10 p-2 rounded-full hover:bg-gray-100 transition-colors text-gray-500 hover:text-gray-900"
          aria-label="Close"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="p-4 sm:p-6 lg:p-8">
          {/* Header */}
          <div className="text-center mb-4 sm:mb-6">
            <div className="flex justify-center mb-3 sm:mb-4">
              {settings.company_logo_url ? (
                <img 
                  src={settings.company_logo_url.startsWith('http') 
                    ? settings.company_logo_url 
                    : `${import.meta.env.VITE_API_URL || 'http://localhost:8000'}${settings.company_logo_url}`}
                  alt={settings.company_name || 'Logo'}
                  className="h-12 sm:h-14 lg:h-16 w-auto max-w-[120px] sm:max-w-[150px] object-contain"
                  style={{ filter: 'drop-shadow(0 4px 6px rgba(0,0,0,0.1))' }}
                />
              ) : (
                <div className="relative p-2.5 sm:p-3 bg-gradient-to-br from-[#d4af37] to-[#c9a227] rounded-full shadow-lg shadow-[#d4af37]/30">
                  <UserPlus className="w-6 h-6 sm:w-8 sm:h-8 text-[#0f0f0f] relative z-10" />
                </div>
              )}
            </div>
            {settings.company_tagline && (
              <p className="text-[10px] sm:text-xs text-[#d4af37] uppercase tracking-[1.5px] sm:tracking-[2px] mb-1 sm:mb-2 font-light">
                {settings.company_tagline}
              </p>
            )}
            <h2 className="text-xl sm:text-2xl lg:text-3xl font-elegant font-semibold text-gray-900 tracking-tight">
              Create Account
            </h2>
            <p className="mt-1 sm:mt-2 text-xs sm:text-sm text-gray-600 font-light tracking-wide">
              Join {settings.company_name || 'Luxury Hotel'} for exclusive benefits
            </p>
          </div>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 sm:space-y-5">
            {error && (
              <div className="bg-red-50/80 backdrop-blur-sm border border-red-200 text-red-700 px-4 py-3 rounded-sm text-sm font-light">
                {error}
              </div>
            )}

            <div>
              <label htmlFor="name" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                Full Name
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <User className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                </div>
                <input
                  {...register('name')}
                  id="name"
                  type="text"
                  autoComplete="name"
                  className={`luxury-input pl-9 sm:pl-10 py-2.5 sm:py-3 text-sm sm:text-base w-full ${
                    errors.name ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="John Doe"
                />
              </div>
              {errors.name && (
                <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                  {errors.name.message}
                </p>
              )}
            </div>

            <div>
              <label htmlFor="email" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                Email
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Mail className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                </div>
                <input
                  {...register('email')}
                  id="email"
                  type="email"
                  autoComplete="email"
                  className={`luxury-input pl-9 sm:pl-10 py-2.5 sm:py-3 text-sm sm:text-base w-full ${
                    errors.email ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="email@example.com"
                />
              </div>
              {errors.email && (
                <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                  {errors.email.message}
                </p>
              )}
            </div>

            <div>
              <label htmlFor="phone" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                Phone Number (Optional)
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Phone className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                </div>
                <input
                  {...register('phone')}
                  id="phone"
                  type="tel"
                  autoComplete="tel"
                  className={`luxury-input pl-9 sm:pl-10 py-2.5 sm:py-3 text-sm sm:text-base w-full ${
                    errors.phone ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="0123456789"
                />
              </div>
              {errors.phone && (
                <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                  {errors.phone.message}
                </p>
              )}
            </div>

            <div>
              <label htmlFor="password" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                Password
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                </div>
                <input
                  {...register('password')}
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  autoComplete="new-password"
                  className={`luxury-input pl-9 sm:pl-10 pr-9 sm:pr-10 py-2.5 sm:py-3 text-sm sm:text-base w-full ${
                    errors.password ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-0 pr-3 flex items-center transition-colors hover:text-[#d4af37]"
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                  ) : (
                    <Eye className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                  )}
                </button>
              </div>
              {errors.password && (
                <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                  {errors.password.message}
                </p>
              )}

              {password && password.length > 0 && (
                <div className="mt-2">
                  <div className="flex items-center gap-2">
                    <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                      <div
                        className={`h-full transition-all duration-300 ${
                          passwordStrength.strength >= 4 
                            ? 'bg-[#d4af37]' 
                            : passwordStrength.strength >= 3
                            ? 'bg-yellow-500'
                            : 'bg-red-500'
                        }`}
                        style={{ width: `${(passwordStrength.strength / 5) * 100}%` }}
                      />
                    </div>
                    <span className="text-[10px] sm:text-xs font-medium text-gray-600 tracking-wide">
                      {passwordStrength.label}
                    </span>
                  </div>

                  <div className="mt-2 space-y-1">
                    <PasswordRequirement met={password.length >= 8} text="At least 8 characters" />
                    <PasswordRequirement met={/[a-z]/.test(password)} text="Lowercase letter (a-z)" />
                    <PasswordRequirement met={/[A-Z]/.test(password)} text="Uppercase letter (A-Z)" />
                    <PasswordRequirement met={/\d/.test(password)} text="Number (0-9)" />
                    <PasswordRequirement met={/[@$!%*?&]/.test(password)} text="Special character (@$!%*?&)" />
                  </div>
                </div>
              )}
            </div>

            <div>
              <label htmlFor="confirmPassword" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                Confirm Password
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Lock className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                </div>
                <input
                  {...register('confirmPassword')}
                  id="confirmPassword"
                  type={showConfirmPassword ? 'text' : 'password'}
                  autoComplete="new-password"
                  className={`luxury-input pl-9 sm:pl-10 pr-9 sm:pr-10 py-2.5 sm:py-3 text-sm sm:text-base w-full ${
                    errors.confirmPassword ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                  }`}
                  placeholder="••••••••"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute inset-y-0 right-0 pr-3 flex items-center transition-colors hover:text-[#d4af37]"
                >
                  {showConfirmPassword ? (
                    <EyeOff className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                  ) : (
                    <Eye className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                  )}
                </button>
              </div>
              {errors.confirmPassword && (
                <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                  {errors.confirmPassword.message}
                </p>
              )}
            </div>

            <div className="flex justify-center">
              <Recaptcha
                onChange={(token) => setRecaptchaToken(token)}
                onError={(error) => {
                  console.error('reCAPTCHA error:', error);
                  setRecaptchaToken(null);
                }}
                theme="light"
                size="normal"
              />
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className="btn-luxury-primary w-full flex items-center justify-center py-2.5 sm:py-3 px-4 text-xs sm:text-sm relative"
            >
              {isLoading ? (
                <>
                  <Loader2 className="animate-spin -ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5 relative z-10" />
                  <span className="relative z-10">Processing...</span>
                </>
              ) : (
                <>
                  <UserPlus className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5 relative z-10" />
                  <span className="relative z-10">Register</span>
                </>
              )}
            </button>
          </form>

          <div className="mt-4 sm:mt-6 text-center">
            <p className="text-xs sm:text-sm text-gray-600 font-light tracking-wide">
              Already have an account?{' '}
              <button
                onClick={() => openModal('login')}
                className="font-medium text-[#d4af37] hover:text-[#c9a227] transition-colors"
              >
                Login now
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RegisterModal;

