import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { getAuthToken } from "../api.jsx";
import {
  getFederalDistricts,
  createFederalDistrict,
  updateFederalDistrict,
  deleteFederalDistrict,
} from "../api.jsx";

const FederalDistricts = () => {
  const [districts, setDistricts] = useState([]);
  const [newDistrict, setNewDistrict] = useState({
    name: "",
  });
  const [editingDistrictId, setEditingDistrictId] = useState(null);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

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

  const fetchFederalDistricts = async () => {
    try {
      const data = await getFederalDistricts();
      setDistricts(data);
    } catch (error) {
      console.error("Ошибка при загрузке федеральных округов:", error);
    }
  };

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

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

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

    try {
      if (editingDistrictId) {
        await updateFederalDistrict(editingDistrictId, newDistrict);
      } else {
        await createFederalDistrict(newDistrict);
      }
      fetchFederalDistricts();
      resetForm();
    } catch (error) {
      console.error(
        "Ошибка при добавлении или обновлении федерального округа:",
        error
      );
    }
  };

  const handleEdit = (district) => {
    setNewDistrict({
      name: district.name,
    });
    setEditingDistrictId(district.id);
  };

  const handleDelete = async (districtId) => {
    try {
      await deleteFederalDistrict(districtId);
      fetchFederalDistricts();
    } catch (error) {
      console.error("Ошибка при удалении федерального округа:", error);
    }
  };

  const resetForm = () => {
    setNewDistrict({
      name: "",
    });
    setEditingDistrictId(null);
  };

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

  return (
    <div className="container mt-4">
      <h3>Федеральные округа</h3>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="districtName">Название округа</label>
          <input
            type="text"
            className="form-control"
            id="districtName"
            name="name"
            placeholder="Введите название округа"
            value={newDistrict.name}
            onChange={handleInputChange}
          />
        </div>

        <div className="btn-group">
          <button type="submit" className="btn btn-primary">
            {editingDistrictId ? "Обновить" : "Создать"}
          </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>ID</th>
            <th>Название</th>
            <th>Действия</th>
          </tr>
        </thead>
        <tbody>
          {districts.map((district) => (
            <tr key={district.id}>
              <td>{district.id}</td>
              <td>{district.name}</td>
              <td>
                <div className="btn-group">
                  <button
                    className="btn btn-warning"
                    onClick={() => handleEdit(district)}
                  >
                    Изменить
                  </button>
                  <button
                    className="btn btn-danger"
                    onClick={() => handleDelete(district.id)}
                  >
                    Удалить
                  </button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default FederalDistricts;
