"use client";

import Image from "next/image";
import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { User } from "@/types/types";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import ReadReceipt from "./ReadReceipt";
import VoiceMessagePlayer from "./VoiceMessagePlayer";
import FileMessageBubble from "./FileMessageBubble";
import VideoMessageBubble from "./VideoMessageBubble";
import LocationMessageBubble, {
  parseLocationContent,
} from "./LocationMessageBubble";
import { detectChatFileType } from "@/lib/chat/detectFileType";
import { formatBubbleTime } from "@/lib/chat/formatMessageTime";

export interface ChatMessage {
  _id: string;
  content: string;
  senderId: string;
  receiverId?: string;
  createdAt: string;
  file?: string;
  fileType?: "image" | "video" | "file" | "voice" | "location";
  status?: "pending" | "sent" | "seen";
  replyTo?: {
    _id: string;
    content: string;
    senderName?: string;
  };
  forwardedFrom?: {
    userId: string;
    userName: string;
    displayName: string;
  };
}

interface ChatMessageCardProps {
  message: ChatMessage;
  userDetail: User | undefined;
  selected?: boolean;
  onBubbleClick?: (message: ChatMessage) => void;
}

function parseForwarded(content: string): ChatMessage["forwardedFrom"] | null {
  try {
    const line = content.split("\n")[0];
    const j = JSON.parse(line);
    return j.forwardedFrom ?? null;
  } catch {
    return null;
  }
}

const ChatMessageCard = ({
  message,
  userDetail,
  selected = false,
  onBubbleClick,
}: ChatMessageCardProps) => {
  const isSender = !!(userDetail && message.senderId === userDetail._id);
  const [preview, setPreview] = useState<string | null>(null);

  const forwarded =
    message.forwardedFrom || parseForwarded(message.content || "");
  const locationData = parseLocationContent(message.content);
  const hasLocation = message.fileType === "location" || !!locationData;

  if (!message.content && !message.file && !hasLocation) return null;

  const fileUrl = message.file?.startsWith("blob:")
    ? message.file
    : message.file
      ? IMAGE_BASE_URL + message.file
      : "";

  const fileType = hasLocation
    ? "location"
    : detectChatFileType(message.file || "", message.fileType);

  const textContent =
    message.content &&
    !parseLocationContent(message.content) &&
    !forwarded
      ? message.content.replace(/^\{.*\}\n?/, "").trim()
      : message.content?.replace(/^\{.*\}\n?/, "").trim() || "";

  const showTextBubble =
    textContent &&
    fileType !== "file" &&
    fileType !== "location" &&
    (!message.file || (fileType === "image" && textContent));

  const tailClass = isSender ? "bubble-tail-out" : "bubble-tail-in";
  const timeLabel = formatBubbleTime(message.createdAt);

  const TimeInline = () => (
    <span
      className={`message-time-inline ${isSender ? "text-white/70" : "text-neutral-400"}`}
    >
      {timeLabel}
      {isSender && (
        <span className="mr-1 inline-flex align-middle">
          <ReadReceipt status={message.status} />
        </span>
      )}
    </span>
  );

  const TimeBelow = () => (
    <span
      className={`message-time-below mt-0.5 block text-[10px] tabular-nums text-neutral-400 ${isSender ? "text-left" : "text-right"}`}
    >
      {timeLabel}
      {isSender && (
        <span className="mr-1 inline-flex">
          <ReadReceipt status={message.status} />
        </span>
      )}
    </span>
  );

  const handleBubbleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onBubbleClick?.(message);
  };

  return (
    <>
      <motion.div
        layout
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        className={`message-enter relative my-0.5 flex w-full ${isSender ? "justify-end" : "justify-start"}`}
        dir="rtl"
      >
        <div
          className={`relative flex w-full max-w-[min(88%,340px)] flex-col sm:max-w-[85%] ${isSender ? "items-end" : "items-start"}`}
        >
          {forwarded && (
            <Link
              href={`/users/${forwarded.userName}`}
              className="mb-0.5 text-[11px] font-semibold text-[#0095f6]"
              onClick={(e) => e.stopPropagation()}
            >
              {forwarded.displayName}
            </Link>
          )}

          {message.replyTo && (
            <div className="mb-1 max-w-full rounded-lg border-r-2 border-[#0095f6] bg-black/5 px-2 py-1 text-[11px] opacity-90 dark:bg-white/10">
              <span className="font-semibold text-[#0095f6]">
                {message.replyTo.senderName}
              </span>
              <p className="truncate">{message.replyTo.content}</p>
            </div>
          )}

          <button
            type="button"
            onClick={handleBubbleClick}
            className={`gentle-transition relative text-right outline-none ${tailClass} ${
              selected ? "ring-2 ring-[#0095f6]/50 rounded-2xl" : ""
            }`}
          >
            {fileType === "image" && fileUrl && (
              <div
                className="block overflow-hidden rounded-2xl"
                onClick={(e) => {
                  e.stopPropagation();
                  setPreview(fileUrl);
                }}
              >
                <div className="relative aspect-[3/4] w-44 sm:w-52">
                  <Image fill src={fileUrl} alt="" className="object-cover" sizes="208px" />
                </div>
                <TimeBelow />
              </div>
            )}

            {fileType === "video" && fileUrl && (
              <div>
                <VideoMessageBubble
                  src={fileUrl}
                  isOutgoing={isSender}
                  onOpen={() => setPreview(fileUrl)}
                />
                <TimeBelow />
              </div>
            )}

            {fileType === "voice" && fileUrl && (
              <div className={isSender ? "chat-bubble-out rounded-2xl p-1" : "chat-bubble-in rounded-2xl p-1"}>
                <VoiceMessagePlayer src={fileUrl} isOutgoing={isSender} />
                <TimeBelow />
              </div>
            )}

            {fileType === "file" && fileUrl && (
              <div>
                <FileMessageBubble
                  url={fileUrl}
                  fileName={textContent || "فایل"}
                  isOutgoing={isSender}
                />
                <TimeBelow />
              </div>
            )}

            {fileType === "location" && locationData && (
              <div>
                <LocationMessageBubble location={locationData} isOutgoing={isSender} />
                <TimeBelow />
              </div>
            )}

            {showTextBubble && !message.file && (
              <div
                className={`chat-text-bubble ${isSender ? "chat-bubble-out" : "chat-bubble-in"} px-3 py-2 text-[15px]`}
              >
                <p className="chat-message-text">{textContent}</p>
                <TimeInline />
              </div>
            )}
          </button>
        </div>
      </motion.div>

      <AnimatePresence>
        {preview && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/95"
            onClick={() => setPreview(null)}
          >
            <motion.div
              initial={{ scale: 0.9 }}
              animate={{ scale: 1 }}
              className="max-h-[92vh] max-w-[95vw] p-4"
              onClick={(e) => e.stopPropagation()}
            >
              {fileType === "video" ? (
                <video src={preview} controls autoPlay className="max-h-[88vh] rounded-lg" />
              ) : (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={preview} alt="" className="max-h-[88vh] object-contain" />
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default ChatMessageCard;
