import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { getAuthToken } from "../api.jsx";
import { getTrucks, createTruck, updateTruck, deleteTruck } from "../api.jsx";

const Trucks = () => {
  const [trucks, setTrucks] = useState([]);
  const [newTruck, setNewTruck] = useState({
    name: "",
    capacity: "",
    volume: "",
  });
  const [editingTruckId, setEditingTruckId] = useState(null);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    fetchTrucks();
  }, []);

  const fetchTrucks = async () => {
    try {
      const data = await getTrucks();
      setTrucks(data);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        navigate("/login");
      }
      console.error("Ошибка при загрузке грузовиков:", error);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setNewTruck({ ...newTruck, [name]: value });
  };

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

    if (!newTruck.name || !newTruck.capacity || !newTruck.volume) {
      setError("Пожалуйста, заполните все поля.");
      return;
    }

    try {
      if (editingTruckId) {
        await updateTruck(editingTruckId, newTruck);
      } else {
        await createTruck(newTruck);
      }
      fetchTrucks();
      resetForm();
    } catch (error) {
      console.error("Ошибка при добавлении или обновлении грузовика:", error);
    }
  };

  const handleEdit = (truck) => {
    setNewTruck({
      name: truck.name,
      capacity: truck.capacity,
      volume: truck.volume,
    });
    setEditingTruckId(truck.id);
  };

  const handleDelete = async (truckId) => {
    try {
      await deleteTruck(truckId);
      fetchTrucks();
    } catch (error) {
      console.error("Ошибка при удалении грузовика:", error);
    }
  };

  const resetForm = () => {
    setNewTruck({
      name: "",
      capacity: "",
      volume: "",
    });
    setEditingTruckId(null);
  };

  if (getAuthToken() === null) {
    navigate("/login");
  }

  return (
    <div className="container mt-4">
      <h3>Грузовики</h3>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="truckName">Название грузовика</label>
          <input
            type="text"
            className="form-control"
            id="truckName"
            name="name"
            placeholder="Введите название грузовика"
            value={newTruck.name}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-group">
          <label htmlFor="truckCapacity">Грузоподъемность (тонны)</label>
          <input
            type="number"
            className="form-control"
            id="truckCapacity"
            name="capacity"
            placeholder="Введите грузоподъемность"
            value={newTruck.capacity}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-group">
          <label htmlFor="truckVolume">Объем (кубометры)</label>
          <input
            type="number"
            className="form-control"
            id="truckVolume"
            name="volume"
            placeholder="Введите объем"
            value={newTruck.volume}
            onChange={handleInputChange}
          />
        </div>

        <div className="btn-group">
          <button type="submit" className="btn btn-primary">
            {editingTruckId ? "Обновить" : "Создать"}
          </button>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={resetForm}
          >
            Отменить
          </button>
        </div>
        {error && (
          <div className="alert alert-danger mt-3" role="alert">
            {error}
          </div>
        )}
      </form>
      <h3 className="mt-5">Список грузовиков</h3>
      <table className="table table-bordered">
        <thead>
          <tr>
            <th>Название</th>
            <th>Грузоподъемность</th>
            <th>Объем</th>
            <th>Действия</th>
          </tr>
        </thead>
        <tbody>
          {trucks.map((truck) => (
            <tr key={truck.id}>
              <td>{truck.name}</td>
              <td>{truck.capacity}</td>
              <td>{truck.volume}</td>
              <td>
                <div className="btn-group">
                  <button
                    className="btn btn-warning"
                    onClick={() => handleEdit(truck)}
                  >
                    Изменить
                  </button>
                  <button
                    className="btn btn-danger"
                    onClick={() => handleDelete(truck.id)}
                  >
                    Удалить
                  </button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Trucks;
