import { useState, useMemo, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Grid3X3, List } from "lucide-react";
import { useAuthorWorks } from "@/hooks/use-author-api";
import type { Work } from "@shared/schema";
import { WorkFilters } from "./author-works/filters";
import { AuthorWorksSkeleton } from "./author-works/skeleton";
import { WorksEmptyState } from "./author-works/empty-state";
import type { FilterState } from "./author-works/types";
import { formatTypeName } from "./author-works/utils";
import { SimpleWorkCard } from "./author-works/work-card";
import { AuthorReadingStats } from "./author-works/reading-stats";

interface AuthorWorksDisplayProps {
  authorId: string;
  className?: string;
}

// FilterState moved to author-works/types

// SimpleWorkCard extracted to author-works/work-card.tsx

export function AuthorWorksDisplay({
  authorId,
  className,
}: AuthorWorksDisplayProps) {
  const [view, setView] = useState<"list" | "grid">("list");
  const [filters, setFilters] = useState<FilterState>({
    selectedGenre: null,
    selectedYear: null,
    selectedWorkType: null,
    selectedLanguage: null,
  });

  // Use the actual API hook to fetch author's works
  const { data: works, isLoading, error } = useAuthorWorks(authorId);

  // Extract filter options from works data
  const years = useMemo(
    () =>
      Array.from(
        new Set(works?.map((work) => work.year?.toString()).filter(Boolean))
      ).filter((year): year is string => year !== undefined),
    [works]
  );

  const languages = useMemo(
    () =>
      Array.from(new Set(works?.map((work) => work.language).filter(Boolean))),
    [works]
  );

  const workTypes = useMemo(
    () => Array.from(new Set(works?.map((work) => work.type).filter(Boolean))),
    [works]
  );

  // Since tags are tag IDs in the actual API, we'll skip genre filtering for now
  // In a real implementation, you'd need to fetch tag names by IDs

  // Filter works based on selected filters
  const filteredWorks = useMemo(
    () =>
      works?.filter((work) => {
        if (
          filters.selectedYear &&
          work.year?.toString() !== filters.selectedYear
        ) {
          return false;
        }
        if (
          filters.selectedWorkType &&
          work.type !== filters.selectedWorkType
        ) {
          return false;
        }
        if (
          filters.selectedLanguage &&
          work.language !== filters.selectedLanguage
        ) {
          return false;
        }
        return true;
      }),
    [works, filters]
  );

  // Group works by type
  const worksByType = useMemo(
    () =>
      filteredWorks?.reduce<Record<string, Work[]>>((acc, work) => {
        const type = work.type || "Other";
        if (!acc[type]) acc[type] = [];
        acc[type].push(work);
        return acc;
      }, {}),
    [filteredWorks]
  );

  // Clear all filters
  const clearFilters = useCallback(() => {
    setFilters({
      selectedGenre: null,
      selectedYear: null,
      selectedWorkType: null,
      selectedLanguage: null,
    });
  }, []);

  // Format type name for display
  // formatTypeName now imported from shared utils

  // Handle filter changes
  const handleFilterChange = useCallback(
    (filterType: keyof FilterState, value: string | null) => {
      setFilters((prev) => ({
        ...prev,
        [filterType]: value === "all" ? null : value,
      }));
    },
    []
  );

  if (isLoading) return <AuthorWorksSkeleton className={className} />;

  if (error) {
    return (
      <div className={className}>
        <div className="text-center py-12 bg-navy/5 dark:bg-navy/10 rounded-lg">
          <p className="text-navy/70 dark:text-cream/70">
            Unable to load works at this time.
          </p>
        </div>
      </div>
    );
  }

  if (!works || works.length === 0)
    return <WorksEmptyState variant="none" className={className} />;

  const hasActiveFilters = Object.values(filters).some(
    (filter) => filter !== null
  );

  return (
    <div className={className}>
      <Tabs defaultValue="works" className="w-full">
        <TabsList className="grid grid-cols-5 mb-8">
          <TabsTrigger value="works" className="text-sm md:text-base">
            Works
          </TabsTrigger>
          <TabsTrigger value="timeline" className="text-sm md:text-base">
            Timeline
          </TabsTrigger>
          <TabsTrigger value="related" className="text-sm md:text-base">
            Related Authors
          </TabsTrigger>
          <TabsTrigger value="about" className="text-sm md:text-base">
            Biography
          </TabsTrigger>
          <TabsTrigger value="discussions" className="text-sm md:text-base">
            Discussions
          </TabsTrigger>
        </TabsList>

        <TabsContent value="works" className="w-full space-y-6">
          {/* Controls row */}
          <div className="flex flex-col sm:flex-row justify-between gap-4 items-start sm:items-center bg-navy/5 dark:bg-navy/10 p-4 rounded-lg">
            <WorkFilters
              filters={filters}
              years={years}
              languages={languages}
              workTypes={workTypes}
              hasActiveFilters={hasActiveFilters}
              onFilterChange={handleFilterChange}
              onClear={clearFilters}
            />

            {/* View options */}
            <div className="flex items-center gap-2 ml-auto">
              <span className="text-sm text-navy/70 dark:text-cream/70">
                View:
              </span>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant={view === "list" ? "default" : "ghost"}
                      size="icon"
                      className="h-9 w-9"
                      onClick={() => setView("list")}
                    >
                      <List className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>List view</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>

              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Button
                      variant={view === "grid" ? "default" : "ghost"}
                      size="icon"
                      className="h-9 w-9"
                      onClick={() => setView("grid")}
                    >
                      <Grid3X3 className="h-4 w-4" />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Grid view</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </div>

          {/* Works display */}
          {filteredWorks && filteredWorks.length > 0 ? (
            hasActiveFilters ? (
              // Filtered results
              <div>
                {view === "list" ? (
                  <div className="space-y-3">
                    {filteredWorks.map((work) => (
                      <SimpleWorkCard key={work.id} work={work} />
                    ))}
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredWorks.map((work) => (
                      <SimpleWorkCard key={work.id} work={work} grid />
                    ))}
                  </div>
                )}
              </div>
            ) : (
              // By type grouping (default)
              <div className="space-y-10">
                {Object.entries(worksByType || {}).map(([type, typeWorks]) => (
                  <div key={type} className="space-y-4">
                    <h3 className="text-xl font-serif font-semibold text-navy dark:text-cream border-b border-sage/10 dark:border-sage/5 pb-2">
                      {formatTypeName(type)}{" "}
                      <span className="text-navy/60 dark:text-cream/60 text-base">
                        ({typeWorks.length})
                      </span>
                    </h3>

                    {view === "list" ? (
                      <div className="space-y-3">
                        {typeWorks.map((work) => (
                          <SimpleWorkCard key={work.id} work={work} />
                        ))}
                      </div>
                    ) : (
                      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                        {typeWorks.map((work) => (
                          <SimpleWorkCard key={work.id} work={work} grid />
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )
          ) : (
            <WorksEmptyState variant="filters" onClearFilters={clearFilters} />
          )}

          {/* Reading statistics (extracted component) */}
          {works && works.length > 0 && (
            <AuthorReadingStats
              works={works}
              workTypes={workTypes}
              languages={languages}
            />
          )}
        </TabsContent>

        {/* TODO: Other tab contents would use their respective hooks */}
        <TabsContent value="timeline" className="w-full">
          <div className="text-center py-12 bg-navy/5 dark:bg-navy/10 rounded-lg">
            <p className="text-navy/70 dark:text-cream/70">
              Timeline content would be loaded here using useAuthorTimeline
              hook.
            </p>
          </div>
        </TabsContent>

        <TabsContent value="related" className="w-full">
          <div className="text-center py-12 bg-navy/5 dark:bg-navy/10 rounded-lg">
            <p className="text-navy/70 dark:text-cream/70">
              Related authors would be loaded here using useRelatedAuthors hook.
            </p>
          </div>
        </TabsContent>

        <TabsContent value="about" className="w-full">
          <div className="text-center py-12 bg-navy/5 dark:bg-navy/10 rounded-lg">
            <p className="text-navy/70 dark:text-cream/70">
              Extended biography content would be loaded here.
            </p>
          </div>
        </TabsContent>

        <TabsContent value="discussions" className="w-full">
          <div className="text-center py-12 bg-navy/5 dark:bg-navy/10 rounded-lg">
            <p className="text-navy/70 dark:text-cream/70">
              Discussions would be loaded here using useAuthorDiscussions hook.
            </p>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
