import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { X, Mail, ArrowLeft, Send, Loader2, CheckCircle } from 'lucide-react';
import useAuthStore from '../../../store/useAuthStore';
import { forgotPasswordSchema, ForgotPasswordFormData } from '../../../shared/utils/validationSchemas';
import { useCompanySettings } from '../../../shared/contexts/CompanySettingsContext';
import { useAuthModal } from '../contexts/AuthModalContext';
import { useAntibotForm } from '../hooks/useAntibotForm';
import HoneypotField from '../../../shared/components/HoneypotField';
import { toast } from 'react-toastify';

const ForgotPasswordModal: React.FC = () => {
  const { closeModal, openModal } = useAuthModal();
  const { forgotPassword, isLoading, error, clearError } = useAuthStore();
  const { settings } = useCompanySettings();
  
  const [isSuccess, setIsSuccess] = useState(false);
  const [submittedEmail, setSubmittedEmail] = useState('');
  
  // Enhanced antibot protection
  const {
    honeypotValue,
    setHoneypotValue,
    validate: validateAntibot,
    rateLimitInfo,
  } = useAntibotForm({
    formId: 'forgot-password',
    minTimeOnPage: 3000,
    minTimeToFill: 2000,
    requireRecaptcha: false,
    maxAttempts: 3,
    onValidationError: (errors) => {
      errors.forEach((err) => toast.error(err));
    },
  });

  const supportEmail = settings.company_email || 'support@hotel.com';
  const supportPhone = settings.company_phone || '1900-xxxx';

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotPasswordFormData>({
    resolver: yupResolver(forgotPasswordSchema),
    defaultValues: {
      email: '',
    },
  });

  const onSubmit = async (data: ForgotPasswordFormData) => {
    try {
      clearError();
      
      // Validate antibot protection
      const isValid = await validateAntibot();
      if (!isValid) {
        return;
      }
      
      setSubmittedEmail(data.email);
      await forgotPassword({ email: data.email });
      setIsSuccess(true);
    } catch (error) {
      console.error('Forgot password error:', error);
    }
  };

  // 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">
                  <Mail 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">
              Forgot Password?
            </h2>
            <p className="mt-1 sm:mt-2 text-xs sm:text-sm text-gray-600 font-light tracking-wide">
              Enter your email to receive a password reset link for {settings.company_name || 'Luxury Hotel'}
            </p>
          </div>

          {isSuccess ? (
            <div className="text-center space-y-4 sm:space-y-5">
              <div className="flex justify-center">
                <div className="w-12 h-12 sm:w-14 sm:h-14 lg:w-16 lg:h-16 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 sm:w-8 sm:h-8 lg:w-10 lg:h-10 text-green-600" />
                </div>
              </div>

              <div className="space-y-1.5 sm:space-y-2">
                <h3 className="text-lg sm:text-xl font-semibold text-gray-900">
                  Email Sent!
                </h3>
                <p className="text-xs sm:text-sm text-gray-600">
                  We have sent a password reset link to
                </p>
                <p className="text-xs sm:text-sm font-medium text-[#d4af37] break-all">
                  {submittedEmail}
                </p>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 sm:p-4 text-left">
                <p className="text-xs sm:text-sm text-gray-700">
                  <strong>Note:</strong>
                </p>
                <ul className="mt-2 space-y-1 text-xs sm:text-sm text-gray-600 list-disc list-inside">
                  <li>Link is valid for 1 hour</li>
                  <li>Check your Spam/Junk folder</li>
                  <li>If you don't receive the email, please try again</li>
                </ul>
              </div>

              <div className="space-y-2.5 sm:space-y-3">
                <button
                  onClick={() => {
                    setIsSuccess(false);
                    clearError();
                  }}
                  className="w-full flex items-center justify-center py-2.5 sm:py-3 px-4 border border-gray-300 rounded-lg text-xs sm:text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#d4af37] transition-colors"
                >
                  <Mail className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                  Resend Email
                </button>

                <button
                  onClick={() => openModal('login')}
                  className="w-full flex items-center justify-center py-2.5 sm:py-3 px-4 border border-transparent rounded-lg text-xs sm:text-sm font-medium text-white bg-gradient-to-r from-[#d4af37] to-[#c9a227] hover:from-[#f5d76e] hover:to-[#d4af37] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#d4af37] transition-colors"
                >
                  <ArrowLeft className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                  Back to Login
                </button>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 sm:space-y-5 relative">
              {/* Honeypot field - hidden from users */}
              <HoneypotField value={honeypotValue} onChange={setHoneypotValue} />
              
              {rateLimitInfo && !rateLimitInfo.allowed && (
                <div className="bg-yellow-50/80 backdrop-blur-sm border border-yellow-200 text-yellow-700 px-4 py-3 rounded-sm text-sm font-light mb-4">
                  Too many password reset attempts. Please try again later.
                </div>
              )}
              {error && (
                <div className="bg-red-50 border border-red-200 text-red-700 px-3 sm:px-4 py-2.5 sm:py-3 rounded-lg text-xs sm:text-sm">
                  {error}
                </div>
              )}

              <div>
                <label htmlFor="email" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">
                  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"
                    autoFocus
                    className={`block w-full pl-9 sm:pl-10 pr-3 py-2.5 sm:py-3 border rounded-lg focus:outline-none focus:ring-2 transition-colors text-sm sm:text-base luxury-input ${
                      errors.email
                        ? 'border-red-300 focus:ring-red-500'
                        : 'border-gray-300 focus:ring-[#d4af37]'
                    }`}
                    placeholder="email@example.com"
                  />
                </div>
                {errors.email && (
                  <p className="mt-1 text-xs sm:text-sm text-red-600">
                    {errors.email.message}
                  </p>
                )}
              </div>

              <button
                type="submit"
                disabled={isLoading}
                className="w-full flex items-center justify-center py-2.5 sm:py-3 px-4 border border-transparent rounded-lg shadow-sm text-xs sm:text-sm font-medium text-white bg-gradient-to-r from-[#d4af37] to-[#c9a227] hover:from-[#f5d76e] hover:to-[#d4af37] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#d4af37] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="animate-spin -ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                    Processing...
                  </>
                ) : (
                  <>
                    <Send className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                    Send Reset Link
                  </>
                )}
              </button>

              <div className="text-center">
                <button
                  type="button"
                  onClick={() => openModal('login')}
                  className="inline-flex items-center text-xs sm:text-sm font-medium text-[#d4af37] hover:text-[#c9a227] transition-colors"
                >
                  <ArrowLeft className="mr-1 h-3.5 w-3.5 sm:h-4 sm:w-4" />
                  Back to Login
                </button>
              </div>
            </form>
          )}

          {!isSuccess && (
            <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>
          )}

          {!isSuccess && (
            <div className="mt-4 bg-white rounded-lg shadow-sm border border-gray-200 p-3 sm:p-4">
              <h3 className="text-xs sm:text-sm font-semibold text-gray-900 mb-1.5 sm:mb-2">
                Need Help?
              </h3>
              <p className="text-[10px] sm:text-xs text-gray-600 leading-relaxed">
                If you're having trouble resetting your password, please contact our support team via email{' '}
                <a
                  href={`mailto:${supportEmail}`}
                  className="text-[#d4af37] hover:underline break-all"
                >
                  {supportEmail}
                </a>
                {supportPhone && (
                  <>
                    {' '}or hotline{' '}
                    <a
                      href={`tel:${supportPhone.replace(/\s+/g, '').replace(/[()]/g, '')}`}
                      className="text-[#d4af37] hover:underline"
                    >
                      {supportPhone}
                    </a>
                  </>
                )}
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ForgotPasswordModal;

