import React, { useState, useEffect } from 'react';
import { X, Shield, Lock, KeyRound } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { toast } from 'react-toastify';
import accountantSecurityService from '../../security/services/accountantSecurityService';
import adminSecurityService from '../../security/services/adminSecurityService';
import useAuthStore from '../../../store/useAuthStore';
import { getUserFriendlyError } from '../../../shared/utils/errorSanitizer';

const mfaTokenSchema = yup.object({
  mfaToken: yup
    .string()
    .required('MFA token is required')
    .matches(/^\d{6}$/, 'MFA token must be 6 digits'),
});

const passwordSchema = yup.object({
  password: yup
    .string()
    .required('Password is required')
    .min(6, 'Password must be at least 6 characters'),
});

type MFATokenFormData = yup.InferType<typeof mfaTokenSchema>;
type PasswordFormData = yup.InferType<typeof passwordSchema>;

interface StepUpAuthModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  actionDescription?: string;
}

const StepUpAuthModal: React.FC<StepUpAuthModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  actionDescription = 'this action',
}) => {
  const { userInfo } = useAuthStore();
  const userWithRoleName = userInfo ? (userInfo as typeof userInfo & { role_name?: string }) : null;
  const isAdmin = (userInfo?.role || userWithRoleName?.role_name)?.toLowerCase() === 'admin';
  const [verificationMethod, setVerificationMethod] = useState<'mfa' | 'password'>('mfa');
  const [isVerifying, setIsVerifying] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const {
    register: registerMFA,
    handleSubmit: handleSubmitMFA,
    formState: { errors: mfaErrors },
    reset: resetMFA,
  } = useForm<MFATokenFormData>({
    resolver: yupResolver(mfaTokenSchema),
    defaultValues: {
      mfaToken: '',
    },
  });

  const {
    register: registerPassword,
    handleSubmit: handleSubmitPassword,
    formState: { errors: passwordErrors },
    reset: resetPassword,
  } = useForm<PasswordFormData>({
    resolver: yupResolver(passwordSchema),
    defaultValues: {
      password: '',
    },
  });

  useEffect(() => {
    if (isOpen) {
      setError(null);
      resetMFA();
      resetPassword();
      // Default to MFA if user has it enabled, otherwise password
      // You can check userInfo.mfa_enabled if available
      setVerificationMethod('mfa');
    }
  }, [isOpen, resetMFA, resetPassword]);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen && !isVerifying) {
        onClose();
      }
    };
    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, isVerifying, onClose]);

  const onSubmitMFA = async (data: MFATokenFormData) => {
    try {
      setIsVerifying(true);
      setError(null);

      const response = await (isAdmin
        ? adminSecurityService.verifyStepUp({
            mfa_token: data.mfaToken,
          })
        : accountantSecurityService.verifyStepUp({
            mfa_token: data.mfaToken,
          }));

      if (response.status === 'success' && response.data.step_up_completed) {
        toast.success('Identity verified successfully');
        // Small delay to ensure backend commit is complete before retrying
        await new Promise(resolve => setTimeout(resolve, 100));
        onSuccess();
        onClose();
      } else {
        throw new Error('Step-up verification failed');
      }
    } catch (error: unknown) {
      // Prevent page refresh by ensuring error is caught and handled
      const errorMessage = getUserFriendlyError(error) || 'Failed to verify identity. Please try again.';
      setError(errorMessage);
      toast.error(errorMessage);
      // Don't close modal on error - let user try again
    } finally {
      setIsVerifying(false);
    }
  };

  const onSubmitPassword = async (data: PasswordFormData) => {
    try {
      setIsVerifying(true);
      setError(null);

      const response = await (isAdmin
        ? adminSecurityService.verifyStepUp({
            password: data.password,
          })
        : accountantSecurityService.verifyStepUp({
            password: data.password,
          }));

      if (response.status === 'success' && response.data.step_up_completed) {
        toast.success('Identity verified successfully');
        // Small delay to ensure backend commit is complete before retrying
        await new Promise(resolve => setTimeout(resolve, 100));
        onSuccess();
        onClose();
      } else {
        throw new Error('Step-up verification failed');
      }
    } catch (error: unknown) {
      // Prevent page refresh by ensuring error is caught and handled
      const errorMessage = getUserFriendlyError(error) || 'Invalid password. Please try again.';
      setError(errorMessage);
      toast.error(errorMessage);
      // Don't close modal on error - let user try again
    } finally {
      setIsVerifying(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center p-3 sm:p-4 md:p-6"
      onClick={(e) => {
        if (e.target === e.currentTarget && !isVerifying) {
          onClose();
        }
      }}
    >
      {/* 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-amber-200">
        {/* Close button */}
        {!isVerifying && (
          <button
            onClick={onClose}
            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-6">
            <div className="mx-auto w-16 h-16 bg-gradient-to-br from-amber-400 to-amber-600 rounded-full flex items-center justify-center mb-4">
              <Shield className="w-8 h-8 text-white" />
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-2">Verify Your Identity</h2>
            <p className="text-gray-600 text-sm">
              Step-up authentication is required for <span className="font-semibold">{actionDescription}</span>
            </p>
          </div>

          {/* Error message */}
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">{error}</div>
          )}

          {/* Verification method selector */}
          <div className="mb-6 flex gap-2 p-1 bg-gray-100 rounded-lg">
            <button
              type="button"
              onClick={() => {
                if (!isVerifying) {
                  setVerificationMethod('mfa');
                  setError(null);
                  resetMFA();
                }
              }}
              className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all ${
                verificationMethod === 'mfa'
                  ? 'bg-white text-amber-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              } ${isVerifying ? 'opacity-50 cursor-not-allowed' : ''}`}
              disabled={isVerifying}
            >
              <div className="flex items-center justify-center gap-2">
                <KeyRound className="w-4 h-4" />
                MFA Token
              </div>
            </button>
            <button
              type="button"
              onClick={() => {
                if (!isVerifying) {
                  setVerificationMethod('password');
                  setError(null);
                  resetPassword();
                }
              }}
              className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all ${
                verificationMethod === 'password'
                  ? 'bg-white text-amber-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              } ${isVerifying ? 'opacity-50 cursor-not-allowed' : ''}`}
              disabled={isVerifying}
            >
              <div className="flex items-center justify-center gap-2">
                <Lock className="w-4 h-4" />
                Password
              </div>
            </button>
          </div>

          {/* MFA Form */}
          {verificationMethod === 'mfa' && (
            <form onSubmit={handleSubmitMFA(onSubmitMFA)} className="space-y-4">
              <div>
                <label htmlFor="mfaToken" className="block text-sm font-medium text-gray-700 mb-2">
                  Enter 6-digit MFA code
                </label>
                <input
                  {...registerMFA('mfaToken')}
                  type="text"
                  id="mfaToken"
                  maxLength={6}
                  placeholder="000000"
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 text-center text-2xl tracking-widest font-mono"
                  disabled={isVerifying}
                  autoComplete="one-time-code"
                />
                {mfaErrors.mfaToken && (
                  <p className="mt-1 text-sm text-red-600">{mfaErrors.mfaToken.message}</p>
                )}
                <p className="mt-2 text-xs text-gray-500">Enter the 6-digit code from your authenticator app</p>
              </div>

              <button
                type="submit"
                disabled={isVerifying}
                className="w-full py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-lg font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {isVerifying ? (
                  <>
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Verifying...
                  </>
                ) : (
                  <>
                    <Shield className="w-5 h-5" />
                    Verify Identity
                  </>
                )}
              </button>
            </form>
          )}

          {/* Password Form */}
          {verificationMethod === 'password' && (
            <form onSubmit={handleSubmitPassword(onSubmitPassword)} className="space-y-4">
              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
                  Re-enter your password
                </label>
                <input
                  {...registerPassword('password')}
                  type="password"
                  id="password"
                  placeholder="Enter your password"
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500"
                  disabled={isVerifying}
                  autoComplete="current-password"
                />
                {passwordErrors.password && (
                  <p className="mt-1 text-sm text-red-600">{passwordErrors.password.message}</p>
                )}
                <p className="mt-2 text-xs text-gray-500">Enter your password to verify your identity</p>
              </div>

              <button
                type="submit"
                disabled={isVerifying}
                className="w-full py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-lg font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {isVerifying ? (
                  <>
                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Verifying...
                  </>
                ) : (
                  <>
                    <Shield className="w-5 h-5" />
                    Verify Identity
                  </>
                )}
              </button>
            </form>
          )}

          {/* Info */}
          <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
            <p className="text-xs text-blue-800">
              <strong>Note:</strong> Step-up authentication is valid for 15 minutes. You won't need to verify again for
              similar actions during this time.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default StepUpAuthModal;

