import React, { useState } from 'react';
import PasswordInput from './ui/password';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../services/AuthContext';
import loginBg from '../../public/images/salesbuddy_logo.jpg';

const Login = () => {

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();
  const { login } = useAuth();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);

    try {
      const response = await fetch('http://localhost:8000/token', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.detail || 'Login failed');
      }

      login(data.access_token);
      navigate('/');
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <>
      <div className="grid-container">
        <div className="column-a" style={{ backgroundImage: `url(${loginBg})` }}>
        </div>
        <div className="column-b">
          <div className="login-panel">

            <h6>Please provide your credentials:</h6>
            <input className="textbox" type="text" placeholder="User" onChange={(e) => setUsername(e.target.value)} />
            <PasswordInput onChange={(e) => setPassword(e.target.value)} />
            <button onClick={handleSubmit}>Sign In</button>
            <div style={{margin:"auto"}}>
            <Link to="/register" className="text-blue-600 hover:text-blue-500">
              Register?
            </Link>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Login;