import { useState, type FormEvent } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { fetchDashboardRoute } from '../api/session'
import { useAuth } from '../auth/AuthProvider'
import { spaPathFromCiUrl } from '../lib/ciSpaPaths'
import { isParentPortalRole, isTeacherPortalRole } from '../lib/portalRoles'

export function LoginPage() {
  const { login } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  const locState = location.state as { from?: string; registered?: boolean; message?: string } | null

  const from = locState?.from ?? '/app/home'
  const flashMessage = locState?.message ?? null
  const flashVariant = locState?.registered === true ? 'success' : 'warning'

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setError(null)
    setBusy(true)
    try {
      const result = await login(email, password)
      if (result.ok === false) {
        setError(result.message)
        return
      }
      if (result.requiresRoleSelection) {
        navigate('/app/select-role', { replace: true, state: { from } })
        return
      }

      const singleRole = result.roles.length === 1 ? result.roles[0] : ''

      let target = '/app/home'
      if (from.startsWith('/app')) target = from
      else if (from.startsWith('/docs')) target = from

      if (result.roles.length === 1 && target === '/app/home') {
        if (isParentPortalRole(singleRole)) target = '/app/parent/home'
        if (isTeacherPortalRole(singleRole)) {
          target = '/app/teacher_dashboard'
        }
      }

      try {
        const dash = await fetchDashboardRoute()
        const route = dash.data?.dashboard?.route
        const mapped = spaPathFromCiUrl(route)
        if (mapped) target = mapped
      } catch {
        /* keep default */
      }

      /* API default dashboard can point parents at teacher URLs (or vice versa); honor single-role account. */
      if (result.roles.length === 1) {
        if (isTeacherPortalRole(singleRole)) {
          if (target === '/app/home' || target.startsWith('/app/parent')) {
            target = '/app/teacher_dashboard'
          }
        } else if (isParentPortalRole(singleRole)) {
          if (target === '/app/home' || target.startsWith('/app/teacher')) {
            target = '/app/parent/home'
          }
        }
      }

      navigate(target, { replace: true })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="ci-auth-bg flex-grow-1 py-4">
      <div className="registration-form ci-parity container mt-5 mb-5">
        <form id="loginForm" onSubmit={onSubmit}>
          <div className="text-center mb-4">
            <Link to="/">
              <img
                src="/alrahma_logo.png"
                alt=""
                style={{ width: 180, height: 120, objectFit: 'contain' }}
                onError={(ev) => {
                  ;(ev.target as HTMLImageElement).style.display = 'none'
                }}
              />
            </Link>
          </div>

          <h3
            className="text-center text-success mb-4"
            style={{ fontFamily: 'Arial, sans-serif' }}
          >
            Login to Your Account
          </h3>

          {flashMessage ? (
            <div className={`alert alert-${flashVariant} text-center`} role="alert">
              {flashMessage}
            </div>
          ) : null}

          <div className="mb-3">
            <label className="form-label visually-hidden" htmlFor="email">
              Email
            </label>
            <input
              type="email"
              className="form-control item"
              id="email"
              placeholder="Enter your email"
              maxLength={50}
              autoComplete="username"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>

          <div className="mb-4 position-relative">
            <label className="form-label visually-hidden" htmlFor="password">
              Password
            </label>
            <input
              type={showPassword ? 'text' : 'password'}
              className="form-control item pe-5"
              id="password"
              placeholder="Enter your password"
              maxLength={30}
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <button
              type="button"
              className="btn btn-link position-absolute top-50 end-0 translate-middle-y me-2 px-2 py-0 border-0"
              aria-label={showPassword ? 'Hide password' : 'Show password'}
              onClick={() => setShowPassword((v) => !v)}
            >
              <i className={`bi ${showPassword ? 'bi-eye-slash' : 'bi-eye'}`} aria-hidden />
            </button>
          </div>

          {error ? (
            <div className="alert alert-danger mt-3 text-center" role="alert">
              {error}
            </div>
          ) : null}

          <div className="mb-3 d-grid">
            <button type="submit" className="btn btn-success item" disabled={busy}>
              {busy ? 'Signing in…' : 'Login'}
            </button>
          </div>

          <div className="forgot-password text-center mt-3">
            <Link to="/forgot-password">Forgot Password?</Link>
          </div>

          <p className="text-center small mt-4 mb-0">
            Need an account? <Link to="/register">Register now</Link>
          </p>
        </form>
      </div>
    </div>
  )
}
