import React, { useState } from 'react'
import { Eye, EyeOff, X } from 'lucide-react'
import { useIsLoginModalOpen, useSetIsLoginModalOpen } from '../../contexts/UIContext'
import { useAuth } from '../../contexts/AuthContext'
import { useAppRoute } from '../../hooks/useAppRoute'
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 { openHomeRoute } = useAppRoute()

  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();
          return; // waiting on the emailed code — don't navigate yet
        }
        await signup(name, email, password, verificationCode);
      } else {
        await login(email, password);
      }
      // Successful login / completed signup → always land on the new chat page.
      openHomeRoute();
      handleClose();
    } 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="relative z-10 w-full max-w-md overflow-hidden rounded-2xl border border-app-border bg-app-surface shadow-2xl">
            <div className="flex items-center justify-between border-b border-app-border p-6">
              <h2 className="text-xl font-semibold text-app-text">
                Password Reset Successful
              </h2>
            </div>

            <div className="p-8 space-y-6">
              <div className="rounded-lg border border-success/25 bg-success/10 p-4 text-success-text">
                <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 rounded-lg bg-brand-button px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-button-hover"
              >
                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="relative z-10 w-full max-w-md overflow-hidden rounded-2xl border border-app-border bg-app-surface shadow-2xl">
          <div className="flex items-center justify-between border-b border-app-border p-6">
            <h2 className="text-xl font-semibold text-app-text">
              {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-app-text">
                  Email
                </label>
                <input
                  type="email"
                  id="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                  required
                />
              </div>
            )}

            {isVerifying && (
              <>
                {emailSent && (
                  <div className="mb-4 rounded-lg border border-brand/20 bg-brand-subtle p-4 text-brand-text">
                    <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-app-text">
                    Verification Code
                  </label>
                  <input
                    type="text"
                    id="resetVerificationCode"
                    value={resetVerificationCode}
                    onChange={(e) => setResetVerificationCode(e.target.value)}
                    className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                    required
                    autoComplete="off"
                  />
                </div>

                <div className="space-y-2">
                  <label htmlFor="newPassword" className="block px-1 text-sm font-medium text-app-text">
                    New Password
                  </label>
                  <div className="relative">
                    <input
                      type={showNewPassword ? "text" : "password"}
                      id="newPassword"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                      required
                    />
                    <button
                      type="button"
                      onClick={() => setShowNewPassword(!showNewPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-app-muted transition-colors hover:text-app-text"
                    >
                      {showNewPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                    </button>
                  </div>
                </div>
              </>
            )}

            {authError && (
              <div className="rounded-lg border border-danger/25 bg-danger/10 p-3 text-sm text-danger-text">
                {typeof authError === 'string' ? authError : 'An error occurred'}
              </div>
            )}

            <button
              type="submit"
              disabled={isSubmitting}
              className={`w-full rounded-lg bg-brand-button px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-button-hover ${
                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="border-t border-app-border px-8 py-6 text-center">
            <button
              onClick={() => {
                resetState();
                setIsPasswordReset(false);
                setIsSignup(false);
              }}
              className="font-medium text-brand-text 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="relative z-10 m-0 h-full w-full overflow-y-auto rounded-none border border-app-border bg-app-surface shadow-2xl sm:m-auto sm:h-auto sm:max-h-[85vh] sm:max-w-md sm:overflow-visible sm:rounded-2xl max-h-[100dvh]">
        <div className="sticky top-0 z-20">
          <div className="flex items-center justify-between border-b border-app-border bg-app-surface p-6 sm:rounded-t-2xl">
            <h2 className="text-xl font-semibold text-app-text">
              {isSignup ? (isVerifying ? 'Verify Email' : 'Sign Up') : 'Login'}
            </h2>
            <button
              onClick={handleClose}
              className="text-app-muted transition-colors hover:text-app-text"
              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-app-text">
                Full Name
              </label>
              <input
                type="text"
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                required
              />
            </div>
          )}

          {(!isVerifying) && (
            <div className="space-y-2">
              <label htmlFor="email" className="block px-1 text-sm font-medium text-app-text">
                Email
              </label>
              <input
                type="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                required
              />
            </div>
          )}

          {(!isSignup || !isVerifying) && (
            <div className="space-y-2">
              <label htmlFor="password" className="block px-1 text-sm font-medium text-app-text">
                Password
              </label>
              <div className="relative">
                <input
                  type={showPassword ? "text" : "password"}
                  id="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-app-muted transition-colors hover:text-app-text"
                >
                  {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
              {!isSignup && (
                <div className="text-right">
                  <button
                    onClick={() => {
                      resetState();
                      setIsPasswordReset(true);
                    }}
                    className="text-sm font-medium text-brand-text 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-app-text">
                Confirm Password
              </label>
              <div className="relative">
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  id="confirmPassword"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-app-muted transition-colors hover:text-app-text"
                >
                  {showConfirmPassword ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
            </div>
          )}

          {isSignup && isVerifying && (
            <>
              {emailSent && (
                <div className="mb-4 rounded-lg border border-brand/20 bg-brand-subtle p-4 text-brand-text">
                  <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-app-text">
                  Verification Code
                </label>
                <input
                  type="text"
                  id="verificationCode"
                  value={verificationCode}
                  onChange={(e) => setVerificationCode(e.target.value)}
                  className="w-full rounded-xl border border-app-border bg-app-surface px-4 py-3 text-sm text-app-text outline-none transition placeholder:text-app-muted focus:border-brand focus:ring-2 focus:ring-brand/25"
                  required
                  autoComplete="off"
                />
              </div>
            </>
          )}

          {authError && (
            <div className="rounded-lg border border-danger/25 bg-danger/10 p-3 text-sm text-danger-text">
              {typeof authError === 'string' ? authError : 'An error occurred'}
            </div>
          )}

          <button
            type="submit"
            disabled={isSubmitting}
            className={`w-full rounded-lg bg-brand-button px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-button-hover ${
              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="border-t border-app-border px-8 py-6 text-center">
          {isSignup ? (
            <p className="text-sm">
              Already have an account?{' '}
              <button
                onClick={() => {
                  resetState();
                  setIsSignup(false);
                }}
                className="font-medium text-brand-text hover:underline"
                type="button"
              >
                Log In
              </button>
            </p>
          ) : (
            <p className="text-sm">
              Don't have an account?{' '}
              <button
                onClick={() => {
                  resetState();
                  setIsSignup(true);
                }}
                className="font-medium text-brand-text hover:underline"
                type="button"
              >
                Sign Up
              </button>
            </p>
          )}
        </div>
      </div>
    </div>
  )
}