/**
 * RecipeListPage - Displays a list of all recipes with search and filtering
 */

import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useRecipes } from '../hooks/useRecipes';
import { useTags } from '../hooks/useTags';
import { RecipeCard } from '../components/RecipeCard';
import { MissionControlPanel } from '../components/MissionControlPanel';

export function RecipeListPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTagId, setSelectedTagId] = useState<number | null>(null);
  
  const { recipes, loading, error, hasMore, loadMore } = useRecipes({
    search: searchQuery,
    limit: 20,
  });
  
  const { tags, loading: tagsLoading } = useTags();

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchQuery(searchTerm);
  };

  const handleClearSearch = () => {
    setSearchTerm('');
    setSearchQuery('');
  };

  const handleClearFilters = () => {
    setSearchTerm('');
    setSearchQuery('');
    setSelectedTagId(null);
  };

  // Note: This is client-side filtering. For better performance with large datasets,
  // the backend should support tag filtering in the API.
  // For now, when a tag is selected, we show all recipes with a note that this feature
  // is in development. Full tag filtering will require fetching recipe-tag associations.
  const filteredRecipes = recipes;

  const hasActiveFilters = searchQuery || selectedTagId !== null;

  return (
    <div>
      <MissionControlPanel />

      {/* Header */}
      <div className="mb-6">
        <div className="flex justify-between items-center mb-4">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">My Recipes</h2>
            <p className="mt-1 text-sm text-gray-500">
              Browse and search your recipe collection
            </p>
          </div>
          <Link
            to="/recipe/new"
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
          >
            + New Recipe
          </Link>
        </div>

        {/* Search Bar */}
        <form onSubmit={handleSearch} className="flex gap-2">
          <div className="flex-1 relative">
            <input
              type="text"
              placeholder="Search recipes by title or ingredients..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            {searchQuery && (
              <button
                type="button"
                onClick={handleClearSearch}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                aria-label="Clear search"
              >
                ✕
              </button>
            )}
          </div>
          <button
            type="submit"
            className="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors"
          >
            Search
          </button>
        </form>

        {/* Tag Filter */}
        {!tagsLoading && tags.length > 0 && (
          <div className="mt-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Filter by tag:
            </label>
            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => setSelectedTagId(null)}
                className={`
                  px-3 py-1.5 rounded-full text-sm font-medium transition-colors
                  ${selectedTagId === null
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                  }
                `}
              >
                All Recipes
              </button>
              {tags.map(tag => (
                <button
                  key={tag.id}
                  onClick={() => setSelectedTagId(tag.id)}
                  className={`
                    px-3 py-1.5 rounded-full text-sm font-medium transition-colors
                    ${selectedTagId === tag.id
                      ? 'text-white'
                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                    }
                  `}
                  style={
                    selectedTagId === tag.id && tag.color
                      ? { backgroundColor: tag.color }
                      : {}
                  }
                >
                  {tag.name}
                </button>
              ))}
            </div>
          </div>
        )}

        {hasActiveFilters && (
          <div className="mt-3 flex items-center gap-3 text-sm">
            <span className="text-gray-600">Active filters:</span>
            {searchQuery && (
              <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded">
                Search: "{searchQuery}"
              </span>
            )}
            {selectedTagId !== null && (
              <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded">
                Tag: {tags.find(t => t.id === selectedTagId)?.name}
              </span>
            )}
            <button
              onClick={handleClearFilters}
              className="text-blue-600 hover:text-blue-700 font-medium"
            >
              Clear all filters
            </button>
          </div>
        )}

        {selectedTagId !== null && (
          <div className="mt-3 bg-yellow-50 border border-yellow-200 rounded-lg p-3">
            <p className="text-sm text-yellow-800">
              <strong>Note:</strong> Tag filtering is currently a work in progress. 
              All recipes are shown below. Individual recipe tags can be viewed on their detail pages.
            </p>
          </div>
        )}
      </div>

      {/* Error State */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
          <p className="text-red-800">
            <strong>Error:</strong> {error}
          </p>
        </div>
      )}

      {/* Loading State (first load) */}
      {loading && recipes.length === 0 && (
        <div className="text-center py-12">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <p className="mt-4 text-gray-600">Loading recipes...</p>
        </div>
      )}

      {/* Empty State */}
      {!loading && !error && filteredRecipes.length === 0 && (
        <div className="bg-white rounded-lg shadow p-12 text-center">
          <div className="text-6xl mb-4">🍳</div>
          <h3 className="text-xl font-semibold text-gray-900 mb-2">
            {searchQuery ? 'No recipes found' : 'No recipes yet'}
          </h3>
          <p className="text-gray-600 mb-6">
            {searchQuery
              ? 'Try a different search term'
              : 'Get started by adding your first recipe'}
          </p>
          {!searchQuery && (
            <Link
              to="/recipe/new"
              className="inline-block bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-medium transition-colors"
            >
              Add Your First Recipe
            </Link>
          )}
        </div>
      )}

      {/* Recipe Grid */}
      {filteredRecipes.length > 0 && (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredRecipes.map((recipe) => (
              <RecipeCard key={recipe.id} recipe={recipe} />
            ))}
          </div>

          {/* Load More Button */}
          {hasMore && (
            <div className="mt-8 text-center">
              <button
                onClick={loadMore}
                disabled={loading}
                className="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? 'Loading...' : 'Load More'}
              </button>
            </div>
          )}

          {/* Results summary */}
          <div className="mt-6 text-center text-sm text-gray-500">
            Showing {filteredRecipes.length} recipe{filteredRecipes.length !== 1 ? 's' : ''}
          </div>
        </>
      )}
    </div>
  );
}
