All files / src/features/shopping WatchedItemsList.tsx

72.72% Statements 32/44
82.35% Branches 28/34
83.33% Functions 15/18
72.5% Lines 29/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219                                            1x               15x 15x 15x 15x 15x 15x   15x                                 15x 2x     15x 36x 11x     15x   15x   11x   15x 61x 55x   6x         15x 1x                         14x                     2x           36x                                                                                       42x                                               40x                       1x               1x                                          
// src/components/WatchedItemsList.tsx
import React, { useState, useMemo } from 'react';
import type { MasterGroceryItem, User } from '../../types';
import { EyeIcon } from '../../components/icons/EyeIcon';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { SortAscIcon } from '../../components/icons/SortAscIcon';
import { SortDescIcon } from '../../components/icons/SortDescIcon';
import { TrashIcon } from '../../components/icons/TrashIcon';
import { UserIcon } from '../../components/icons/UserIcon';
import { PlusCircleIcon } from '../../components/icons/PlusCircleIcon';
import { logger } from '../../services/logger.client';
import { useCategoriesQuery } from '../../hooks/queries/useCategoriesQuery';
 
interface WatchedItemsListProps {
  items: MasterGroceryItem[];
  onAddItem: (itemName: string, category_id: number) => Promise<void>;
  onRemoveItem: (masterItemId: number) => Promise<void>;
  user: User | null;
  activeListId: number | null;
  onAddItemToList: (masterItemId: number) => void;
}
 
export const WatchedItemsList: React.FC<WatchedItemsListProps> = ({
  items,
  onAddItem,
  onRemoveItem,
  user,
  activeListId,
  onAddItemToList,
}) => {
  const [newItemName, setNewItemName] = useState('');
  const [newCategoryId, setNewCategoryId] = useState<number | ''>('');
  const [isAdding, setIsAdding] = useState(false);
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const { data: categories = [] } = useCategoriesQuery();
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newItemName.trim() || !newCategoryId) return;
 
    setIsAdding(true);
    try {
      await onAddItem(newItemName, newCategoryId as number);
      setNewItemName('');
      setNewCategoryId('');
    } catch (error) {
      // Error is handled in the parent component
      logger.error('Failed to add watched item from WatchedItemsList', { error });
    } finally {
      setIsAdding(false);
    }
  };
 
  const handleSortToggle = () => {
    setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'));
  };
 
  const availableCategories = useMemo(() => {
    const cats = new Set(items.map((i) => i.category_name).filter((c): c is string => !!c));
    return Array.from(cats).sort();
  }, [items]);
 
  const sortedAndFilteredItems = useMemo(() => {
    const filteredItems =
      categoryFilter === 'all'
        ? items
        : items.filter((item) => item.category_name === categoryFilter);
 
    return [...filteredItems].sort((a, b) => {
      if (sortOrder === 'asc') {
        return a.name.localeCompare(b.name);
      } else {
        return b.name.localeCompare(a.name);
      }
    });
  }, [items, sortOrder, categoryFilter]);
 
  if (!user) {
    return (
      <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700 p-4 text-center">
        <div className="flex flex-col items-center justify-center h-full min-h-[150px]">
          <UserIcon className="w-10 h-10 text-gray-400 mb-3" />
          <h4 className="font-semibold text-gray-700 dark:text-gray-300">Personalize Your Deals</h4>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Please log in to create and manage your personal watchlist.
          </p>
        </div>
      </div>
    );
  }
 
  return (
    <div className="bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <div className="flex justify-between items-center mb-3">
        <h3 className="text-lg font-bold text-gray-800 dark:text-white flex items-center">
          <EyeIcon className="w-6 h-6 mr-2 text-brand-primary" />
          Your Watched Items
        </h3>
        <div className="flex items-center space-x-2">
          {items.length > 0 && (
            <select
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
              className="block w-full pl-3 pr-8 py-1.5 text-xs bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-brand-primary focus:border-brand-primary"
              aria-label="Filter by category"
            >
              <option value="all">All Categories</option>
              {availableCategories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat}
                </option>
              ))}
            </select>
          )}
          {items.length > 1 && (
            <button
              onClick={handleSortToggle}
              className="p-1.5 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400 transition-colors"
              aria-label={`Sort items ${sortOrder === 'asc' ? 'descending' : 'ascending'}`}
              title={`Sort ${sortOrder === 'asc' ? 'Z-A' : 'A-Z'}`}
            >
              {sortOrder === 'asc' ? (
                <SortAscIcon className="w-5 h-5" />
              ) : (
                <SortDescIcon className="w-5 h-5" />
              )}
            </button>
          )}
        </div>
      </div>
 
      <form onSubmit={handleSubmit} className="space-y-2 mb-4">
        <input
          type="text"
          value={newItemName}
          onChange={(e) => setNewItemName(e.target.value)}
          placeholder="Add item (e.g., Avocados)"
          className="grow block w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-brand-primary focus:border-brand-primary sm:text-sm"
          disabled={isAdding}
        />
        <div className="grid grid-cols-3 gap-2">
          <select
            value={newCategoryId}
            onChange={(e) => setNewCategoryId(Number(e.target.value))}
            required
            className="col-span-2 block w-full px-3 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-brand-primary focus:border-brand-primary sm:text-sm"
            disabled={isAdding}
          >
            <option value="" disabled>
              Select a category
            </option>
            {categories.map((cat) => (
              <option key={cat.category_id} value={cat.category_id}>
                {cat.name}
              </option>
            ))}
          </select>
          <button
            type="submit"
            disabled={isAdding || !newItemName.trim() || !newCategoryId}
            className="col-span-1 bg-brand-secondary hover:bg-brand-dark disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-bold py-2 px-3 rounded-lg transition-colors duration-300 flex items-center justify-center"
          >
            {isAdding ? (
              <div className="w-5 h-5">
                <LoadingSpinner />
              </div>
            ) : (
              'Add'
            )}
          </button>
        </div>
      </form>
 
      {sortedAndFilteredItems.length > 0 ? (
        <ul className="space-y-2 max-h-60 overflow-y-auto">
          {sortedAndFilteredItems.map((item) => (
            <li
              key={item.master_grocery_item_id}
              className="group text-sm bg-gray-50 dark:bg-gray-800 p-2 rounded text-gray-700 dark:text-gray-300 flex justify-between items-center"
            >
              <div className="grow">
                <span>{item.name}</span>
                <span className="text-xs text-gray-500 dark:text-gray-400 italic ml-2">
                  {item.category_name}
                </span>
              </div>
              <div className="flex items-center shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                <button
                  onClick={() => onAddItemToList(item.master_grocery_item_id)}
                  disabled={!activeListId}
                  className="p-1 text-gray-400 hover:text-brand-primary disabled:text-gray-300 disabled:cursor-not-allowed"
                  title={activeListId ? `Add ${item.name} to list` : 'Select a shopping list first'}
                >
                  <PlusCircleIcon className="w-4 h-4" />
                </button>
                <button
                  onClick={() => onRemoveItem(item.master_grocery_item_id)}
                  className="text-red-500 hover:text-red-700 dark:hover:text-red-400 p-1"
                  aria-label={`Remove ${item.name}`}
                  title={`Remove ${item.name}`}
                >
                  <TrashIcon className="w-4 h-4" />
                </button>
              </div>
            </li>
          ))}
        </ul>
      ) : (
        <p className="p-4 text-center text-sm text-gray-500 dark:text-gray-400">
          {categoryFilter === 'all'
            ? 'Your watchlist is empty. Add items above to start tracking prices.'
            : `No watched items in the "${categoryFilter}" category.`}
        </p>
      )}
    </div>
  );
};