import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { X, Eye, EyeOff, Lock, Loader2, CheckCircle2, XCircle, AlertCircle, KeyRound } from 'lucide-react';
import useAuthStore from '../../../store/useAuthStore';
import { resetPasswordSchema, ResetPasswordFormData } from '../../../shared/utils/validationSchemas';
import { useCompanySettings } from '../../../shared/contexts/CompanySettingsContext';
import { useAuthModal } from '../contexts/AuthModalContext';

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">
    {met ? (
      <CheckCircle2 className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-green-500 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-green-600' : 'text-gray-500'}>
      {text}
    </span>
  </div>
);

interface ResetPasswordModalProps {
  token: string;
}

const ResetPasswordModal: React.FC<ResetPasswordModalProps> = ({ token }) => {
  const { closeModal, openModal } = useAuthModal();
  const { resetPassword, isLoading, error, clearError, isAuthenticated } = useAuthStore();
  const { settings } = useCompanySettings();

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);

  // Close modal on successful reset
  useEffect(() => {
    if (!isLoading && isAuthenticated) {
      setTimeout(() => {
        closeModal();
        openModal('login');
      }, 2000);
    }
  }, [isLoading, isAuthenticated, closeModal, openModal]);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<ResetPasswordFormData>({
    resolver: yupResolver(resetPasswordSchema),
    defaultValues: {
      password: '',
      confirmPassword: '',
    },
  });

  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: ResetPasswordFormData) => {
    if (!token) {
      return;
    }

    try {
      clearError();
      await resetPassword({
        token,
        password: data.password,
        confirmPassword: data.confirmPassword,
      });
      setIsSuccess(true);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error('Reset password error:', error);
      }
    }
  };

  const isTokenError = error?.includes('token') || error?.includes('expired');
  const isReuseError = error?.toLowerCase().includes('must be different') || error?.toLowerCase().includes('different from old');

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

  if (!token) {
    return null;
  }

  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 && !isSuccess) {
          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-[var(--luxury-gold)]/20">
        {/* Close button */}
        {!isSuccess && (
          <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-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] rounded-full shadow-lg shadow-[var(--luxury-gold)]/30">
                  <KeyRound 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-[var(--luxury-gold)] 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">
              {isSuccess ? 'Complete!' : 'Reset Password'}
            </h2>
            <p className="mt-1 sm:mt-2 text-xs sm:text-sm text-gray-600 font-light tracking-wide">
              {isSuccess
                ? 'Password has been reset successfully'
                : `Enter a new password for your ${settings.company_name || 'Luxury Hotel'} account`}
            </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">
                  <CheckCircle2 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">
                  Password reset successful!
                </h3>
                <p className="text-xs sm:text-sm text-gray-600">
                  Your password has been updated.
                </p>
                <p className="text-xs sm:text-sm text-gray-600">
                  You can now login with your new password.
                </p>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 sm:p-4">
                <p className="text-xs sm:text-sm text-gray-700">
                  Redirecting to login...
                </p>
                <div className="mt-2 flex justify-center">
                  <Loader2 className="animate-spin h-4 w-4 sm:h-5 sm:w-5 text-[var(--luxury-gold)]" />
                </div>
              </div>

              <button
                onClick={() => {
                  closeModal();
                  openModal('login');
                }}
                className="inline-flex items-center justify-center w-full 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-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--luxury-gold)] transition-colors"
              >
                <KeyRound className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                Login Now
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 sm:space-y-5">
              {error && (
                <div
                  className={`border px-3 sm:px-4 py-2.5 sm:py-3 rounded-lg text-xs sm:text-sm flex items-start gap-2 ${
                    isTokenError
                      ? 'bg-yellow-50 border-yellow-200 text-yellow-800'
                      : 'bg-red-50 border-red-200 text-red-700'
                  }`}
                >
                  <AlertCircle className="h-4 w-4 sm:h-5 sm:w-5 flex-shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <p className="font-medium">
                      {isReuseError
                        ? 'New password must be different from old password'
                        : error}
                    </p>
                    {isTokenError && (
                      <button
                        onClick={() => {
                          closeModal();
                          openModal('forgot-password');
                        }}
                        className="mt-2 inline-block text-xs sm:text-sm font-medium underline hover:text-yellow-900"
                      >
                        Request new link
                      </button>
                    )}
                  </div>
                </div>
              )}

              <div>
                <label htmlFor="password" className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">
                  New 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"
                    autoFocus
                    className={`block w-full pl-9 sm:pl-10 pr-9 sm:pr-10 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.password
                        ? 'border-red-300 focus:ring-red-500'
                        : 'border-gray-300 focus:ring-[var(--luxury-gold)]'
                    }`}
                    placeholder="••••••••"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400 hover:text-gray-600" />
                    ) : (
                      <Eye className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400 hover:text-gray-600" />
                    )}
                  </button>
                </div>
                {errors.password && (
                  <p className="mt-1 text-xs sm:text-sm text-red-600">
                    {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.color}`}
                          style={{ width: `${(passwordStrength.strength / 5) * 100}%` }}
                        />
                      </div>
                      <span className="text-[10px] sm:text-xs font-medium text-gray-600">
                        {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">
                  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={`block w-full pl-9 sm:pl-10 pr-9 sm:pr-10 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.confirmPassword
                        ? 'border-red-300 focus:ring-red-500'
                        : 'border-gray-300 focus:ring-[var(--luxury-gold)]'
                    }`}
                    placeholder="••••••••"
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showConfirmPassword ? (
                      <EyeOff className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400 hover:text-gray-600" />
                    ) : (
                      <Eye className="h-4 w-4 sm:h-5 sm:w-5 text-gray-400 hover:text-gray-600" />
                    )}
                  </button>
                </div>
                {errors.confirmPassword && (
                  <p className="mt-1 text-xs sm:text-sm text-red-600">
                    {errors.confirmPassword.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-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--luxury-gold)] 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...
                  </>
                ) : (
                  <>
                    <KeyRound className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" />
                    Reset Password
                  </>
                )}
              </button>

              <div className="text-center">
                <button
                  type="button"
                  onClick={() => openModal('login')}
                  className="text-xs sm:text-sm font-medium text-[var(--luxury-gold)] hover:text-[var(--luxury-gold-dark)] transition-colors"
                >
                  Back to Login
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default ResetPasswordModal;

