import React, { useState } from 'react';
import { FaSearch, FaSpinner } from 'react-icons/fa';

const TMDBImportModal = ({ onClose, onImport }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const searchTMDB = async (query) => {
    if (!query.trim()) return;

    setLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `https://api.themoviedb.org/3/search/multi?api_key=ba3a2d0e9b1ceaf29511da9f2d26bf91&query=${encodeURIComponent(query)}&language=ru-RU`,
        {
          headers: {
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJiYTNhMmQwZTliMWNlYWYyOTUxMWRhOWYyZDI2YmY5MSIsIm5iZiI6MTc0NTc0MjkwNy4yMTQwMDAyLCJzdWIiOiI2ODBkZWMzYjE2MzVkMjkxOGM4MGZkN2IiLCJzY29wZXMiOlsiYXBpX3JlYWQiXSwidmVyc2lvbiI6MX0.xHuQc27ZvJWzl1oLdBK50nMSxNsETd863gjnDnOuyCU'
          }
        }
      );

      if (!response.ok) {
        throw new Error('Ошибка при поиске в TMDB');
      }

      const data = await response.json();
      setSearchResults(data.results.filter(item => item.media_type === 'movie' || item.media_type === 'tv'));
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (e) => {
    e.preventDefault();
    searchTMDB(searchQuery);
  };

  const handleImport = async (item) => {
    try {
      setLoading(true);
      setError(null);

      // Получаем детальную информацию о фильме/сериале
      const response = await fetch(
        `https://api.themoviedb.org/3/${item.media_type}/${item.id}?api_key=ba3a2d0e9b1ceaf29511da9f2d26bf91&language=ru-RU`,
        {
          headers: {
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJiYTNhMmQwZTliMWNlYWYyOTUxMWRhOWYyZDI2YmY5MSIsIm5iZiI6MTc0NTc0MjkwNy4yMTQwMDAyLCJzdWIiOiI2ODBkZWMzYjE2MzVkMjkxOGM4MGZkN2IiLCJzY29wZXMiOlsiYXBpX3JlYWQiXSwidmVyc2lvbiI6MX0.xHuQc27ZvJWzl1oLdBK50nMSxNsETd863gjnDnOuyCU'
          }
        }
      );

      if (!response.ok) {
        throw new Error('Ошибка при получении деталей');
      }

      const details = await response.json();

      // Формируем данные для импорта
      const importData = {
        title: details.title || details.name,
        path: (details.title || details.name).toLowerCase().replace(/[^a-z0-9]+/g, '-'),
        type: item.media_type === 'movie' ? 'movie' : 'tv',
        overview: details.overview,
        release_date: details.release_date || details.first_air_date,
        poster_path: details.poster_path,
        backdrop_path: details.backdrop_path,
        tmdb_id: details.id,
        tmdb_type: item.media_type
      };

      onImport(importData);
      onClose();
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6 bg-campfire-charcoal rounded-lg shadow-md text-campfire-light">
      <h2 className="text-2xl font-bold mb-6">Импорт из TMDB</h2>

      <form onSubmit={handleSearch} className="mb-6">
        <div className="flex gap-2">
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Поиск фильмов и сериалов..."
            className="flex-1 input px-3 py-2 bg-campfire-dark text-campfire-light border border-campfire-ash/30 rounded-md focus:outline-none focus:ring-campfire-amber focus:border-campfire-amber"
          />
          <button
            type="submit"
            disabled={loading}
            className="btn-primary flex items-center gap-2"
          >
            {loading ? <FaSpinner className="animate-spin" /> : <FaSearch />}
            <span>Поиск</span>
          </button>
        </div>
      </form>

      {error && (
        <div className="bg-status-error/20 text-status-error p-4 rounded-md mb-6">
          {error}
        </div>
      )}

      {searchResults.length > 0 && (
        <div className="space-y-4 max-h-[60vh] overflow-y-auto custom-scrollbar">
          {searchResults.map((item) => (
            <div
              key={item.id}
              className="flex items-center gap-4 p-4 bg-campfire-dark rounded-lg hover:bg-campfire-ash/20 transition-colors"
            >
              {item.poster_path && (
                <img
                  src={`https://image.tmdb.org/t/p/w92${item.poster_path}`}
                  alt={item.title || item.name}
                  className="w-16 h-24 object-cover rounded"
                />
              )}
              <div className="flex-1">
                <h3 className="font-semibold">{item.title || item.name}</h3>
                <p className="text-sm text-campfire-ash">
                  {item.media_type === 'movie' ? 'Фильм' : 'Сериал'} •{' '}
                  {new Date(item.release_date || item.first_air_date).getFullYear()}
                </p>
              </div>
              <button
                onClick={() => handleImport(item)}
                disabled={loading}
                className="btn-secondary"
              >
                Импорт
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default TMDBImportModal; 