/**
 * AuthorBio - Composable biography component for authors
 */

import { useState } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { AuthorWithStats } from "../types";
import { authorUtils } from "../utils";

const authorBioVariants = cva("text-muted-foreground", {
  variants: {
    size: {
      xs: "text-xs",
      sm: "text-sm",
      md: "text-sm",
      lg: "text-base",
    },
    lines: {
      1: "line-clamp-1",
      2: "line-clamp-2",
      3: "line-clamp-3",
      4: "line-clamp-4",
      none: "",
    },
  },
  defaultVariants: {
    size: "sm",
    lines: 2,
  },
});

interface AuthorBioProps
  extends React.HTMLAttributes<HTMLParagraphElement>,
    VariantProps<typeof authorBioVariants> {
  author: Pick<AuthorWithStats, "biography">;
  maxLength?: number;
  expandable?: boolean;
}

export function AuthorBio({
  author,
  size,
  lines,
  maxLength = 150,
  expandable,
  className,
  ...props
}: AuthorBioProps) {
  const [isExpanded, setIsExpanded] = useState(false);

  if (!author.biography) return null;

  const { text: truncatedBio, isTruncated } = authorUtils.formatBio(
    author.biography,
    maxLength,
    isExpanded
  );
  const shouldTruncate = isTruncated;

  return (
    <div className="space-y-1">
      <p
        className={cn(
          authorBioVariants({
            size,
            lines: isExpanded ? "none" : lines,
          }),
          className
        )}
        {...props}
      >
        {isExpanded ? author.biography : truncatedBio}
      </p>
      {expandable && shouldTruncate && (
        <Button
          variant="ghost"
          size="sm"
          className="h-auto p-0 text-xs text-primary hover:text-primary/80"
          onClick={() => setIsExpanded(!isExpanded)}
        >
          {isExpanded ? "Show less" : "Show more"}
        </Button>
      )}
    </div>
  );
}

export type { AuthorBioProps };
export { authorBioVariants };
