import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { X, Eye, EyeOff, LogIn, Loader2, Mail, Lock, Shield, ArrowLeft } from 'lucide-react';
import useAuthStore from '../../store/useAuthStore';
import { loginSchema, LoginFormData } from '../../utils/validationSchemas';
import { useCompanySettings } from '../../contexts/CompanySettingsContext';
import { useAuthModal } from '../../contexts/AuthModalContext';
import * as yup from 'yup';
import { toast } from 'react-toastify';
import Recaptcha from '../common/Recaptcha';
import { recaptchaService } from '../../services/api/systemSettingsService';

const mfaTokenSchema = yup.object().shape({
  mfaToken: yup
    .string()
    .required('MFA token is required')
    .min(6, 'MFA token must be 6 digits')
    .max(8, 'MFA token must be 6-8 characters')
    .matches(/^\d+$|^[A-Z0-9]{8}$/, 'Invalid token format'),
});

type MFATokenFormData = yup.InferType<typeof mfaTokenSchema>;

const LoginModal: React.FC = () => {
  const { closeModal, openModal } = useAuthModal();
  const { login, verifyMFA, isLoading, error, clearError, requiresMFA, clearMFA, isAuthenticated } = useAuthStore();
  const { settings } = useCompanySettings();
  
  const [showPassword, setShowPassword] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState<string | null>(null);
  
  const {
    register: registerMFA,
    handleSubmit: handleSubmitMFA,
    formState: { errors: mfaErrors },
  } = useForm<MFATokenFormData>({
    resolver: yupResolver(mfaTokenSchema),
    defaultValues: {
      mfaToken: '',
    },
  });

  // Close modal on successful authentication
  useEffect(() => {
    if (!isLoading && isAuthenticated && !requiresMFA) {
      closeModal();
    }
  }, [isLoading, isAuthenticated, requiresMFA, closeModal]);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: yupResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
      rememberMe: false,
    },
  });

  const onSubmit = async (data: LoginFormData) => {
    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 login({
        email: data.email,
        password: data.password,
        rememberMe: data.rememberMe,
      });

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

  const onSubmitMFA = async (data: MFATokenFormData) => {
    try {
      clearError();
      await verifyMFA(data.mfaToken);
    } catch (error) {
      console.error('MFA verification error:', error);
    }
  };

  const handleBackToLogin = () => {
    clearMFA();
    clearError();
  };

  // 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">
                  <Shield 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">
              {requiresMFA ? 'Verify Your Identity' : 'Welcome Back'}
            </h2>
            <p className="mt-1 sm:mt-2 text-xs sm:text-sm text-gray-600 font-light tracking-wide">
              {requiresMFA 
                ? 'Enter the 6-digit code from your authenticator app' 
                : `Sign in to ${settings.company_name || 'Luxury Hotel'}`}
            </p>
          </div>

          {requiresMFA ? (
            <form onSubmit={handleSubmitMFA(onSubmitMFA)} 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="mfaToken" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2 tracking-wide">
                  Authentication Code
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Shield className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400" />
                  </div>
                  <input
                    {...registerMFA('mfaToken')}
                    id="mfaToken"
                    type="text"
                    autoComplete="one-time-code"
                    maxLength={8}
                    className={`luxury-input pl-9 sm:pl-10 py-2.5 sm:py-3 text-sm sm:text-base text-center tracking-widest w-full ${
                      mfaErrors.mfaToken ? 'border-red-300 focus:ring-red-500 focus:border-red-500' : ''
                    }`}
                    placeholder="000000"
                  />
                </div>
                {mfaErrors.mfaToken && (
                  <p className="mt-1 text-xs sm:text-sm text-red-600 font-light">
                    {mfaErrors.mfaToken.message}
                  </p>
                )}
                <p className="mt-1.5 text-xs text-gray-500 font-light">
                  Enter the 6-digit code from your authenticator app or an 8-character backup code
                </p>
              </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">Verifying...</span>
                  </>
                ) : (
                  <>
                    <Shield className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5 relative z-10" />
                    <span className="relative z-10">Verify</span>
                  </>
                )}
              </button>

              <div className="text-center">
                <button
                  type="button"
                  onClick={handleBackToLogin}
                  className="inline-flex items-center text-xs sm:text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors"
                >
                  <ArrowLeft className="mr-1 h-3.5 w-3.5 sm:h-4 sm:w-4" />
                  Back to Login
                </button>
              </div>
            </form>
          ) : (
            <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="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-sm text-red-600 font-light">
                    {errors.email.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="current-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-sm text-red-600 font-light">
                    {errors.password.message}
                  </p>
                )}
              </div>

              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 sm:gap-0">
                <div className="flex items-center">
                  <input
                    {...register('rememberMe')}
                    id="rememberMe"
                    type="checkbox"
                    className="h-4 w-4 text-[#d4af37] focus:ring-[#d4af37]/50 border-gray-300 rounded-sm cursor-pointer accent-[#d4af37]"
                  />
                  <label htmlFor="rememberMe" className="ml-2 block text-xs sm:text-sm text-gray-700 cursor-pointer font-light tracking-wide">
                    Remember me
                  </label>
                </div>

                <button
                  type="button"
                  onClick={() => openModal('forgot-password')}
                  className="text-xs sm:text-sm font-medium text-[#d4af37] hover:text-[#c9a227] transition-colors tracking-wide"
                >
                  Forgot password?
                </button>
              </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>
                  </>
                ) : (
                  <>
                    <LogIn className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5 relative z-10" />
                    <span className="relative z-10">Sign In</span>
                  </>
                )}
              </button>
            </form>
          )}

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

export default LoginModal;

