import React, { useState, useContext } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import api from '../api'
import { AuthContext } from '../context/AuthContext'
import Toast from '../components/Toast'
import Modal from '../components/Modal'
import '../styles/global.css'

export default function Login() {
  const navigate = useNavigate()
  const { setUser, setToken } = useContext(AuthContext)
  const [formData, setFormData] = useState({
    identifier: '',
    password: '',
  })
  const [loading, setLoading] = useState(false)
  const [toast, setToast] = useState(null)
  const [showForgotPassword, setShowForgotPassword] = useState(false)
  const [showPinEntry, setShowPinEntry] = useState(false)
  const [showChangePassword, setShowChangePassword] = useState(false)
  const [resetEmail, setResetEmail] = useState('')
  const [resetPin, setResetPin] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [resetLoading, setResetLoading] = useState(false)
  const [currentUserData, setCurrentUserData] = useState(null)

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setLoading(true)

    try {
      const response = await api.post('/auth/login', {
        identifier: formData.identifier,
        password: formData.password,
      })

      // Check if user must change password
      if (response.data.user.must_change_password) {
        setCurrentUserData({ token: response.data.access_token, user: response.data.user })
        setShowChangePassword(true)
        setToast({ type: 'warning', message: 'You must change your password before continuing' })
      } else {
        setToken(response.data.access_token)
        setUser(response.data.user)
        setToast({ type: 'success', message: 'Login successful!' })
        setTimeout(() => navigate('/'), 1000)
      }
    } catch (error) {
      setToast({ type: 'error', message: 'Invalid credentials' })
      console.error('Login error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleForgotPassword = async (e) => {
    e.preventDefault()
    setResetLoading(true)

    try {
      const response = await api.post('/auth/request-reset-pin', { email: resetEmail })
      setToast({ type: 'success', message: 'A PIN has been sent to your email!' })
      setShowForgotPassword(false)
      setShowPinEntry(true)
      // For testing - show the PIN from response (remove in production)
      if (response.data.pin) {
        console.log('Reset PIN:', response.data.pin)
      }
    } catch (error) {
      setToast({ type: 'error', message: 'Error sending PIN. Please try again.' })
      console.error('Forgot password error:', error)
    } finally {
      setResetLoading(false)
    }
  }

  const handleResetWithPin = async (e) => {
    e.preventDefault()
    setResetLoading(true)

    try {
      await api.post('/auth/reset-password-with-pin', {
        email: resetEmail,
        pin: resetPin,
        new_password: newPassword
      })
      setToast({ type: 'success', message: 'Password reset successful! Please login.' })
      setShowPinEntry(false)
      setResetEmail('')
      setResetPin('')
      setNewPassword('')
    } catch (error) {
      setToast({ type: 'error', message: error.response?.data?.detail || 'Invalid PIN or request expired' })
      console.error('Reset password error:', error)
    } finally {
      setResetLoading(false)
    }
  }

  const handleChangePassword = async (e) => {
    e.preventDefault()
    setResetLoading(true)

    try {
      // Set token temporarily for this request
      const tempToken = currentUserData.token
      await api.post('/auth/change-password', 
        {
          old_password: formData.password,
          new_password: newPassword
        },
        {
          headers: { Authorization: `Bearer ${tempToken}` }
        }
      )
      
      // Login with new credentials
      setToken(currentUserData.token)
      setUser(currentUserData.user)
      setToast({ type: 'success', message: 'Password changed successfully!' })
      setShowChangePassword(false)
      setTimeout(() => navigate('/'), 1000)
    } catch (error) {
      setToast({ type: 'error', message: error.response?.data?.detail || 'Error changing password' })
      console.error('Change password error:', error)
    } finally {
      setResetLoading(false)
    }
  }

  return (
    <div className="auth-page">
      <div className="auth-container">
        <h1>Login</h1>

        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label>Email, Username, or Phone</label>
            <input
              type="text"
              name="identifier"
              value={formData.identifier}
              onChange={handleChange}
              placeholder="Enter email, username, or phone"
              required
            />
          </div>

          <div className="form-group">
            <label>Password</label>
            <input
              type="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              required
            />
          </div>

          <div className="forgot-password-link">
            <button
              type="button"
              className="link-button"
              onClick={() => setShowForgotPassword(true)}
            >
              Forgot Password?
            </button>
          </div>

          <button type="submit" className="btn btn-full" disabled={loading}>
            {loading ? 'Logging in...' : 'Login'}
          </button>
        </form>

        <p className="auth-switch">
          Don't have an account? <Link to="/register">Sign up here</Link>
        </p>
      </div>

      {/* Forgot Password Modal */}
      <Modal
        isOpen={showForgotPassword}
        onClose={() => setShowForgotPassword(false)}
        title="Reset Password"
      >
        <form onSubmit={handleForgotPassword}>
          <p className="modal-description">
            Enter your email address and we'll send you a 6-digit PIN to reset your password.
          </p>
          <div className="form-group">
            <label>Email</label>
            <input
              type="email"
              value={resetEmail}
              onChange={(e) => setResetEmail(e.target.value)}
              placeholder="your@email.com"
              required
            />
          </div>
          <button type="submit" className="btn btn-full" disabled={resetLoading}>
            {resetLoading ? 'Sending...' : 'Send PIN'}
          </button>
        </form>
      </Modal>

      {/* PIN Entry Modal */}
      <Modal
        isOpen={showPinEntry}
        onClose={() => setShowPinEntry(false)}
        title="Enter PIN"
      >
        <form onSubmit={handleResetWithPin}>
          <p className="modal-description">
            Enter the 6-digit PIN sent to {resetEmail} and your new password.
          </p>
          <div className="form-group">
            <label>6-Digit PIN</label>
            <input
              type="text"
              value={resetPin}
              onChange={(e) => setResetPin(e.target.value.replace(/\D/g, '').slice(0, 6))}
              placeholder="123456"
              maxLength="6"
              required
            />
          </div>
          <div className="form-group">
            <label>New Password</label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="Enter new password"
              required
            />
          </div>
          <button type="submit" className="btn btn-full" disabled={resetLoading}>
            {resetLoading ? 'Resetting...' : 'Reset Password'}
          </button>
        </form>
      </Modal>

      {/* Force Password Change Modal */}
      <Modal
        isOpen={showChangePassword}
        onClose={() => {}} // Cannot close - must change password
        title="Change Password Required"
      >
        <form onSubmit={handleChangePassword}>
          <p className="modal-description">
            For security reasons, you must change your password before continuing.
          </p>
          <div className="form-group">
            <label>New Password</label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="Enter new password"
              minLength="6"
              required
            />
          </div>
          <button type="submit" className="btn btn-full" disabled={resetLoading}>
            {resetLoading ? 'Changing...' : 'Change Password'}
          </button>
        </form>
      </Modal>

      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  )
}
