import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
} from 'react'

const STORAGE_KEY = 'librairie-books'

const demoBooks = [
  {
    id: '1',
    title: 'Le Petit Prince',
    author: 'Antoine de Saint-Exupéry',
    year: 1943,
    genre: 'Conte',
    price: 8.5,
    read: true,
  },
  {
    id: '2',
    title: '1984',
    author: 'George Orwell',
    year: 1949,
    genre: 'Science-fiction',
    price: 9.9,
    read: false,
  },
]

function normalizeBook(b) {
  const price = Number(b?.price)
  return {
    ...b,
    price: Number.isFinite(price) ? price : 10,
  }
}

function loadBooks() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (raw === null) return demoBooks
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? parsed.map(normalizeBook) : demoBooks
  } catch {
    return demoBooks
  }
}

function saveBooks(books) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(books))
}

const BooksContext = createContext(null)

export function BooksProvider({ children }) {
  const [books, setBooks] = useState(loadBooks)

  useEffect(() => {
    saveBooks(books)
  }, [books])

  /** Équivalent métier d’un POST /api/books (ici : persistance locale + id généré). */
  const postBook = useCallback((book) => {
    const id = crypto.randomUUID()
    setBooks((prev) => [...prev, normalizeBook({ ...book, id })])
  }, [])

  const removeBook = useCallback((id) => {
    setBooks((prev) => prev.filter((b) => b.id !== id))
  }, [])

  const toggleRead = useCallback((id) => {
    setBooks((prev) =>
      prev.map((b) => (b.id === id ? { ...b, read: !b.read } : b)),
    )
  }, [])

  const value = { books, postBook, removeBook, toggleRead }

  return (
    <BooksContext.Provider value={value}>{children}</BooksContext.Provider>
  )
}

export function useBooks() {
  const ctx = useContext(BooksContext)
  if (!ctx) {
    throw new Error('useBooks doit être utilisé dans un BooksProvider')
  }
  return ctx
}
