import React, { useEffect, useState } 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 { MockMangaRepository } from '../../infrastructure/api/mockMangaRepository.js';
import { GetMangaCollection } from '../../application/useCases/getMangaCollection.js';
import { 
  faRefresh, 
  faSearch,
  faGear,
  faEye,
  faSort,
  faFilter
} from '@fortawesome/free-solid-svg-icons';

const mangaRepository = new MockMangaRepository();
const getMangaCollection = new GetMangaCollection(mangaRepository);

export function HomePage() {
  const navigate = useNavigate();
  const [mangaCollection, setMangaCollection] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const handleRefresh = async () => {
    setLoading(true);
    try {
      const collection = await getMangaCollection.execute(1);
      setMangaCollection(collection);
    } catch (err) {
      setError('Failed to load mangas');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleMangaClick = (slug) => {
    navigate(`/manga/${slug}`);
  };

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

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

  if (loading) {
    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 onMangaClick={handleMangaClick} onAddMangaClick={handleAddMangaClick}>
      <Toolbar {...toolbarConfig} className="sticky top-16 z-10" />
      <div className="container mx-auto px-4">
        <MangaGrid mangas={mangaCollection.items} onMangaClick={handleMangaClick} />
      </div>
    </Layout>
  );
}