import React, { useState } from 'react'
import { Eye, EyeOff, X } from 'lucide-react'
import { useIsLoginModalOpen, useSetIsLoginModalOpen } from '../../contexts/UIContext'
import { useAuth } from '../../contexts/AuthContext'
import useRenderTracker from '../../hooks/useRenderTracker'

interface LoginModalProps {
  openSignup: boolean | undefined
}

export default function LoginModal({
  openSignup,
}: LoginModalProps) {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [isSignup, setIsSignup] = useState(openSignup)
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [name, setName] = useState('')
  const [verificationCode, setVerificationCode] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [emailSent, setEmailSent] = useState(false);
  const [isPasswordReset, setIsPasswordReset] = useState(false);
  const [resetVerificationCode, setResetVerificationCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [resetSuccess, setResetSuccess] = useState(false);

  const isLoginModalOpen = useIsLoginModalOpen();
  const setIsLoginModalOpen = useSetIsLoginModalOpen();

  const { login, signup, requestVerification, authError, setAuthError, resetPassword } = useAuth()

  const handleRequestVerification = async () => {
    setIsSubmitting(true);
    try {
      await requestVerification(email, 'registration');
      setIsVerifying(true);
      setEmailSent(true);
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'An error occurred');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handlePasswordResetRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      await requestVerification(email, 'password_reset');
      setIsVerifying(true);
      setEmailSent(true);
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'An error occurred');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handlePasswordReset = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      await resetPassword(email, resetVerificationCode, newPassword);
      setAuthError(null);
      setResetSuccess(true);
    } catch (error) {
      setAuthError(error instanceof Error ? error.message : 'Password reset failed');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setAuthError(null);
    
    try {
      if (isSignup) {
        // Password match verification
        if (password !== confirmPassword) {
          setAuthError("Passwords do not match");
          setIsSubmitting(false);
          return;
        }

        // Password strength validation
        if (password.length < 8) {
          setAuthError("Password must be at least 8 characters long");
          setIsSubmitting(false);
          return;
        }

        if (!isVerifying) {
          await handleRequestVerification();
        } else {
          await signup(name, email, password, verificationCode);
        }
      } else {
        await login(email, password);
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const resetState = () => {
    setEmail('')
    setPassword('')
    setConfirmPassword('')
    setIsSignup(openSignup)
    setShowPassword(false)
    setShowConfirmPassword(false)
    setName('')
    setAuthError(null)
    setIsPasswordReset(false)
    setResetVerificationCode('')
    setNewPassword('')
    setShowNewPassword(false)
    setIsVerifying(false)
    setEmailSent(false)
  }

  const handleClose = () => {
    resetState()
    setIsLoginModalOpen(false)
  }

  useRenderTracker('LoginModal', {
    isLoginModalOpen,
    authError,
    isSignup,
    email,
    name
  });

  if (!isLoginModalOpen) return null

  if (isPasswordReset) {
    if (resetSuccess) {
      return (
        <div className="fixed inset-0 flex items-center justify-center p-4 z-50">
          <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" onClick={handleClose} />
          <div className="bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-2xl shadow-xl w-full max-w-md relative z-10 overflow-hidden">
            <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-xl font-semibold text-text-light dark:text-text-dark">
                Password Reset Successful
              </h2>
            </div>

            <div className="p-8 space-y-6">
              <div className="p-4 bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 rounded-lg">
                <p>Your password has been successfully reset!</p>
                <p className="text-sm mt-1">You can now log in with your new password.</p>
              </div>

              <button
                onClick={() => {
                  resetState();
                  setIsPasswordReset(false);
                  setResetSuccess(false);
                  setIsSignup(false);
                }}
                className="w-full py-3 px-4 rounded-lg shadow-md shadow-black/5 dark:shadow-lg dark:shadow-gray-800/35 dark:border-gray-700/75 bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100"
              >
                Return to Login
              </button>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="fixed inset-0 flex items-center justify-center p-4 z-50">
        <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" onClick={handleClose} />
        <div className="bg-background-light dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-2xl shadow-xl w-full max-w-md relative z-10 overflow-hidden">
          <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700">
            <h2 className="text-xl font-semibold text-text-light dark:text-text-dark">
              {isVerifying ? 'Reset Password' : 'Forgot Password'}
            </h2>
          </div>

          <form onSubmit={isVerifying ? handlePasswordReset : handlePasswordResetRequest} className="p-8 space-y-6">
            {!isVerifying && (
              <div className="space-y-2">
                <label htmlFor="email" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                  Email
                </label>
                <input
                  type="email"
                  id="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                  required
                />
              </div>
            )}

            {isVerifying && (
              <>
                {emailSent && (
                  <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg">
                    <p>We've sent a verification code to <span className="font-medium">{email}</span></p>
                    <p className="text-sm mt-1">Please check your inbox (and spam folder) for the code.</p>
                  </div>
                )}
                <div className="space-y-2">
                  <label htmlFor="resetVerificationCode" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                    Verification Code
                  </label>
                  <input
                    type="text"
                    id="resetVerificationCode"
                    value={resetVerificationCode}
                    onChange={(e) => setResetVerificationCode(e.target.value)}
                    className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                    required
                    autoComplete="off"
                  />
                </div>

                <div className="space-y-2">
                  <label htmlFor="newPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                    New Password
                  </label>
                  <div className="relative">
                    <input
                      type={showNewPassword ? "text" : "password"}
                      id="newPassword"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                      required
                    />
                    <button
                      type="button"
                      onClick={() => setShowNewPassword(!showNewPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                    >
                      {showNewPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                  </div>
                </div>
              </>
            )}

            {authError && (
              <div className="text-red-500 text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
                {typeof authError === 'string' ? authError : 'An error occurred'}
              </div>
            )}

            <button
              type="submit"
              disabled={isSubmitting}
              className={`w-full py-3 px-4 rounded-lg shadow-md shadow-black/5 dark:shadow-lg dark:shadow-gray-800/35 dark:border-gray-700/75 bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100 ${
                isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
              }`}
            >
              {isSubmitting ? (
                <span className="inline-flex items-center">
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Processing...
                </span>
              ) : isVerifying ? (
                'Reset Password'
              ) : (
                'Send Reset Code'
              )}
            </button>
          </form>

          <div className="px-8 py-6 border-t border-gray-200 dark:border-gray-700 text-center">
            <button
              onClick={() => {
                resetState();
                setIsPasswordReset(false);
                setIsSignup(false);
              }}
              className="text-blue-600 dark:text-blue-400 hover:underline"
              type="button"
            >
              Back to Login
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 flex items-center justify-center p-0 sm:p-4 z-50">
      <div className="absolute inset-0 bg-black/30 backdrop-blur-sm" onClick={handleClose} />
      <div className="bg-background-light dark:bg-background-dark 
                      border border-gray-200 dark:border-gray-700 
                      rounded-none sm:rounded-2xl shadow-xl 
                      w-full h-full sm:h-auto sm:max-w-md 
                      relative z-10 
                      max-h-[100dvh] sm:max-h-[85vh] 
                      overflow-y-auto
                      sm:overflow-visible
                      m-0 sm:m-auto">
        <div className="sticky top-0 z-20">
          <div className="flex justify-between items-center p-6 border-b border-gray-200 dark:border-gray-700 bg-background-light dark:bg-background-dark sm:rounded-t-2xl">
            <h2 className="text-xl font-semibold text-text-light dark:text-text-dark">
              {isSignup ? (isVerifying ? 'Verify Email' : 'Sign Up') : 'Login'}
            </h2>
            <button
              onClick={handleClose}
              className="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
              type="button"
              aria-label="Close"
            >
              <X size={24} />
            </button>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="p-8 space-y-6">
          {isSignup && !isVerifying && (
            <div className="space-y-2">
              <label htmlFor="fullName" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Full Name
              </label>
              <input
                type="text"
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
          )}

          {(!isVerifying) && (
            <div className="space-y-2">
              <label htmlFor="email" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Email
              </label>
              <input
                type="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
          )}

          {(!isSignup || !isVerifying) && (
            <div className="space-y-2">
              <label htmlFor="password" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Password
              </label>
              <div className="relative">
                <input
                  type={showPassword ? "text" : "password"}
                  id="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                >
                  {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
              {!isSignup && (
                <div className="text-right">
                  <button
                    onClick={() => {
                      resetState();
                      setIsPasswordReset(true);
                    }}
                    className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                    type="button"
                  >
                    Forgot Password?
                  </button>
                </div>
              )}
            </div>
          )}

          {isSignup && !isVerifying && (
            <div className="space-y-2">
              <label htmlFor="confirmPassword" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                Confirm Password
              </label>
              <div className="relative">
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  id="confirmPassword"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400"
                >
                  {showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
            </div>
          )}

          {isSignup && isVerifying && (
            <>
              {emailSent && (
                <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg">
                  <p>We've sent a verification code to <span className="font-medium">{email}</span></p>
                  <p className="text-sm mt-1">Please check your inbox (and spam folder) for the code.</p>
                </div>
              )}
              <div className="space-y-2">
                <label htmlFor="verificationCode" className="block px-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                  Verification Code
                </label>
                <input
                  type="text"
                  id="verificationCode"
                  value={verificationCode}
                  onChange={(e) => setVerificationCode(e.target.value)}
                  className="w-full px-4 py-3 rounded-2xl border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-1 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-500/15 text-gray-900 dark:text-gray-100"
                  required
                  autoComplete="off"
                />
              </div>
            </>
          )}

          {authError && (
            <div className="text-red-500 text-sm bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
              {typeof authError === 'string' ? authError : 'An error occurred'}
            </div>
          )}

          <button
            type="submit"
            disabled={isSubmitting}
            className={`w-full py-3 px-4 rounded-lg shadow-md shadow-black/5 dark:shadow-lg dark:shadow-gray-800/35 dark:border-gray-700/75 bg-gray-100 border border-gray-400/30 dark:bg-gray-600/10 text-gray-900 dark:hover:border-gray-700/50 dark:text-gray-100 hover:shadow-none dark:hover:shadow-none duration-100 ${
              isSubmitting ? 'opacity-50 cursor-not-allowed' : ''
            }`}
          >
            {isSubmitting ? (
              <span className="inline-flex items-center">
                <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Processing...
              </span>
            ) : isSignup ? (
              isVerifying ? 'Verify Email' : 'Sign Up'
            ) : (
              'Log In'
            )}
          </button>
        </form>

        <div className="px-8 py-6 border-t border-gray-200 dark:border-gray-700 text-center">
          {isSignup ? (
            <p className="text-sm">
              Already have an account?{' '}
              <button
                onClick={() => {
                  resetState();
                  setIsSignup(false);
                }}
                className="text-blue-600 dark:text-blue-400 hover:underline"
                type="button"
              >
                Log In
              </button>
            </p>
          ) : (
            <p className="text-sm">
              Don't have an account?{' '}
              <button
                onClick={() => {
                  resetState();
                  setIsSignup(true);
                }}
                className="text-blue-600 dark:text-blue-400 hover:underline"
                type="button"
              >
                Sign Up
              </button>
            </p>
          )}
        </div>
      </div>
    </div>
  )
}