"use client";

import Link from "next/link";
import type { ReactNode } from "react";
import {
  ForwardedMessageSnapshot as ForwardedMessageSnapshotSchema,
  type ForwardedMessageSnapshot,
} from "@slackwsh/contracts";
import { avatarColor } from "../lib/avatar";
import { channelPath } from "../lib/conversations";
import { IconClip, IconLink, IconLock } from "./icons";
import { UserAvatar } from "./UserAvatar";

export function forwardedMessageFromBlocks(blocks: unknown): ForwardedMessageSnapshot | null {
  if (!blocks || typeof blocks !== "object") return null;
  const parsed = ForwardedMessageSnapshotSchema.safeParse((blocks as Record<string, unknown>).forwardedMessage);
  return parsed.success ? parsed.data : null;
}

function ordinalDate(iso: string) {
  const date = new Date(iso);
  const day = date.getDate();
  const mod100 = day % 100;
  const suffix = mod100 >= 11 && mod100 <= 13 ? "th" : day % 10 === 1 ? "st" : day % 10 === 2 ? "nd" : day % 10 === 3 ? "rd" : "th";
  return `${date.toLocaleDateString([], { month: "short" })} ${day}${suffix}`;
}

export function ForwardedMessageCard({
  snapshot,
  workspaceId,
  renderText,
}: {
  snapshot: ForwardedMessageSnapshot;
  workspaceId: string | number;
  renderText: (text: string) => ReactNode;
}) {
  const color = avatarColor(String(snapshot.authorId));
  const isPrivateConversation = snapshot.channelType === "dm" || snapshot.channelType === "group_dm";
  const href = `${channelPath(String(workspaceId), String(snapshot.channelId))}&messageId=${encodeURIComponent(String(snapshot.messageId))}${
    snapshot.parentId == null ? "" : `&threadId=${encodeURIComponent(String(snapshot.parentId))}`
  }`;

  return (
    <div className="forwarded-message-card">
      <div className="forwarded-message-head">
        <UserAvatar
          className="forwarded-message-avatar"
          userId={snapshot.authorId}
          name={snapshot.authorName}
          avatarUrl={snapshot.authorAvatarUrl}
          style={{ background: color.bg, color: color.fg }}
        />
        <div>
          <span><strong>{snapshot.authorName}</strong><time dateTime={snapshot.createdAt}>{ordinalDate(snapshot.createdAt)}</time></span>
          <small>
            {isPrivateConversation ? (
              "From a private conversation"
            ) : (
              <>{"Posted in "}{snapshot.channelType === "private" && <IconLock size={11} />}#{snapshot.channelName ?? "channel"}</>
            )}
          </small>
        </div>
      </div>
      {snapshot.text && <p className="forwarded-message-text">{renderText(snapshot.text)}</p>}
      {snapshot.attachmentNames.length > 0 && (
        <div className="forwarded-message-files">
          {snapshot.attachmentNames.map((name, index) => <span key={`${name}-${index}`}><IconClip size={12} />{name}</span>)}
        </div>
      )}
      <Link className="forwarded-message-link" href={href} aria-label="Open original message" title="Open original message">
        <IconLink size={13} />
      </Link>
    </div>
  );
}
