import type { PayloadAction } from '@reduxjs/toolkit';
import { createAppSlice } from '../../app/createAppSlice';
import type { Book, InputBook } from './Book';

export type BooksSliceState = {
  books: Book[];
  status: 'idle' | 'loading' | 'failed';
  removeStatus: 'idle' | 'loading' | 'failed';
};

export const booksSlice = createAppSlice({
  name: 'books',
  initialState: {
    books: [],
    status: 'idle',
    removeStatus: 'idle',
  } as BooksSliceState,
  reducers: (create) => ({
    remove: create.asyncThunk(
      async (id: number) => {
        const response = await fetch(`http://localhost:3001/books/${id}`, {
          method: 'DELETE',
        });
        if (!response.ok) {
          throw new Error('Failed to delete book');
        }
        return id;
      },
      {
        pending: (state) => {
          state.removeStatus = 'loading';
        },
        fulfilled: (state, action) => {
          state.removeStatus = 'idle';
          state.books = state.books.filter(
            (book) => book.id !== action.payload,
          );
        },
        rejected: (state) => {
          state.removeStatus = 'failed';
        },
      },
    ),
    save: create.reducer((state, action: PayloadAction<InputBook>) => {
      if (action.payload.id) {
        const index = state.books.findIndex((b) => b.id === action.payload.id);
        state.books[index] = {
          ...state.books[index],
          ...action.payload,
        };
      } else {
        const newBook = {
          ...action.payload,
          id: Math.max(0, ...state.books.map((b) => b.id)) + 1,
        };
        state.books.push(newBook);
      }
    }),
    loadData: create.asyncThunk(
      async () => {
        const response = await fetch('http://localhost:3001/books');
        if (!response.ok) {
          throw new Error('Failed to load books data');
        }
        return response.json();
      },
      {
        pending: (state) => {
          state.status = 'loading';
        },
        fulfilled: (state, action) => {
          state.status = 'idle';
          state.books = action.payload;
        },
        rejected: (state) => {
          state.status = 'failed';
        },
      },
    ),
  }),
  selectors: {
    selectAllBooks: (state) => state.books,
    selectBookById: (state) => (id: number) =>
      state.books.find((b) => b.id === id),
    selectStatus: (state) => state.status,
    selectRemoveStatus: (state) => state.removeStatus,
  },
});

export const {
  selectAllBooks,
  selectBookById,
  selectStatus,
  selectRemoveStatus,
} = booksSlice.selectors;
export const { remove, save, loadData } = booksSlice.actions;
