import { type ReactElement } from "react";
import { Layers } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardTitle,
} from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { formatDateShort } from "@/lib/format-date";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/** Visibility group a template belongs to. */
export type TemplateScope = "private" | "company" | "wealthx";

export interface TemplateCardProps {
  name: string;
  description?: string;
  /** Column blueprint — only the names are needed for the preview strip. */
  columns: { name: string }[];
  scope: TemplateScope;
  /** Admin-pinned official template — shows a star marker. */
  isOfficial?: boolean;
  creator: { name: string; avatarUrl?: string };
  /** How many boards were created from this template. */
  usageCount: number;
  /** ISO date of the last edit. */
  updatedAt: string;
  /** Highlights the card (e.g. picked in the create-from-template gallery). */
  selected?: boolean;
  /** Click the card body — open detail or pick in a gallery. */
  onSelect?: () => void;
  /** Primary CTA — create a board from this template. Hidden when omitted. */
  onUse?: () => void;
  className?: string;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const getInitials = (name: string): string =>
  name
    .split(" ")
    .map((part) => part[0])
    .filter(Boolean)
    .slice(0, 2)
    .join("")
    .toUpperCase();

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

/**
 * A single Kanban template tile. Used in the Create-from-Template gallery and
 * the Template Library page. Shows the column structure preview, creator and
 * usage so an advisor can pick the right starting point.
 */
export function TemplateCard({
  name,
  description,
  columns,
  isOfficial = false,
  creator,
  usageCount,
  updatedAt,
  selected = false,
  onSelect,
  onUse,
  className,
}: TemplateCardProps): ReactElement {
  const isInteractive = Boolean(onSelect);

  return (
    <Card
      className={cn(
        "flex flex-col gap-0 overflow-hidden border-border py-0 transition-colors",
        isInteractive && "cursor-pointer hover:border-primary/60",
        selected && "border-primary ring-1 ring-primary",
        className,
      )}
      onClick={onSelect}
      data-selected={selected}
      role={isInteractive ? "button" : undefined}
      tabIndex={isInteractive ? 0 : undefined}
      onKeyDown={
        isInteractive
          ? (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                onSelect?.();
              }
            }
          : undefined
      }
    >
      <CardContent className="flex flex-1 flex-col gap-4 p-4">
        {/* Title + badges */}
        <div className="flex flex-col gap-2">
          <CardTitle className="leading-tight">{name}</CardTitle>
          <div className="flex flex-wrap items-center gap-1.5">
            {isOfficial && <Badge variant="default">Official</Badge>}
            <span className="inline-flex items-center gap-1 text-caption text-muted-foreground">
              <Layers className="size-3" />
              {columns.length} columns
            </span>
          </div>
        </div>

        {description && (
          <CardDescription className="line-clamp-2">
            {description}
          </CardDescription>
        )}

        {/* Column structure preview */}
        <div className="flex flex-wrap gap-1.5">
          {columns.map((col, i) => (
            <Badge
              key={`${col.name}-${i}`}
              variant="secondary"
              className="max-w-full truncate font-normal"
              title={col.name}
            >
              {col.name}
            </Badge>
          ))}
        </div>
      </CardContent>

      <Separator />

      {/* Footer: creator + usage + optional CTA */}
      <CardFooter className="justify-between gap-2 p-4">
        <div className="flex min-w-0 items-center gap-2">
          <Avatar className="size-6">
            {creator.avatarUrl && (
              <AvatarImage src={creator.avatarUrl} alt={creator.name} />
            )}
            <AvatarFallback className="text-caption">
              {getInitials(creator.name)}
            </AvatarFallback>
          </Avatar>
          <div className="flex min-w-0 flex-col">
            <span className="truncate text-caption text-foreground">
              {creator.name}
            </span>
            <span className="truncate text-caption text-muted-foreground">
              {usageCount.toLocaleString()} uses · {formatDateShort(updatedAt)}
            </span>
          </div>
        </div>
        {onUse && (
          <Button
            size="sm"
            variant="outline"
            onClick={(e) => {
              e.stopPropagation();
              onUse();
            }}
          >
            Use
          </Button>
        )}
      </CardFooter>
    </Card>
  );
}
