import { useState, useCallback } from 'react';
import { validateTOCEntry } from '@/lib/tocUtils';

export function useTableOfContents(initialEntries = []) {
  const [entries, setEntries] = useState(initialEntries);
  const [errors, setErrors] = useState({});

  const addEntry = useCallback((entry) => {
    const validationErrors = validateTOCEntry(entry, entries);
    if (validationErrors) {
      setErrors(validationErrors);
      return false;
    }

    const newEntry = {
      id: crypto.randomUUID(),
      ...entry,
      pageNumber: parseInt(entry.pageNumber, 10)
    };

    setEntries(prev => [...prev, newEntry]);
    setErrors({});
    return true;
  }, [entries]);

  const updateEntry = useCallback((id, updates) => {
    if (updates.pageNumber !== undefined) {
       const pageError = validateTOCEntry({ ...updates, pageNumber: updates.pageNumber }).pageNumber;
       if (pageError) {
         setErrors({ pageNumber: pageError });
         return false;
       }
    }

    setEntries(prev => prev.map(item => 
      item.id === id ? { ...item, ...updates, pageNumber: updates.pageNumber ? parseInt(updates.pageNumber, 10) : item.pageNumber } : item
    ));
    setErrors({});
    return true;
  }, []);

  const deleteEntry = useCallback((id) => {
    setEntries(prev => prev.filter(item => item.id !== id));
  }, []);

  const reorderEntries = useCallback((newOrder) => {
    setEntries(newOrder);
  }, []);

  const setAllEntries = useCallback((newEntries) => {
    setEntries(newEntries || []);
  }, []);

  return {
    entries,
    errors,
    addEntry,
    updateEntry,
    deleteEntry,
    reorderEntries,
    setAllEntries
  };
}
