import { useActionMutation } from "@agent-native/core/client/hooks";
import { IconHeart, IconHeartFilled } from "@tabler/icons-react";
import { useState } from "react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useVisitorId } from "@/lib/visitor-id";

export type QuoteCardData = {
  id: number;
  text: string;
  tags: string[];
  poem: {
    title: string;
    author: string;
    source: string | null;
    year: number | null;
  };
  favoriteCount: number;
  isFavorited: boolean;
};

interface QuoteCardProps {
  quote: QuoteCardData;
  onTagClick?: (tag: string) => void;
  className?: string;
}

export function QuoteCard({ quote, onTagClick, className }: QuoteCardProps) {
  const visitorId = useVisitorId();
  const [optimistic, setOptimistic] = useState<{ favorited: boolean; count: number } | null>(
    null,
  );
  const { mutate, isPending } = useActionMutation("toggle-favorite", {
    onSuccess: (result) => {
      setOptimistic({ favorited: result.favorited, count: result.favoriteCount });
    },
    onError: () => setOptimistic(null),
  });

  const favorited = optimistic?.favorited ?? quote.isFavorited;
  const count = optimistic?.count ?? quote.favoriteCount;

  return (
    <Card className={cn("flex h-full flex-col justify-between", className)}>
      <CardContent className="pt-6">
        <blockquote className="text-balance text-lg leading-relaxed font-medium text-foreground">
          “{quote.text}”
        </blockquote>
        <p className="mt-4 text-sm text-muted-foreground">
          — {quote.poem.author}, <span className="italic">{quote.poem.title}</span>
          {quote.poem.year ? ` (${quote.poem.year})` : ""}
        </p>
        {quote.tags.length > 0 && (
          <div className="mt-4 flex flex-wrap gap-1.5">
            {quote.tags.map((tag) => (
              <Badge
                key={tag}
                variant="secondary"
                className={cn(onTagClick && "cursor-pointer hover:bg-secondary/70")}
                onClick={() => onTagClick?.(tag)}
              >
                {tag}
              </Badge>
            ))}
          </div>
        )}
      </CardContent>
      <CardFooter className="flex items-center justify-between border-t pt-4">
        <span className="text-xs text-muted-foreground">
          {count} {count === 1 ? "favorite" : "favorites"}
        </span>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          disabled={isPending || !visitorId}
          onClick={() => mutate({ quoteId: quote.id, visitorId })}
          aria-pressed={favorited}
          aria-label={favorited ? "Remove from favorites" : "Add to favorites"}
          className={cn("gap-1.5", favorited && "text-rose-500 hover:text-rose-500")}
        >
          {favorited ? (
            <IconHeartFilled className="size-4" />
          ) : (
            <IconHeart className="size-4" />
          )}
          {favorited ? "Favorited" : "Favorite"}
        </Button>
      </CardFooter>
    </Card>
  );
}
