'use client';

import { useState, useEffect } from 'react';
import { collectionApi, tagApi } from '../../lib/api';
import { Collection, Tag } from '../../types/api';
import AppLayout from '../../components/layout/AppLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import CollectionGrid from '../../components/collections/CollectionGrid';
import TagFilter from '../../components/stories/TagFilter';
import LoadingSpinner from '../../components/ui/LoadingSpinner';

type ViewMode = 'grid' | 'list';

export default function CollectionsPage() {
  const [collections, setCollections] = useState<Collection[]>([]);
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [showArchived, setShowArchived] = useState(false);
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(20);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCollections, setTotalCollections] = useState(0);
  const [refreshTrigger, setRefreshTrigger] = useState(0);


  // Extract tags from current collection results with counts
  const extractTagsFromResults = (collections: Collection[]): Tag[] => {
    const tagCounts: { [key: string]: number } = {};
    
    collections.forEach(collection => {
      collection.tagNames?.forEach(tagName => {
        if (tagCounts[tagName]) {
          tagCounts[tagName]++;
        } else {
          tagCounts[tagName] = 1;
        }
      });
    });
    
    return Object.entries(tagCounts).map(([tagName, count]) => ({
      id: tagName, // Use tag name as ID since we don't have actual IDs from search results
      name: tagName,
      collectionCount: count
    }));
  };

  // Load collections with search and filters
  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      const loadCollections = async () => {
        try {
          setLoading(true);
          
          const result = await collectionApi.getCollections({
            page: page,
            limit: pageSize,
            search: searchQuery.trim() || undefined,
            tags: selectedTags.length > 0 ? selectedTags : undefined,
            archived: showArchived,
          });
          
          const currentCollections = result?.results || [];
          setCollections(currentCollections);
          setTotalPages(Math.ceil((result?.totalHits || 0) / pageSize));
          setTotalCollections(result?.totalHits || 0);
          
          // Always update tags based on current search results (including initial wildcard search)
          const resultTags = extractTagsFromResults(currentCollections);
          setTags(resultTags);
        } catch (error) {
          console.error('Failed to load collections:', error);
          setCollections([]);
        } finally {
          setLoading(false);
        }
      };
      
      loadCollections();
    }, searchQuery ? 300 : 0); // Debounce search, but not other changes

    return () => clearTimeout(debounceTimer);
  }, [searchQuery, selectedTags, page, pageSize, showArchived, refreshTrigger]);

  // Reset page when search or filters change
  const resetPage = () => {
    if (page !== 0) {
      setPage(0);
    }
  };

  const handleTagToggle = (tagName: string) => {
    setSelectedTags(prev => {
      const newTags = prev.includes(tagName)
        ? prev.filter(t => t !== tagName)
        : [...prev, tagName];
      resetPage();
      return newTags;
    });
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    resetPage();
  };

  const handlePageSizeChange = (newSize: number) => {
    setPageSize(newSize);
    resetPage();
  };

  const clearFilters = () => {
    setSearchQuery('');
    setSelectedTags([]);
    setShowArchived(false);
    resetPage();
  };

  const handleCollectionUpdate = () => {
    // Trigger reload by incrementing refresh trigger
    setRefreshTrigger(prev => prev + 1);
  };

  if (loading && collections.length === 0) {
    return (
      <AppLayout>
        <div className="flex items-center justify-center py-20">
          <LoadingSpinner size="lg" />
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold theme-header">Collections</h1>
            <p className="theme-text mt-1">
              {totalCollections} {totalCollections === 1 ? 'collection' : 'collections'}
              {searchQuery || selectedTags.length > 0 || showArchived ? ` found` : ` total`}
            </p>
          </div>
          
          <Button href="/collections/new">
            Create New Collection
          </Button>
        </div>

        {/* Search and Filters */}
        <div className="space-y-4">
          {/* Search Bar */}
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <Input
                type="search"
                placeholder="Search collections by name or description..."
                value={searchQuery}
                onChange={handleSearchChange}
                className="w-full"
              />
            </div>
            
            {/* View Mode Toggle */}
            <div className="flex items-center gap-2">
              <button
                onClick={() => setViewMode('grid')}
                className={`p-2 rounded-lg transition-colors ${
                  viewMode === 'grid'
                    ? 'theme-accent-bg text-white'
                    : 'theme-card theme-text hover:bg-opacity-80'
                }`}
                aria-label="Grid view"
              >
                ⊞
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`p-2 rounded-lg transition-colors ${
                  viewMode === 'list'
                    ? 'theme-accent-bg text-white'
                    : 'theme-card theme-text hover:bg-opacity-80'
                }`}
                aria-label="List view"
              >
                ☰
              </button>
            </div>
          </div>

          {/* Filters and Controls */}
          <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
            {/* Page Size Selector */}
            <div className="flex items-center gap-2">
              <label className="theme-text font-medium text-sm">Show:</label>
              <select
                value={pageSize}
                onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                className="px-3 py-1 rounded-lg theme-card theme-text theme-border border focus:outline-none focus:ring-2 focus:ring-theme-accent"
              >
                <option value={10}>10</option>
                <option value={20}>20</option>
                <option value={50}>50</option>
              </select>
            </div>

            {/* Archive Toggle */}
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={showArchived}
                onChange={(e) => {
                  setShowArchived(e.target.checked);
                  resetPage();
                }}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="theme-text text-sm">Show archived</span>
            </label>

            {/* Clear Filters */}
            {(searchQuery || selectedTags.length > 0 || showArchived) && (
              <Button variant="ghost" size="sm" onClick={clearFilters}>
                Clear Filters
              </Button>
            )}
          </div>

          {/* Tag Filter */}
          <TagFilter
            tags={tags}
            selectedTags={selectedTags}
            onTagToggle={handleTagToggle}
            showCollectionCount={true}
          />
        </div>

        {/* Collections Display */}
        <CollectionGrid
          collections={collections}
          viewMode={viewMode}
          onUpdate={handleCollectionUpdate}
        />

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex justify-center items-center gap-4 mt-8">
            <Button
              variant="ghost"
              onClick={() => setPage(page - 1)}
              disabled={page === 0}
            >
              Previous
            </Button>
            
            <div className="flex items-center gap-2">
              <span className="theme-text text-sm">Page</span>
              <input
                type="number"
                min={1}
                max={totalPages}
                value={page + 1}
                onChange={(e) => {
                  const newPage = Math.max(0, Math.min(totalPages - 1, parseInt(e.target.value) - 1));
                  if (!isNaN(newPage)) {
                    setPage(newPage);
                  }
                }}
                className="w-16 px-2 py-1 text-center rounded theme-card theme-text theme-border border focus:outline-none focus:ring-2 focus:ring-theme-accent"
              />
              <span className="theme-text text-sm">of {totalPages}</span>
            </div>
            
            <Button
              variant="ghost"
              onClick={() => setPage(page + 1)}
              disabled={page >= totalPages - 1}
            >
              Next
            </Button>
          </div>
        )}

        {/* Loading Overlay */}
        {loading && collections.length > 0 && (
          <div className="fixed inset-0 bg-black bg-opacity-20 flex items-center justify-center z-50">
            <div className="theme-card p-4 rounded-lg">
              <LoadingSpinner size="md" />
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}