import { LoaderCircle, Play } from "lucide-react";
import { useState } from "react";
import { Link } from "react-router-dom";
import { FavoriteButton } from "../favorites/FavoriteButton";
import { useI18n } from "../i18n";
import { useLocalizedPath } from "../useLocalizedPath";
import type { Attachment, Post } from "../types/post";
import { DownloadCloudIcon } from "./icons/DownloadCloudIcon";
import {
  mediaSaveKindFromAttachment,
  useSaveToAlbumGuide,
} from "./SaveToAlbumGuide";
import { useToast } from "./Toast";
import { downloadAttachment } from "./messageStream/utils/downloadFile";
import { fileIcon } from "./messageStream/utils/fileIcon";
import {
  filenameWithExtension,
  splitFilename,
} from "./messageStream/utils/filenameDisplay";
import { formatBytes } from "./messageStream/utils/formatBytes";
import { formatDateTime } from "./messageStream/utils/formatTime";
import { postDisplayText } from "./messageStream/utils/postText";
import { autolink } from "./messageStream/utils/autolink";

function LatestActions({
  post,
  attachment,
}: {
  post: Post;
  attachment?: Attachment;
}) {
  const { t } = useI18n();
  const { showToast } = useToast();
  const { showSaveToAlbumGuide } = useSaveToAlbumGuide();
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownload = async () => {
    if (!attachment || isDownloading) return;
    setIsDownloading(true);
    try {
      await downloadAttachment(post.id, attachment.id, attachment.filename);
      const mediaKind = mediaSaveKindFromAttachment(attachment);
      if (mediaKind) showSaveToAlbumGuide(mediaKind);
    } catch {
      showToast(t("downloadFail"), "error");
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <div className="relative z-20 flex shrink-0 items-center gap-2">
      <FavoriteButton resourceId={post.id} size="sm" />
      {attachment ? (
        <button
          type="button"
          onClick={(event) => {
            event.preventDefault();
            event.stopPropagation();
            void handleDownload();
          }}
          disabled={isDownloading}
          aria-label={
            isDownloading ? t("downloading") : `Download ${attachment.filename}`
          }
          aria-busy={isDownloading}
          className="relative z-20 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#191921] transition hover:bg-[#22232D] disabled:cursor-wait"
        >
          {isDownloading ? (
            <LoaderCircle
              className="h-5 w-5 animate-spin text-[#A8A9AE]"
              strokeWidth={2.3}
            />
          ) : (
            <DownloadCloudIcon />
          )}
        </button>
      ) : null}
    </div>
  );
}

function Footer({ post, attachment }: { post: Post; attachment?: Attachment }) {
  return (
    <div className="flex min-h-16 items-center justify-between gap-3 px-4 py-3">
      <time
        dateTime={post.publishedAt}
        className="shrink-0 text-[12px] font-medium leading-[19.2px] text-[#A8A9AE]"
      >
        {formatDateTime(post.publishedAt)}
      </time>
      <LatestActions post={post} attachment={attachment} />
    </div>
  );
}

function attachmentPreview(att: Attachment | undefined): string {
  if (!att) return "";
  return att.thumbnailUrl ?? att.posterUrl ?? att.thumbUrl ?? att.url ?? "";
}

function FileCard({ post, att }: { post: Post; att: Attachment }) {
  const { lang } = useI18n();
  const { Icon, color } = fileIcon({ mime: att.mime, filename: att.filename });
  const displayFilename = filenameWithExtension(att.filename, att.mime);
  const text = postDisplayText(post, lang);

  return (
    <article className="relative flex flex-col overflow-hidden rounded-2xl bg-[#272632] text-left">
      <CardLink postId={post.id} />
      <div className="flex min-h-[52px] min-w-0 items-center gap-4 px-4 pt-3">
        <div
          className="flex h-[52px] w-[52px] shrink-0 items-center justify-center rounded-full"
          style={{ backgroundColor: color }}
          aria-hidden
        >
          <Icon className="h-8 w-8 text-white" strokeWidth={2.1} />
        </div>
        <div className="min-w-0 flex-1">
          <div
            className="flex min-w-0 items-baseline text-[15px] font-medium leading-6 text-ark-gold"
            title={displayFilename}
          >
            {(() => {
              const { base, ext } = splitFilename(displayFilename);
              const tailChars = Math.min(8, base.length);
              const head = base.slice(0, base.length - tailChars);
              const tail = base.slice(base.length - tailChars) + ext;
              return (
                <>
                  <span className="min-w-0 truncate">{head}</span>
                  <span className="shrink-0 whitespace-pre">{tail}</span>
                </>
              );
            })()}
          </div>
          <div className="text-[12px] font-medium leading-[19.2px] text-[#A8A9AE]">
            {formatBytes(att.sizeBytes)}
          </div>
        </div>
      </div>
      <div className="whitespace-pre-wrap break-words px-4 pt-3 text-[15px] font-medium leading-6 text-white">
        {text || post.title || displayFilename}
      </div>
      <Footer post={post} attachment={att} />
    </article>
  );
}

function MediaGrid({ attachments }: { attachments: Attachment[] }) {
  const visible = attachments.slice(0, 4);
  const extra = Math.max(0, attachments.length - visible.length);
  if (visible.length <= 1) {
    const src = attachmentPreview(visible[0]);
    return src ? (
      <img
        src={src}
        alt=""
        className="h-full w-full object-cover"
        loading="lazy"
        decoding="async"
      />
    ) : (
      <div className="h-full w-full bg-black" />
    );
  }
  return (
    <div className="grid h-full w-full grid-cols-2 grid-rows-2 gap-0">
      {visible.map((att, index) => (
        <div key={att.id} className="relative overflow-hidden bg-black">
          <img
            src={attachmentPreview(att)}
            alt=""
            className="h-full w-full object-cover"
            loading="lazy"
            decoding="async"
          />
          {extra > 0 && index === visible.length - 1 ? (
            <div className="absolute inset-0 grid place-items-center bg-black/55 text-[24px] font-bold text-white backdrop-blur-sm">
              +{extra}
            </div>
          ) : null}
        </div>
      ))}
    </div>
  );
}

function MediaBadge({ att }: { att?: Attachment }) {
  if (!att) return null;
  return (
    <div className="absolute left-3 top-3 z-20 inline-flex h-8 items-center overflow-hidden rounded-full bg-black/75 text-[12px] font-medium text-white shadow-lg backdrop-blur">
      <span className="grid h-8 w-8 place-items-center rounded-full bg-[#3a3a40]">
        <DownloadCloudIcon />
      </span>
      <span className="px-3">{formatBytes(att.sizeBytes)}</span>
    </div>
  );
}

function VisualCard({ post }: { post: Post }) {
  const { lang } = useI18n();
  const att = post.attachments[0];
  const isVideo = att?.kind === "video" || att?.mime.startsWith("video/");
  const text = postDisplayText(post, lang);

  return (
    <article className="relative flex flex-col overflow-hidden rounded-2xl bg-[#272632] text-left">
      <CardLink postId={post.id} />
      <div
        className={`relative overflow-hidden bg-black ${
          isVideo ? "aspect-[416/180]" : "aspect-[416/230]"
        }`}
      >
        <MediaGrid attachments={post.attachments} />
        <MediaBadge att={att} />
        {isVideo ? (
          <div className="absolute inset-0 grid place-items-center">
            <span className="grid h-14 w-14 place-items-center rounded-full bg-black/55 text-white backdrop-blur-sm">
              <Play className="ml-1 h-7 w-7 fill-current" />
            </span>
          </div>
        ) : null}
      </div>
      {text || post.title ? (
        <div className="message-stream-copyable-text whitespace-pre-wrap break-words px-4 pt-3 text-[15px] font-medium leading-6 text-white">
          {autolink(text || post.title || "")}
        </div>
      ) : null}
      <Footer post={post} attachment={att} />
    </article>
  );
}

function CardLink({ postId }: { postId: string }) {
  const lp = useLocalizedPath();
  return (
    <Link
      to={lp(`/browse?post=${encodeURIComponent(postId)}`)}
      aria-label="Open post"
      className="absolute inset-0 z-10 rounded-2xl outline-none focus-visible:ring-2 focus-visible:ring-ark-gold/70"
    />
  );
}

export function LatestUpdateCard({ post }: { post: Post }) {
  const first = post.attachments[0];
  const isFile =
    !!first &&
    !(
      first.kind === "image" ||
      first.kind === "video" ||
      first.mime.startsWith("image/") ||
      first.mime.startsWith("video/")
    );
  if (isFile) return <FileCard post={post} att={first} />;
  return <VisualCard post={post} />;
}
