'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { authorApi, getImageUrl } from '../../lib/api';
import { Author } from '../../types/api';
import AppLayout from '../../components/layout/AppLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import LoadingSpinner from '../../components/ui/LoadingSpinner';

export default function AuthorsPage() {
  const [authors, setAuthors] = useState<Author[]>([]);
  const [filteredAuthors, setFilteredAuthors] = useState<Author[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [sortBy, setSortBy] = useState('name');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [currentPage, setCurrentPage] = useState(0);
  const [totalHits, setTotalHits] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const ITEMS_PER_PAGE = 50; // Safe limit under Typesense's 250 limit

  useEffect(() => {
    const debounceTimer = setTimeout(() => {
      const loadAuthors = async () => {
        try {
          // Use searchLoading for background search, loading only for initial load
          const isInitialLoad = authors.length === 0 && !searchQuery && currentPage === 0;
          if (isInitialLoad) {
            setLoading(true);
          } else {
            setSearchLoading(true);
          }
          const searchResults = await authorApi.searchAuthorsTypesense({ 
            q: searchQuery || '*',
            page: currentPage, 
            size: ITEMS_PER_PAGE,
            sortBy: sortBy,
            sortOrder: sortOrder
          });
          
          if (currentPage === 0) {
            // First page - replace all results
            setAuthors(searchResults.results || []);
            setFilteredAuthors(searchResults.results || []);
          } else {
            // Subsequent pages - append results
            setAuthors(prev => [...prev, ...(searchResults.results || [])]);
            setFilteredAuthors(prev => [...prev, ...(searchResults.results || [])]);
          }
          
          setTotalHits(searchResults.totalHits);
          setHasMore(searchResults.results.length === ITEMS_PER_PAGE && (currentPage + 1) * ITEMS_PER_PAGE < searchResults.totalHits);
          
        } catch (error) {
          console.error('Failed to load authors:', error);
          // Fallback to regular API if Typesense fails (only for first page)
          if (currentPage === 0) {
            try {
              const authorsResult = await authorApi.getAuthors({ page: 0, size: ITEMS_PER_PAGE });
              setAuthors(authorsResult.content || []);
              setFilteredAuthors(authorsResult.content || []);
              setTotalHits(authorsResult.totalElements || 0);
              setHasMore(authorsResult.content.length === ITEMS_PER_PAGE);
            } catch (fallbackError) {
              console.error('Fallback also failed:', fallbackError);
            }
          }
        } finally {
          setLoading(false);
          setSearchLoading(false);
        }
      };

      loadAuthors();
    }, searchQuery ? 500 : 0); // 500ms debounce for search, immediate for other changes

    return () => clearTimeout(debounceTimer);
  }, [searchQuery, sortBy, sortOrder, currentPage]);

  // Reset pagination when search or sort changes
  useEffect(() => {
    if (currentPage !== 0) {
      setCurrentPage(0);
    }
  }, [searchQuery, sortBy, sortOrder]);

  const loadMore = () => {
    if (hasMore && !loading) {
      setCurrentPage(prev => prev + 1);
    }
  };

  // Client-side filtering no longer needed since we use Typesense

  // Note: We no longer have individual story ratings in the author list
  // Average rating would need to be calculated on backend if needed

  if (loading) {
    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">Authors</h1>
            <p className="theme-text mt-1">
              {filteredAuthors.length} of {totalHits} {totalHits === 1 ? 'author' : 'authors'}
              {searchQuery ? ` found` : ` in your library`}
              {hasMore && ` (showing first ${filteredAuthors.length})`}
            </p>
          </div>
          
          {/* View Mode Toggle */}
          <div className="flex items-center gap-2">
            <Button
              variant={viewMode === 'grid' ? 'primary' : 'ghost'}
              onClick={() => setViewMode('grid')}
              className="px-3 py-2"
            >
              ⊞ Grid
            </Button>
            <Button
              variant={viewMode === 'list' ? 'primary' : 'ghost'}
              onClick={() => setViewMode('list')}
              className="px-3 py-2"
            >
              ☰ List
            </Button>
          </div>
        </div>

        {/* Search and Sort Controls */}
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 max-w-md relative">
            <Input
              type="search"
              placeholder="Search authors..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            {searchLoading && (
              <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                <div className="animate-spin h-4 w-4 border-2 border-theme-accent border-t-transparent rounded-full"></div>
              </div>
            )}
          </div>
          
          <div className="flex gap-2">
            <select 
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="px-3 py-2 border rounded-lg theme-card border-gray-300 dark:border-gray-600"
            >
              <option value="name">Name</option>
              <option value="rating">Author Rating</option>
              <option value="storycount">Story Count</option>
              <option value="avgrating">Avg Story Rating</option>
            </select>
            
            <Button
              variant="ghost"
              onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
              className="px-3 py-2"
            >
              {sortOrder === 'asc' ? '↑' : '↓'}
            </Button>
          </div>
        </div>

        {/* Authors Display */}
        {filteredAuthors.length === 0 ? (
          <div className="text-center py-20">
            <div className="theme-text text-lg mb-4">
              {searchQuery 
                ? 'No authors match your search' 
                : 'No authors in your library yet'
              }
            </div>
            {searchQuery ? (
              <button 
                onClick={() => setSearchQuery('')}
                className="theme-accent hover:underline"
              >
                Clear search
              </button>
            ) : (
              <p className="theme-text">
                Authors will appear here when you add stories to your library.
              </p>
            )}
          </div>
        ) : viewMode === 'grid' ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredAuthors.map((author) => (
              <AuthorGridCard key={author.id} author={author} />
            ))}
          </div>
        ) : (
          <div className="space-y-3">
            {filteredAuthors.map((author) => (
              <AuthorListItem key={author.id} author={author} />
            ))}
          </div>
        )}
        
        {/* Load More Button */}
        {hasMore && (
          <div className="flex justify-center pt-8">
            <Button
              onClick={loadMore}
              disabled={loading}
              variant="ghost"
              className="px-8 py-3"
              loading={loading}
            >
              {loading ? 'Loading...' : `Load More Authors (${totalHits - filteredAuthors.length} remaining)`}
            </Button>
          </div>
        )}
      </div>
    </AppLayout>
  );
}

// Author Grid Card Component
function AuthorGridCard({ author }: { author: Author }) {
  return (
    <Link
      href={`/authors/${author.id}`}
      className="theme-card theme-shadow rounded-lg p-6 hover:shadow-lg transition-shadow group"
    >
      {/* Avatar */}
      <div className="flex items-center gap-4 mb-4">
        <div className="w-16 h-16 rounded-full overflow-hidden bg-gray-200 dark:bg-gray-700 flex-shrink-0">
          {author.avatarImagePath ? (
            <Image
              src={getImageUrl(author.avatarImagePath)}
              alt={author.name}
              width={64}
              height={64}
              className="w-full h-full object-cover"
              unoptimized
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-2xl theme-text">
              👤
            </div>
          )}
        </div>
        
        <div className="min-w-0 flex-1">
          <h3 className="text-lg font-semibold theme-header group-hover:theme-accent transition-colors truncate">
            {author.name}
          </h3>
          
          <div className="flex items-center gap-2 mt-1">
            {/* Author Rating */}
            {author.authorRating && (
              <div className="flex items-center gap-1">
                <div className="flex">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <span
                      key={star}
                      className={`text-sm ${
                        star <= (author.authorRating || 0)
                          ? 'text-yellow-400'
                          : 'text-gray-300 dark:text-gray-600'
                      }`}
                    >
                      ★
                    </span>
                  ))}
                </div>
                <span className="text-sm theme-text">
                  ({author.authorRating}/5)
                </span>
              </div>
            )}
            
            {/* Average Story Rating */}
            {author.averageStoryRating && (
              <div className="flex items-center gap-1">
                <div className="flex">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <span
                      key={star}
                      className={`text-xs ${
                        star <= Math.round(author.averageStoryRating || 0)
                          ? 'text-blue-400'
                          : 'text-gray-300 dark:text-gray-600'
                      }`}
                    >
                      ★
                    </span>
                  ))}
                </div>
                <span className="text-xs theme-text">
                  ({author.averageStoryRating.toFixed(1)})
                </span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Stats */}
      <div className="space-y-2 mb-4">
        <div className="flex justify-between items-center text-sm">
          <span className="theme-text">Stories:</span>
          <span className="font-medium theme-header">
            {author.storyCount || 0}
          </span>
        </div>
        
        {author.urls && author.urls.length > 0 && (
          <div className="flex justify-between items-center text-sm">
            <span className="theme-text">Links:</span>
            <span className="font-medium theme-header">
              {author.urls.length}
            </span>
          </div>
        )}
      </div>

      {/* Notes Preview */}
      {author.notes && (
        <div className="text-sm theme-text">
          <p className="line-clamp-3">
            {author.notes}
          </p>
        </div>
      )}
    </Link>
  );
}

// Author List Item Component
function AuthorListItem({ author }: { author: Author }) {
  return (
    <Link
      href={`/authors/${author.id}`}
      className="theme-card theme-shadow rounded-lg p-4 hover:shadow-lg transition-shadow group flex items-center gap-4"
    >
      {/* Avatar */}
      <div className="w-12 h-12 rounded-full overflow-hidden bg-gray-200 dark:bg-gray-700 flex-shrink-0">
        {author.avatarImagePath ? (
          <Image
            src={getImageUrl(author.avatarImagePath)}
            alt={author.name}
            width={48}
            height={48}
            className="w-full h-full object-cover"
            unoptimized
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-xl theme-text">
            👤
          </div>
        )}
      </div>
      
      {/* Author Info */}
      <div className="flex-1 min-w-0">
        <h3 className="text-lg font-semibold theme-header group-hover:theme-accent transition-colors truncate">
          {author.name}
        </h3>
        
        <div className="flex items-center gap-4 mt-1">
          {/* Ratings */}
          <div className="flex items-center gap-3">
            {author.authorRating && (
              <div className="flex items-center gap-1">
                <div className="flex">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <span
                      key={star}
                      className={`text-sm ${
                        star <= (author.authorRating || 0)
                          ? 'text-yellow-400'
                          : 'text-gray-300 dark:text-gray-600'
                      }`}
                    >
                      ★
                    </span>
                  ))}
                </div>
                <span className="text-sm theme-text">
                  ({author.authorRating})
                </span>
              </div>
            )}
            
            {author.averageStoryRating && (
              <div className="flex items-center gap-1">
                <div className="flex">
                  {[1, 2, 3, 4, 5].map((star) => (
                    <span
                      key={star}
                      className={`text-xs ${
                        star <= Math.round(author.averageStoryRating || 0)
                          ? 'text-blue-400'
                          : 'text-gray-300 dark:text-gray-600'
                      }`}
                    >
                      ★
                    </span>
                  ))}
                </div>
                <span className="text-xs theme-text">
                  Avg: {author.averageStoryRating.toFixed(1)}
                </span>
              </div>
            )}
          </div>
          
          {/* Stats */}
          <div className="flex items-center gap-4 text-sm theme-text">
            <span>{author.storyCount || 0} stories</span>
            {author.urls && author.urls.length > 0 && (
              <span>{author.urls.length} links</span>
            )}
          </div>
        </div>
        
        {/* Notes Preview */}
        {author.notes && (
          <p className="text-sm theme-text mt-2 line-clamp-2">
            {author.notes}
          </p>
        )}
      </div>
    </Link>
  );
}