import type { TimelineEvent } from "@shared/schema";
import { cva, type VariantProps } from "class-variance-authority";
import { ChevronDown, ChevronUp, Edit, Share2, Users } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import {
  AuthorAvatar,
  AuthorName,
  AuthorMeta,
  AuthorGenres,
  AuthorStats,
} from "./composables/";
import type { AuthorWithStats } from "./types";
import { QuickFacts } from "./author-header/quick-facts";
import { AuthorTimeline } from "./author-header/timeline";
import { InfluencesSection } from "./author-header/influences";
import { AuthorHeaderSkeleton } from "./author-header/skeleton";

/**
 * Author Header component for displaying author information at the top of author pages
 *
 * @example
 * ```tsx
 * <AuthorHeader
 *   author={{
 *     id: 1,
 *     name: "Fyodor Dostoevsky",
 *     bio: "Russian novelist, philosopher, and short story writer...",
 *     avatar: "/images/dostoevsky.jpg",
 *     birthYear: 1821,
 *     deathYear: 1881,
 *     nationality: "Russian",
 *     era: "19th Century",
 *     genres: ["Novel", "Short Story", "Philosophical fiction"],
 *     influences: ["Gogol", "Dickens"],
 *     location: "Saint Petersburg, Russia",
 *     works: 12,
 *     followers: 345
 *   }}
 *   variant="detailed"
 *   timelineEvents={timelineEvents}
 *   onFollow={() => console.log("Followed")}
 * />
 * ```
 */

const authorHeaderVariants = cva("w-full", {
  variants: {
    variant: {
      default: "py-6",
      compact: "py-4",
      detailed: "py-8",
      minimal: "py-3",
    },
    border: {
      none: "",
      bottom: "border-b",
    },
  },
  defaultVariants: {
    variant: "default",
    border: "bottom",
  },
});

// Backward compatibility type alias (legacy code may import Author)
export type Author = AuthorWithStats;

export interface AuthorHeaderProps
  extends React.HTMLAttributes<HTMLDivElement>,
    VariantProps<typeof authorHeaderVariants> {
  /**
   * Author data
   */
  author: AuthorWithStats;
  /**
   * Whether to show action buttons
   */
  showActions?: boolean;
  /**
   * Grouped actions configuration (takes precedence over individual flags if provided)
   * TODO[author-actions,P2]: Remove individual show* flags once migration complete
   */
  actions?: {
    follow?: boolean;
    share?: boolean;
    edit?: boolean;
  };
  /**
   * Whether to show a follow button
   */
  showFollowButton?: boolean;
  /**
   * Whether to show the share button
   */
  showShareButton?: boolean;
  /**
   * Whether to show the author's works count
   */
  showWorksCount?: boolean;
  /**
   * Whether to collapse the bio by default
   */
  collapseBio?: boolean;
  /**
   * Maximum length of bio before truncating
   */
  bioLength?: number;
  /**
   * Maximum number of genres to display
   */
  maxGenres?: number;
  /**
   * Timeline events for the author
   */
  timelineEvents?: TimelineEvent[];
  /**
   * Follow button click handler
   */
  onFollow?: (author: Author, isFollowed: boolean) => void;
  /**
   * Share button click handler
   */
  onShare?: (author: Author) => void;
  /**
   * Edit button click handler
   */
  onEdit?: (author: Author) => void;
  /**
   * Whether the current user can edit the author
   */
  canEdit?: boolean;
  /**
   * Whether the component is in a loading state
   */
  isLoading?: boolean;
}

export function AuthorHeader({
  className,
  variant,
  border,
  author,
  showActions = true,
  showFollowButton = true,
  showShareButton = true,
  actions,
  showWorksCount = true,
  collapseBio = true,
  bioLength = 280,
  maxGenres = 5,
  timelineEvents = [],
  onFollow,
  onShare,
  onEdit,
  canEdit = false,
  isLoading = false,
  ...props
}: AuthorHeaderProps) {
  const [isFollowed, setIsFollowed] = useState(!!author.isFollowed);
  const [isBioExpanded, setIsBioExpanded] = useState(!collapseBio);
  // Tabs state (only needed when detailed variant)
  const [, /*activeTab*/ setActiveTab] = useState<string>("overview");

  const biography = author.biography;
  const hasLongBio = biography && biography.length > bioLength;
  const truncatedBio = hasLongBio
    ? `${biography?.substring(0, bioLength)}...`
    : biography;
  const displayBio = isBioExpanded ? biography : truncatedBio;

  const handleFollowClick = () => {
    const next = !isFollowed;
    setIsFollowed(next);
    onFollow?.(author, next);
  };
  const handleShareClick = () => onShare?.(author);
  const handleEditClick = () => onEdit?.(author);
  const toggleBio = () => setIsBioExpanded((v) => !v);

  if (isLoading) return <AuthorHeaderSkeleton />;

  // Resolve action visibilities (group prop overrides individual flags if defined)
  const resolved = {
    follow: actions?.follow ?? showFollowButton,
    share: actions?.share ?? showShareButton,
    edit: actions?.edit ?? canEdit,
  };

  return (
    <div
      className={cn(authorHeaderVariants({ variant, border, className }))}
      {...props}
    >
      <div className="container px-4 md:px-6">
        <div className="flex flex-col gap-6">
          <div className="flex flex-col md:flex-row gap-6 md:items-start">
            <AuthorAvatar
              author={{ name: author.name, portrait: author.portrait }}
              size={
                variant === "compact" || variant === "minimal" ? "xl" : "2xl"
              }
              showBadge={!!author.isFeatured}
              badgeContent={author.isFeatured ? "Featured" : undefined}
              className="rounded-lg"
            />
            <div className="flex-1 space-y-4">
              <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                <div className="space-y-2 max-w-prose">
                  <div className="flex items-start gap-2">
                    <AuthorName
                      author={{ name: author.name }}
                      as="h1"
                      size={
                        variant === "compact" || variant === "minimal"
                          ? "xl"
                          : "2xl"
                      }
                      weight="bold"
                      className="font-serif tracking-tight"
                    />
                  </div>
                  <AuthorMeta
                    author={{
                      birthYear: author.birthYear,
                      deathYear: author.deathYear,
                      country: author.country,
                    }}
                    size="sm"
                  />
                  {author.genres && variant !== "minimal" && (
                    <AuthorGenres
                      author={{ genres: author.genres }}
                      maxGenres={maxGenres}
                      size="sm"
                    />
                  )}
                </div>
                {(showActions ||
                  (showWorksCount &&
                    typeof author.worksCount === "number")) && (
                  <div className="flex flex-col gap-2 md:items-end">
                    {showActions && variant !== "minimal" && (
                      <div className="hidden md:flex items-center gap-2">
                        {resolved.follow && (
                          <Button
                            variant={isFollowed ? "default" : "outline"}
                            size="default"
                            onClick={handleFollowClick}
                            className="gap-1.5"
                          >
                            <Users className="h-4 w-4" />
                            {isFollowed ? "Following" : "Follow"}
                          </Button>
                        )}
                        {resolved.edit && (
                          <Button
                            variant="outline"
                            size="default"
                            onClick={handleEditClick}
                            className="gap-1.5"
                          >
                            <Edit className="h-4 w-4" /> Edit
                          </Button>
                        )}
                        {resolved.share && (
                          <Button
                            variant="outline"
                            size="icon"
                            onClick={handleShareClick}
                          >
                            <Share2 className="h-4 w-4" />
                            <span className="sr-only">Share</span>
                          </Button>
                        )}
                        {/* External link button removed (no url field on Author schema) */}
                      </div>
                    )}
                    <div className="flex items-center gap-4 text-muted-foreground">
                      {(() => {
                        // Adapter object matching minimal fields AuthorStats reads
                        const statsAdapter: AuthorWithStats = {
                          ...author,
                          worksCount: author.worksCount,
                          followersCount: author.followersCount,
                          stats: { ...(author.stats || {}) },
                        };
                        return (
                          <AuthorStats
                            author={statsAdapter as AuthorWithStats}
                            layout="horizontal"
                            size="sm"
                            showWorksCount={showWorksCount}
                            showFollowersCount={true}
                            showRating={false}
                            showReadsCount={false}
                            format="abbreviated"
                          />
                        );
                      })()}
                    </div>
                    {showActions && variant !== "minimal" && (
                      <div className="flex md:hidden items-center gap-2 mt-2">
                        {resolved.follow && (
                          <Button
                            variant={isFollowed ? "default" : "outline"}
                            size="sm"
                            onClick={handleFollowClick}
                            className="gap-1"
                          >
                            <Users className="h-4 w-4" />
                            {isFollowed ? "Following" : "Follow"}
                          </Button>
                        )}
                        {resolved.edit && (
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={handleEditClick}
                            className="gap-1"
                          >
                            <Edit className="h-4 w-4" /> Edit
                          </Button>
                        )}
                        {resolved.share && (
                          <Button
                            variant="outline"
                            size="icon"
                            className="h-8 w-8"
                            onClick={handleShareClick}
                          >
                            <Share2 className="h-3.5 w-3.5" />
                          </Button>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
              {variant === "detailed" && (
                <Tabs
                  defaultValue="overview"
                  className="w-full"
                  onValueChange={setActiveTab}
                >
                  <TabsList className="mb-4">
                    <TabsTrigger value="overview">Overview</TabsTrigger>
                    {timelineEvents.length > 0 && (
                      <TabsTrigger value="timeline">Timeline</TabsTrigger>
                    )}
                    {author.influences && author.influences.length > 0 && (
                      <TabsTrigger value="influences">Influences</TabsTrigger>
                    )}
                    <TabsTrigger value="works">Works</TabsTrigger>
                  </TabsList>
                  <TabsContent value="overview" className="space-y-4">
                    {biography && (
                      <div className="space-y-2 max-w-3xl">
                        <p className="text-base text-muted-foreground leading-relaxed">
                          {displayBio}
                        </p>
                        {hasLongBio && (
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 px-2 -ml-2"
                            onClick={toggleBio}
                            aria-expanded={isBioExpanded}
                            aria-label={
                              isBioExpanded
                                ? "Collapse biography"
                                : "Expand biography"
                            }
                          >
                            {isBioExpanded ? (
                              <span className="flex items-center gap-1">
                                Show less <ChevronUp className="h-3.5 w-3.5" />
                              </span>
                            ) : (
                              <span className="flex items-center gap-1">
                                Read more{" "}
                                <ChevronDown className="h-3.5 w-3.5" />
                              </span>
                            )}
                          </Button>
                        )}
                      </div>
                    )}
                    <QuickFacts author={author as AuthorWithStats} />
                  </TabsContent>
                  {timelineEvents.length > 0 && (
                    <TabsContent value="timeline">
                      <AuthorTimeline events={timelineEvents} />
                    </TabsContent>
                  )}
                  {author.influences && author.influences.length > 0 && (
                    <TabsContent value="influences">
                      <InfluencesSection
                        authorName={author.name}
                        influences={author.influences}
                      />
                    </TabsContent>
                  )}
                  <TabsContent value="works">
                    <div className="py-2 text-center text-muted-foreground">
                      Works will be loaded here. This tab serves as a
                      placeholder for the works listing.
                    </div>
                  </TabsContent>
                </Tabs>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default AuthorHeader;
