import { useState } from 'react'
import { useAuth } from './AuthProvider.tsx'
import '../styles/auth.css'

interface AuthModalProps {
  onClose: () => void
  /** When true, forces password re-entry (device renewal) instead of full login */
  renewalMode?: boolean
}

export function AuthModal({ onClose, renewalMode = false }: AuthModalProps) {
  const auth = useAuth()
  const [mode, setMode] = useState<'signin' | 'signup'>(renewalMode ? 'signin' : 'signin')
  const [email, setEmail] = useState(renewalMode ? (auth.user?.email ?? '') : '')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [signupSuccess, setSignupSuccess] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setLoading(true)

    if (mode === 'signup') {
      const result = await auth.signUp(email, password)
      if (result.error) {
        setError(result.error)
      } else {
        setSignupSuccess(true)
      }
    } else {
      const result = await auth.signIn(email, password)
      if (result.error) {
        setError(result.error)
      } else {
        onClose()
      }
    }

    setLoading(false)
  }

  if (signupSuccess) {
    return (
      <div className="auth-backdrop" onClick={onClose}>
        <div className="auth-modal" onClick={e => e.stopPropagation()}>
          <h2>Check your email</h2>
          <p className="auth-success-msg">
            We sent a confirmation link to <strong>{email}</strong>.
            Click the link to activate your account, then sign in.
          </p>
          <button className="auth-btn auth-btn-primary" onClick={onClose}>
            Got it
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="auth-backdrop" onClick={renewalMode ? undefined : onClose}>
      <div className="auth-modal" onClick={e => e.stopPropagation()}>
        <h2>{renewalMode ? 'Re-enter password' : mode === 'signin' ? 'Sign In' : 'Create Account'}</h2>
        {renewalMode && (
          <p className="auth-renewal-msg">
            Your session on this device has expired. Please re-enter your password.
          </p>
        )}

        <form onSubmit={handleSubmit}>
          <div className="auth-field">
            <label htmlFor="auth-email">Email</label>
            <input
              id="auth-email"
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              disabled={renewalMode}
              required
              autoFocus={!renewalMode}
              autoComplete="email"
            />
          </div>

          <div className="auth-field">
            <label htmlFor="auth-password">Password</label>
            <input
              id="auth-password"
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
              autoFocus={renewalMode}
              autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
              minLength={6}
            />
          </div>

          {error && <p className="auth-error">{error}</p>}

          <button className="auth-btn auth-btn-primary" type="submit" disabled={loading}>
            {loading ? 'Loading...' : renewalMode ? 'Confirm' : mode === 'signin' ? 'Sign In' : 'Create Account'}
          </button>
        </form>

        {!renewalMode && (
          <p className="auth-toggle">
            {mode === 'signin' ? (
              <>Don&apos;t have an account?{' '}<button className="auth-link" onClick={() => { setMode('signup'); setError(null) }}>Sign up</button></>
            ) : (
              <>Already have an account?{' '}<button className="auth-link" onClick={() => { setMode('signin'); setError(null) }}>Sign in</button></>
            )}
          </p>
        )}

        {!renewalMode && (
          <button className="auth-close" onClick={onClose} aria-label="Close" title="Close">
            &times;
          </button>
        )}
      </div>
    </div>
  )
}
