import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { authAPI } from '../services/api'

import AuthShell from './AuthShell'

function Login({ onLogin }) {
  const [UserName, setUserName] = useState('')
  const [Password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()


  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      const res = await authAPI.login({ UserName, Password })
      onLogin(res.data.user)
      navigate('/')
    } catch (err) {
      setError(err.response?.data?.message || 'Login failed')
    } finally {
      setLoading(false)
    }
  }

  return (
    <AuthShell
      title="HRMS"
      subtitle="Sign in to your account"
      footer={
        <span>
          Don't have an account?{' '}
          <Link to="/register" className="text-teal-600 hover:text-teal-500">
            Register
          </Link>
        </span>
      }
    >
      {error ? (
        <div className="mb-5 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          {error}
        </div>
      ) : null}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <label className="label">Username</label>
          <input
            type="text"
            className="input"
            placeholder="Username"
            value={UserName}
            onChange={(e) => setUserName(e.target.value)}
            required
            autoComplete="username"
          />
        </div>

        <div className="space-y-2">
          <label className="label">Password</label>
          <input
            type="password"
            className="input"
            placeholder="Password"
            value={Password}
            onChange={(e) => setPassword(e.target.value)}
            required
            autoComplete="current-password"
          />
        </div>

        <button
          type="submit"
          disabled={loading}
          className="btn btn-teal w-full disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {loading ? 'Signing in...' : 'Sign In'}
        </button>
      </form>
    </AuthShell>
  )
}

export default Login
