import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'react-hot-toast'
import { useAuth } from '../context/useAuth.js'
import { FormCard } from '../components/FormCard.jsx'
import { Input } from '../components/Input.jsx'
import { PasswordInput } from '../components/PasswordInput.jsx'
import { Button } from '../components/Button.jsx'
import { Alert } from '../components/Alert.jsx'

export default function LoginPage() {
  const { login } = useAuth()
  const navigate = useNavigate()

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState(null)

  const validate = () => {
    if (!username.trim()) return 'Username is required'
    if (!password.trim()) return 'Password is required'
    return null
  }

  const onSubmit = async (e) => {
    e.preventDefault()
    const v = validate()
    if (v) {
      setError(v)
      return
    }

    setError(null)
    setSubmitting(true)
    try {
      await login({ username: username.trim(), password })
      toast.success('Login successful')
      navigate('/dashboard', { replace: true })
    } catch (err) {
      setError(err?.message || 'Login failed')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen px-4 py-10">
      <div className="mx-auto max-w-lg">
        <div className="mb-6 text-center">
          <h1 className="text-2xl font-bold text-slate-900">Welcome back</h1>
          <p className="mt-2 text-sm text-slate-600">Sign in to manage suppliers, shipments, deliveries and reports.</p>
        </div>

        <FormCard title="Login" description="Enter your credentials to continue.">
          {error ? <Alert type="error" message={error} /> : null}

          <form className="mt-5 space-y-4" onSubmit={onSubmit}>
            <Input label="Username" value={username} onChange={setUsername} placeholder="e.g. admin" />
            <PasswordInput label="Password" value={password} onChange={setPassword} />
            <Button type="submit" disabled={submitting} className="w-full">
              {submitting ? <span className="inline-flex items-center gap-2"><span className="h-4 w-4 animate-spin rounded-full border-2 border-white/60 border-t-white" /> Logging in…</span> : 'Login'}
            </Button>
          </form>

          <div className="mt-5 text-center text-sm text-slate-600">
            Don&apos;t have an account?{' '}
            <Link className="font-medium text-slate-900 hover:underline" to="/register">Create Account</Link>
          </div>
        </FormCard>
      </div>
    </div>
  )
}

