import React, { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { pb } from '../../services/pocketbaseService';
import { getFileUrl } from '../../services/pocketbaseService';
import { FaSearch, FaTimes } from 'react-icons/fa';

const MobileSearch = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = useState(searchParams.get('q') || '');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('all');

  useEffect(() => {
    if (searchQuery) {
      performSearch();
    }
  }, [searchQuery, activeTab]);

  const performSearch = async () => {
    setLoading(true);
    try {
      let filter = '';
      if (activeTab === 'media') {
        filter = `title ~ "${searchQuery}"`;
      } else if (activeTab === 'users') {
        filter = `username ~ "${searchQuery}"`;
      } else {
        const [mediaResults, userResults] = await Promise.all([
          pb.collection('media').getList(1, 10, {
            filter: `title ~ "${searchQuery}"`
          }),
          pb.collection('users').getList(1, 10, {
            filter: `username ~ "${searchQuery}"`
          })
        ]);
        setResults([...mediaResults.items, ...userResults.items]);
        setLoading(false);
        return;
      }

      const records = await pb.collection(activeTab === 'users' ? 'users' : 'media').getList(1, 20, {
        filter: filter
      });
      setResults(records.items);
    } catch (error) {
      console.error('Error performing search:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (e) => {
    e.preventDefault();
    setSearchParams({ q: searchQuery });
  };

  const clearSearch = () => {
    setSearchQuery('');
    setSearchParams({});
    setResults([]);
  };

  return (
    <div className="px-4 py-4">
      <form onSubmit={handleSearch} className="mb-6">
        <div className="relative">
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Поиск..."
            className="w-full pl-10 pr-10 py-2 bg-campfire-dark/50 border border-campfire-ash/30 rounded-lg text-campfire-light focus:outline-none focus:border-campfire-amber"
          />
          <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-campfire-ash" />
          {searchQuery && (
            <button
              type="button"
              onClick={clearSearch}
              className="absolute right-3 top-1/2 transform -translate-y-1/2 text-campfire-ash hover:text-campfire-light"
            >
              <FaTimes />
            </button>
          )}
        </div>
      </form>

      <div className="flex space-x-4 mb-6">
        <button
          onClick={() => setActiveTab('all')}
          className={`flex-1 py-2 px-4 rounded-lg ${
            activeTab === 'all'
              ? 'bg-campfire-amber text-campfire-dark'
              : 'bg-campfire-dark/50 text-campfire-light'
          }`}
        >
          Все
        </button>
        <button
          onClick={() => setActiveTab('media')}
          className={`flex-1 py-2 px-4 rounded-lg ${
            activeTab === 'media'
              ? 'bg-campfire-amber text-campfire-dark'
              : 'bg-campfire-dark/50 text-campfire-light'
          }`}
        >
          Медиа
        </button>
        <button
          onClick={() => setActiveTab('users')}
          className={`flex-1 py-2 px-4 rounded-lg ${
            activeTab === 'users'
              ? 'bg-campfire-amber text-campfire-dark'
              : 'bg-campfire-dark/50 text-campfire-light'
          }`}
        >
          Пользователи
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-campfire-amber"></div>
        </div>
      ) : results.length > 0 ? (
        <div className="space-y-4">
          {results.map((item) => (
            <Link
              key={item.id}
              to={activeTab === 'users' ? `/profile/${item.username}` : `/media/${item.id}`}
              className="flex items-center space-x-4 bg-campfire-dark/50 border border-campfire-ash/30 rounded-lg p-4"
            >
              {activeTab === 'users' ? (
                <>
                  <img
                    src={getFileUrl(item, 'profile_picture')}
                    alt={item.username}
                    className="w-12 h-12 rounded-full object-cover"
                  />
                  <div>
                    <h3 className="text-campfire-light font-semibold">{item.username}</h3>
                    <p className="text-campfire-ash text-sm">
                      {item.reviews_count || 0} обзоров
                    </p>
                  </div>
                </>
              ) : (
                <>
                  <img
                    src={getFileUrl(item, 'poster')}
                    alt={item.title}
                    className="w-12 h-12 rounded-lg object-cover"
                  />
                  <div>
                    <h3 className="text-campfire-light font-semibold">{item.title}</h3>
                    <p className="text-campfire-ash text-sm">
                      {item.type === 'movie' ? 'Фильм' : item.type === 'series' ? 'Сериал' : 'Игра'}
                    </p>
                  </div>
                </>
              )}
            </Link>
          ))}
        </div>
      ) : searchQuery ? (
        <div className="text-center py-8">
          <p className="text-campfire-light">Ничего не найдено</p>
        </div>
      ) : null}
    </div>
  );
};

export default MobileSearch; 