import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { MangaGrid } from '../components/MangaGrid.jsx';
import { Layout } from '../components/Layout/Layout.jsx';
import { Toolbar } from '../components/Toolbar/Toolbar.jsx';
import { useManga } from '../context/MangaContext.jsx';
import { 
  faRefresh, 
  faSearch,
  faGear,
  faEye,
  faSort,
  faFilter
} from '@fortawesome/free-solid-svg-icons';

export function HomePage() {
  const navigate = useNavigate();
  const { 
    collection, 
    loading, 
    error, 
    isBackgroundLoading,
    loadCollection, 
    refreshCollectionInBackground 
  } = useManga();

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

  const handleAddMangaClick = (query = '') => {
    navigate(`/add${query ? `?q=${encodeURIComponent(query)}` : ''}`);
  };

  const toolbarConfig = {
    leftSection: [
      { 
        icon: faRefresh, 
        label: 'Refresh', 
        onClick: refreshCollectionInBackground,
        active: isBackgroundLoading
      },
      { icon: faSearch, label: 'Search', onClick: () => {} }
    ],
    rightSection: [
      { icon: faGear, onClick: () => {} },
      { icon: faEye, onClick: () => {} },
      { icon: faSort, onClick: () => {} },
      { icon: faFilter, onClick: () => {} }
    ]
  };

  if (loading && !collection) {
    return <div className="flex justify-center items-center h-screen">Loading...</div>;
  }

  if (error) {
    return <div className="text-red-500 text-center p-4">{error}</div>;
  }

  return (
    <Layout onAddMangaClick={handleAddMangaClick}>
      <Toolbar {...toolbarConfig} className="sticky top-16 z-10" />
      <div className="container mx-auto px-4">
        <MangaGrid mangas={collection?.items || []} />
        {isBackgroundLoading && (
          <div className="fixed bottom-4 right-4 bg-gray-800 text-white px-4 py-2 rounded-lg shadow-lg">
            Mise à jour en cours...
          </div>
        )}
      </div>
    </Layout>
  );
}