import { useTranslation } from "react-i18next";
import { FiTrash2, FiCornerUpLeft, FiSmile } from "react-icons/fi";
import type { Message as MessageModel } from "@/api/generated/private/models/message";
import type { Chat } from "@/api/generated/private/models/chat";
import Avatar from "@/components/ui/Avatar";
import IconButton from "@/components/ui/IconButton";
import { useAuth } from "@/context/AuthContext";
import { canDeleteMessage } from "@/hooks/usePermissions";
import { formatRelative } from "@/utils/relativeTime";
import { apiSocialMessagesDestroy } from "@/api/generated/private/chat/chat";

interface Props {
  message: MessageModel;
  chat: Chat | null;
  onReply?: (message: MessageModel) => void;
  onReact?: (message: MessageModel, emoji: string) => void;
}

export default function Message({ message, chat, onReply, onReact }: Props) {
  const { t } = useTranslation("social");
  const { user } = useAuth();
  const isOwn = user?.id != null && message.sender === user.id;

  async function handleDelete() {
    if (!confirm("Smazat zprávu?")) return;
    await apiSocialMessagesDestroy(String(message.id));
    // WS delete event will remove from the list; refresh cache as fallback.
  }

  const canDelete = canDeleteMessage(user, message, chat);

  return (
    <div className={`group flex gap-2 px-4 py-1.5 ${isOwn ? "flex-row-reverse" : ""}`}>
      <Avatar name={`user ${message.sender}`} size={28} />
      <div className={`flex max-w-[70%] flex-col ${isOwn ? "items-end" : "items-start"}`}>
        <div
          className={[
            "rounded-2xl px-3 py-2 text-sm break-words whitespace-pre-wrap",
            isOwn
              ? "bg-brand-accent text-brand-bg rounded-br-sm"
              : "bg-brand-bgLight/70 text-brand-text rounded-bl-sm",
          ].join(" ")}
        >
          {message.content}
        </div>
        <div className="mt-0.5 flex items-center gap-2 text-[11px] text-brand-text/50">
          <time dateTime={String(message.created_at)}>
            {formatRelative(message.created_at)}
          </time>
          {message.is_edited && <span>· {t("chat.room.edited")}</span>}
        </div>
        {message.reactions?.length > 0 && (
          <div className="mt-1 flex flex-wrap gap-1">
            {message.reactions.map((r) => (
              <span
                key={r.id}
                className="rounded-full bg-brand-bgLight/60 px-2 py-0.5 text-xs"
              >
                {r.emoji}
              </span>
            ))}
          </div>
        )}
      </div>

      <div className="flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">
        <IconButton
          icon={<FiCornerUpLeft size={14} />}
          label={t("chat.actions.reply")}
          onClick={() => onReply?.(message)}
        />
        <IconButton
          icon={<FiSmile size={14} />}
          label={t("chat.actions.react")}
          onClick={() => onReact?.(message, "👍")}
        />
        {canDelete && (
          <IconButton
            icon={<FiTrash2 size={14} />}
            label={t("chat.actions.delete")}
            onClick={handleDelete}
          />
        )}
      </div>
    </div>
  );
}
