import { Heart } from "lucide-react";
import { useCallback } from "react";
import type { AckInfo } from "@/api/types";
import { apiClient } from "@/api/client";
import { useAuthStore } from "@/stores/auth-store";
import { useAppStore } from "@/stores/app-store";
import { cn } from "@/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface AckButtonProps {
  particleId: string;
  acks: AckInfo[];
}

function getInitials(email: string): string {
  const prefix = email.split("@")[0];
  const parts = prefix.split(/[._-]/);
  if (parts.length >= 2) {
    return (parts[0][0] + parts[1][0]).toUpperCase();
  }
  return prefix.slice(0, 2).toUpperCase();
}

export function AckButton({ particleId, acks }: AckButtonProps) {
  const currentEmail = useAuthStore((s) => s.user?.email);
  const ackParticle = useAppStore((s) => s.ackParticle);
  const hasAcked = acks.some((a) => a.email === currentEmail);

  const handleClick = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation();
      if (hasAcked || !currentEmail) return;
      ackParticle(particleId, currentEmail);
      apiClient.ackParticle(particleId).catch(() => {});
    },
    [hasAcked, currentEmail, particleId, ackParticle],
  );

  const displayedAcks = acks.slice(0, 3);

  return (
    <div className="flex flex-col items-center gap-1.5">
      <button
        type="button"
        onClick={handleClick}
        className={cn(
          "flex h-10 w-10 flex-col items-center justify-center rounded-full bg-black/30 backdrop-blur-sm transition-colors",
          hasAcked
            ? "text-red-500"
            : "text-white hover:bg-black/40",
        )}
      >
        <Heart
          className="h-4 w-4"
          fill={hasAcked ? "currentColor" : "none"}
        />
        <span className="mt-0.5 text-[10px] font-medium leading-none">
          {acks.length}
        </span>
      </button>

      {displayedAcks.length > 0 && (
        <div className="flex flex-col items-center gap-1">
          {displayedAcks.map((ack) => (
            <Tooltip key={ack.email}>
              <TooltipTrigger asChild>
                <div className="flex h-6 w-6 items-center justify-center rounded-full bg-white/20 text-[10px] font-medium text-white backdrop-blur-sm">
                  {getInitials(ack.email)}
                </div>
              </TooltipTrigger>
              <TooltipContent side="left">
                <p>{ack.email}</p>
              </TooltipContent>
            </Tooltip>
          ))}
        </div>
      )}
    </div>
  );
}
