// frontend/src/components/LoginForm.jsx
import { useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
console.log("API_BASE_URL:", import.meta.env.VITE_API_BASE_URL);

const LoginForm = ({ onLogin }) => {
  const [isRegistering, setIsRegistering] = useState(false);
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    first_name: '',
    last_name: '',
    organization: '',
    address: '',
    city: '',
    state: '',
    zip_code: '',
    phone: ''
  });

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

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

    if (isRegistering) {
      // Handle user registration
      try {
        await axios.post(`${API_BASE_URL}/api/auth/register`, formData);
        alert('Registration successful. Please log in.');
        setIsRegistering(false);
      } catch (error) {
        alert('Registration failed. ' + (error.response?.data?.message || error.message));
      }
    } else {
      // Handle user login
      try {
        const response = await axios.post(`${API_BASE_URL}/api/auth/login`, {
          email: formData.email,
          password: formData.password
        });
        localStorage.setItem('token', response.data.token);
        onLogin();
      } catch (error) {
        alert('Login failed. Please check your credentials.');
      }
    }
  };

  return (
    <div className="container mt-5">
      <h2>{isRegistering ? 'Register' : 'Login'}</h2>
      <form onSubmit={handleSubmit}>
        <div className="mb-3">
          <label>Email:</label>
          <input
            type="email"
            className="form-control"
            name="email"
            value={formData.email}
            onChange={handleChange}
            required
          />
        </div>
        <div className="mb-3">
          <label>Password:</label>
          <input
            type="password"
            className="form-control"
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
          />
        </div>

        {isRegistering && (
          <>
            <div className="mb-3">
              <label>First Name:</label>
              <input type="text" className="form-control" name="first_name" value={formData.first_name} onChange={handleChange} required />
            </div>
            <div className="mb-3">
              <label>Last Name:</label>
              <input type="text" className="form-control" name="last_name" value={formData.last_name} onChange={handleChange} required />
            </div>
            <div className="mb-3">
              <label>Organization:</label>
              <input type="text" className="form-control" name="organization" value={formData.organization} onChange={handleChange} />
            </div>
            <div className="mb-3">
              <label>Address:</label>
              <input type="text" className="form-control" name="address" value={formData.address} onChange={handleChange} />
            </div>
            <div className="mb-3">
              <label>City:</label>
              <input type="text" className="form-control" name="city" value={formData.city} onChange={handleChange} />
            </div>
            <div className="mb-3">
              <label>State:</label>
              <input type="text" className="form-control" name="state" value={formData.state} onChange={handleChange} />
            </div>
            <div className="mb-3">
              <label>ZIP Code:</label>
              <input type="text" className="form-control" name="zip_code" value={formData.zip_code} onChange={handleChange} />
            </div>
            <div className="mb-3">
              <label>Phone:</label>
              <input type="text" className="form-control" name="phone" value={formData.phone} onChange={handleChange} />
            </div>
          </>
        )}

        <button type="submit" className="btn btn-primary">
          {isRegistering ? 'Register' : 'Login'}
        </button>

        {import.meta.env.DEV ? (
          <button
            type="button"
            className="btn btn-link mt-2"
            onClick={() => setIsRegistering(!isRegistering)}
          >
            {isRegistering ? 'Already have an account? Login' : 'New here? Register'}
          </button>
        ) : (
          <p className="mt-2">
            New here? Register (Registration is currently disabled)
          </p>
        )}
      </form>
    </div>
  );
};

export default LoginForm;

