import { PageLayout } from "@/components/layout/PageLayout";
import { useQuery } from "@tanstack/react-query";
import { Author } from "@shared/schema";
import { AuthorChip } from "@/components/common/AuthorChip";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { SearchBar } from "@/components/common/SearchBar";
import { useState } from "react";
import { Link } from "wouter";
import { ArrowRight, ChevronLeft, ChevronRight } from "lucide-react";

export default function Authors() {
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  
  const PAGE_SIZE = 12;
  
  const { data: authors, isLoading } = useQuery<Author[]>({
    queryKey: [`/api/authors?limit=${PAGE_SIZE}&offset=${(currentPage - 1) * PAGE_SIZE}`],
  });
  
  // For total number of authors (for pagination)
  const { data: totalAuthors } = useQuery<number>({
    queryKey: ['/api/authors/count'],
    queryFn: async () => {
      // This is a fallback since we don't have a specific count endpoint in our current implementation
      // In a real application, you'd want a dedicated endpoint for this
      return 120; // Mock total for pagination
    }
  });

  const totalPages = totalAuthors ? Math.ceil(totalAuthors / PAGE_SIZE) : 0;

  // Group authors alphabetically by first letter of name
  const groupedAuthors = authors?.reduce<Record<string, Author[]>>((groups, author) => {
    const firstLetter = author.name.charAt(0).toUpperCase();
    if (!groups[firstLetter]) {
      groups[firstLetter] = [];
    }
    groups[firstLetter].push(author);
    return groups;
  }, {});

  // Sort the grouped authors alphabetically
  const sortedGroupKeys = groupedAuthors ? Object.keys(groupedAuthors).sort() : [];

  const handleSearch = (query: string) => {
    setSearchQuery(query);
    // In a real app, we would fetch authors by the search query
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <PageLayout>
      <div className="max-w-[var(--content-width)] mx-auto px-4 md:px-6 py-8">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-2xl md:text-3xl font-bold font-serif text-navy dark:text-cream">Authors</h1>
            <p className="text-navy/70 dark:text-cream/70 mt-1">Discover authors from around the world</p>
          </div>
          <SearchBar placeholder="Search authors..." onSearch={handleSearch} />
        </div>

        {/* Alphabet navigation */}
        <div className="mb-8 flex flex-wrap gap-1 justify-center">
          {[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(letter => {
            const hasAuthors = sortedGroupKeys.includes(letter);
            return (
              <a
                key={letter}
                href={hasAuthors ? `#${letter}` : undefined}
                className={`w-8 h-8 flex items-center justify-center rounded-full text-sm font-medium transition-colors ${
                  hasAuthors 
                    ? 'bg-navy/10 hover:bg-navy/20 dark:bg-navy/20 dark:hover:bg-navy/30 text-navy dark:text-cream cursor-pointer' 
                    : 'bg-navy/5 dark:bg-navy/10 text-navy/40 dark:text-cream/40 cursor-default'
                }`}
              >
                {letter}
              </a>
            );
          })}
        </div>

        {isLoading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {Array.from({ length: 12 }).map((_, i) => (
              <Card key={i} className="bg-cream dark:bg-dark-surface">
                <CardContent className="p-6">
                  <div className="flex items-center gap-4 mb-4">
                    <div className="w-16 h-16 rounded-full bg-navy/10 dark:bg-navy/20 animate-pulse"></div>
                    <div className="flex-1">
                      <div className="h-5 bg-navy/10 dark:bg-navy/20 rounded-md w-3/4 mb-2 animate-pulse"></div>
                      <div className="h-4 bg-navy/10 dark:bg-navy/20 rounded-md w-1/2 animate-pulse"></div>
                    </div>
                  </div>
                  <div className="h-20 bg-navy/10 dark:bg-navy/20 rounded-md animate-pulse"></div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="space-y-8">
            {sortedGroupKeys.map(letter => (
              <div key={letter} id={letter} className="scroll-mt-20">
                <h2 className="text-xl font-serif font-semibold mb-4 text-navy dark:text-cream">{letter}</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                  {groupedAuthors![letter].map(author => (
                    <Card key={author.id} className="bg-cream dark:bg-dark-surface hover:shadow-md transition-shadow">
                      <CardContent className="p-6">
                        <AuthorChip author={author} size="lg" withLifeDates className="mb-4" />
                        <p className="text-navy/80 dark:text-cream/80 text-sm line-clamp-4 mb-4">
                          {author.biography?.slice(0, 150) || "No biography available."}{author.biography?.length > 150 ? "..." : ""}
                        </p>
                        <Link href={`/authors/${author.slug}`}>
                          <Button 
                            variant="outline" 
                            className="w-full flex items-center justify-center gap-1 text-russet"
                          >
                            View Profile <ArrowRight className="h-4 w-4" />
                          </Button>
                        </Link>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-8 flex justify-center">
            <nav className="flex items-center gap-1" aria-label="Pagination">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4" />
                <span className="sr-only">Previous</span>
              </Button>
              
              {[...Array(Math.min(5, totalPages))].map((_, i) => {
                const page = i + 1;
                return (
                  <Button
                    key={page}
                    variant={currentPage === page ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => handlePageChange(page)}
                  >
                    {page}
                  </Button>
                );
              })}
              
              {totalPages > 5 && (
                <>
                  <span className="px-2 text-navy/60 dark:text-cream/60">...</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handlePageChange(totalPages)}
                  >
                    {totalPages}
                  </Button>
                </>
              )}
              
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
                disabled={currentPage === totalPages}
              >
                <ChevronRight className="h-4 w-4" />
                <span className="sr-only">Next</span>
              </Button>
            </nav>
          </div>
        )}
      </div>
    </PageLayout>
  );
}
