import React, { useState } from "react";
import {useNavigate} from 'react-router-dom'
import axios from '../axiosInstance'

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();
  
  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const res = await axios.post('http://localhost:5000/api/user/login', { email, password });
      localStorage.setItem("token", res.data.token);
      navigate("/dshboard");
      window.location.reload();
    } catch (error) {
      if(error.response && error.response.data){
        setError(error.response.data.message);
      }else{
        setError("Failed to login. Please check your details.")
      }
    }
  };

  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center bg-slate-950 px-4">
      <div className="bg-slate-900 border border-slate-800 text-white p-8 rounded-2xl w-full max-w-md shadow-2xl space-y-6">
        <div className="text-center">
          <h2 className="text-3xl font-black text-blue-500">Welcome Back</h2>
          <p className="text-sm text-slate-400 mt-2">Sign in to your administration panel</p>
        </div>

        {error && (
          <div className="bg-rose-950 border border-rose-800 text-rose-300 text-xs p-3 rounded-xl font-medium">
            {error}
          </div>
        )}

        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="text-xs font-bold uppercase tracking-wider text-slate-400 block mb-1">Email Address</label>
            <input 
              type="email" 
              placeholder="Enter your email" 
              className="w-full bg-slate-800 border border-slate-700 p-3 rounded-xl text-sm focus:outline-none focus:border-blue-500 transition"
              required
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>

          <div>
            <label className="text-xs font-bold uppercase tracking-wider text-slate-400 block mb-1">Password</label>
            <input 
              type="password" 
              placeholder="Enter your password" 
              className="w-full bg-slate-800 border border-slate-700 p-3 rounded-xl text-sm focus:outline-none focus:border-blue-500 transition"
              required
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>

          <button type="submit" className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl transition shadow-lg shadow-blue-900/20">
            Login
          </button>
          
          <p className="text-center text-xs text-slate-400 pt-2">
            Don't have an account? <a href="/register" className="text-blue-400 hover:underline font-semibold">Register</a>
          </p>
        </form>
      </div>
    </div>
  );
}
