import React, { useState, useEffect } from "react";
import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import Home from "./components/Home";
import News from "./components/News";
import Manga from "./components/Manga";
import Author from "./components/Author";
import Reading from "./components/Reading";
import Account from "./components/Account";
import data from "../data.json"; // Используем только для авторов и статусов

function App() {
  const [books, setBooks] = useState([]);
  const [authors] = useState(data.authors);
  const [statuses] = useState(data.statuses);
  const [editingBook, setEditingBook] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("");

  // Загрузка книг с сервера
  useEffect(() => {
    fetch("http://localhost:5174/books")
      .then(res => res.json())
      .then(data => setBooks(data));
  }, []);

  // Добавить книгу
  const addBook = (book) => {
    fetch("http://localhost:5174/books", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(book)
    }).then(() => {
      fetch("http://localhost:5174/books")
        .then(res => res.json())
        .then(data => setBooks(data));
    });
  };

  // Удалить книгу
  const deleteBook = (id) => {
    fetch(`http://localhost:5174/books/${id}`, { method: "DELETE" })
      .then(() => {
        fetch("http://localhost:5174/books")
          .then(res => res.json())
          .then(data => setBooks(data));
      });
  };

  // Обновить книгу
  const updateBook = (book) => {
    fetch(`http://localhost:5174/books/${book.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(book)
    }).then(() => {
      fetch("http://localhost:5174/books")
        .then(res => res.json())
        .then(data => setBooks(data));
    });
  };

  // Фильтрация книг по поиску и статусу
  const filteredBooks = books.filter(book =>
    book.title.toLowerCase().includes(searchQuery.toLowerCase()) &&
    (statusFilter === "" ||
      statuses.find(s => String(s.id) === String(book.statusId))?.name === statusFilter)
  );

  return (
    <>
      <Navbar />
      <main className="container py-4">
        <Routes>
          <Route
            path="/"
            element={
              <Home
                books={filteredBooks}
                authors={authors}
                statuses={statuses}
                editingBook={editingBook}
                onAdd={addBook}
                onEdit={updateBook}
                onDelete={deleteBook}
                onCancel={() => setEditingBook(null)}
                setEditingBook={setEditingBook}
                searchQuery={searchQuery}
                setSearchQuery={setSearchQuery}
                statusFilter={statusFilter}
                setStatusFilter={setStatusFilter}
              />
            }
          />
          <Route path="/news" element={<News />} />
          <Route path="/manga/:id" element={<Manga />} />
          <Route path="/author/:id" element={<Author />} />
          <Route path="/reading/:id" element={<Reading />} />
          <Route path="/account" element={<Account />} />
        </Routes>
      </main>
      <Footer />
    </>
  );
}

export default App;
