import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Layout } from '../components/Layout/Layout';
import { Toolbar } from '../components/Toolbar/Toolbar';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft, faSearch, faStar } from '@fortawesome/free-solid-svg-icons';
import { MockMangaRepository } from '../../infrastructure/api/mockMangaRepository';
import { SearchMangas } from '../../application/useCases/searchMangas';

const mangaRepository = new MockMangaRepository();
const searchMangas = new SearchMangas(mangaRepository);

export function AddMangaPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const initialQuery = searchParams.get('q') || '';

  const [query, setQuery] = useState(initialQuery);
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedManga, setSelectedManga] = useState(null);

  useEffect(() => {
    if (initialQuery) {
      handleSearch(initialQuery);
    }
  }, [initialQuery]);

  const handleSearch = async (searchQuery) => {
    if (!searchQuery.trim()) {
      setResults([]);
      return;
    }

    setLoading(true);
    try {
      const searchResults = await searchMangas.execute(searchQuery);
      setResults(searchResults);
    } catch (error) {
      console.error('Search error:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

  const toolbarConfig = {
    leftSection: [
      { icon: faArrowLeft, onClick: () => navigate(-1) }
    ]
  };

  return (
    <Layout onMangaClick={handleMangaClick} onAddMangaClick={handleAddMangaClick}>
      <Toolbar {...toolbarConfig} className="sticky top-16 z-10" />
      
      <div className="container mx-auto px-4 py-6">
        <h1 className="text-2xl font-bold mb-6">Ajouter un manga</h1>
        
        <div className="bg-white rounded-lg shadow-sm p-6">
          <div className="max-w-3xl mx-auto">
            <div className="relative">
              <input
                type="text"
                value={query}
                onChange={(e) => {
                  setQuery(e.target.value);
                  handleSearch(e.target.value);
                }}
                placeholder="Rechercher un manga..."
                className="w-full px-4 py-2 pl-10 border-b border-gray-300 focus:border-green-600 outline-none transition-colors"
              />
              <FontAwesomeIcon 
                icon={faSearch} 
                className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
              />
            </div>

            {loading ? (
              <div className="text-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-2 border-green-600 border-t-transparent mx-auto"></div>
              </div>
            ) : results.length > 0 ? (
              <div className="space-y-4 mt-6">
                {results.map((manga) => (
                  <div
                    key={manga.id}
                    onClick={() => setSelectedManga(manga)}
                    className="flex gap-4 p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer"
                  >
                    <img
                      src={manga.imageUrl}
                      alt={manga.title}
                      className="w-24 h-36 object-cover rounded-lg shadow-sm"
                    />
                    <div className="flex-1">
                      <div className="flex items-start justify-between">
                        <div>
                          <h3 className="text-lg font-semibold text-gray-900">{manga.title}</h3>
                          <p className="text-gray-600">{manga.author}</p>
                        </div>
                        <div className="flex items-center text-yellow-500">
                          <FontAwesomeIcon icon={faStar} className="mr-1" />
                          <span>{manga.rating}</span>
                        </div>
                      </div>
                      <div className="mt-2">
                        <span className="text-sm text-gray-500">
                          {manga.publicationYear} • {manga.status}
                        </span>
                      </div>
                      <div className="mt-2 flex flex-wrap gap-2">
                        {manga.genres.map((genre, index) => (
                          <span
                            key={index}
                            className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full"
                          >
                            {genre}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : query && !loading && (
              <div className="text-center py-8 text-gray-500">
                Aucun résultat trouvé pour "{query}"
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Modal de confirmation */}
      {selectedManga && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4">
            <div className="p-6">
              <h2 className="text-xl font-semibold mb-4">Ajouter à la bibliothèque</h2>
              <div className="flex gap-4 mb-4">
                <img
                  src={selectedManga.imageUrl}
                  alt={selectedManga.title}
                  className="w-24 h-36 object-cover rounded"
                />
                <div>
                  <h3 className="font-semibold">{selectedManga.title}</h3>
                  <p className="text-gray-600">{selectedManga.author}</p>
                  <p className="text-sm text-gray-500 mt-2">
                    {selectedManga.genres.join(', ')}
                  </p>
                </div>
              </div>
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => setSelectedManga(null)}
                  className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  Annuler
                </button>
                <button
                  onClick={() => {
                    handleMangaClick(selectedManga.slug);
                    setSelectedManga(null);
                  }}
                  className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                >
                  Ajouter
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Layout>
  );
}