import { useRef } from "react";
import { motion } from "motion/react";
import { Paperclip } from "lucide-react";
import { toast } from "sonner";
import { ChatFlowMessage } from "../../../hooks/useChatFlow";
import { extractTime } from "../../../utils/chatDateUtils";
import { AudioPlayer } from "../AudioPlayer";
import { VideoPlayer } from "../VideoPlayer";
import { EmojiText } from "./EmojiText";
import chatbotAvatarIcon from "../../../assets/chatbot-bot-avatar.png";

interface ChatMessageItemProps {
  message: ChatFlowMessage;
  animationDelay: number;
  onButtonClick: (buttonId: string, action: string) => void;
}

// استایل پیام کاربر باید مستقل از دکمه ارسال و پیام بات بماند.
const USER_BUBBLE_STYLE = {
  background:
    "linear-gradient(145deg, rgba(218, 94, 142, 0.96) 0%, rgba(162, 56, 110, 0.95) 100%)",
  boxShadow:
    "0 0 24px rgba(240,110,168,0.28), 0 12px 28px rgba(84, 22, 60, 0.38), inset 0 1px 0 rgba(255,255,255,0.16)",
  border: "1px solid rgba(255, 178, 214, 0.58)",
  backdropFilter: "blur(14px)",
  WebkitBackdropFilter: "blur(14px)",
} as const;

const BOT_BUBBLE_STYLE = {
  background:
    "linear-gradient(145deg, rgba(52, 34, 76, 0.94) 0%, rgba(35, 24, 62, 0.94) 100%)",
  backgroundImage:
    "linear-gradient(145deg, rgba(52, 34, 76, 0.94) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
  backgroundOrigin: "border-box",
  backgroundClip: "padding-box, border-box",
  boxShadow:
    "0 0 24px rgba(152,104,235,0.24), 0 12px 28px rgba(12, 8, 30, 0.4), inset 0 1px 0 rgba(255,255,255,0.12)",
  border: "0.5px solid transparent",
  backdropFilter: "blur(14px)",
  WebkitBackdropFilter: "blur(14px)",
} as const;

const USER_MEDIA_BUBBLE_STYLE = {
  background: USER_BUBBLE_STYLE.background,
  boxShadow: "0 12px 28px rgba(84, 22, 60, 0.38)",
  border: USER_BUBBLE_STYLE.border,
} as const;

const BOT_MEDIA_BUBBLE_STYLE = {
  background: BOT_BUBBLE_STYLE.background,
  boxShadow: "0 12px 28px rgba(12, 8, 30, 0.4)",
  border: "1px solid rgba(186, 145, 235, 0.4)",
} as const;

const USER_FILE_BUBBLE_STYLE = {
  background: USER_BUBBLE_STYLE.background,
  boxShadow:
    "0 12px 28px rgba(84, 22, 60, 0.38), inset 0 1px 0 rgba(255,255,255,0.12)",
  border: USER_BUBBLE_STYLE.border,
} as const;

const BOT_FILE_BUBBLE_STYLE = {
  background: BOT_BUBBLE_STYLE.background,
  boxShadow:
    "0 12px 28px rgba(12, 8, 30, 0.4), inset 0 1px 0 rgba(255,255,255,0.12)",
  border: "1px solid rgba(186, 145, 235, 0.4)",
} as const;

const chatToastStyle = {
  background:
    "linear-gradient(180deg, rgba(46, 27, 61, 0.95) 0%, rgba(35, 24, 62, 0.97) 100%), linear-gradient(120deg, rgba(124, 58, 237, 0.5) 0%, rgba(249, 115, 22, 0.32) 58%, rgba(250, 204, 21, 0.25) 100%)",
  backgroundOrigin: "border-box",
  backgroundClip: "padding-box, border-box",
  border: "1px solid transparent",
  boxShadow:
    "0 14px 34px rgba(10, 5, 24, 0.42), 0 0 22px rgba(255, 121, 207, 0.18), inset 0 1px 0 rgba(255,255,255,0.16)",
  color: "#FBE7F5",
  backdropFilter: "blur(16px)",
  WebkitBackdropFilter: "blur(16px)",
  width: "fit-content",
  minWidth: "unset",
  maxWidth: "max-content",
  whiteSpace: "nowrap",
  margin: "0 auto",
} as const;

export function ChatMessageItem({ message, animationDelay, onButtonClick }: ChatMessageItemProps) {
  const isUser = message.type === "user";
  const isBot = !isUser;
  const timeDisplay = extractTime(message.datetime1, message.timestamp);
  const textBubbleStyle = isUser ? USER_BUBBLE_STYLE : BOT_BUBBLE_STYLE;
  const mediaBubbleStyle = isUser ? USER_MEDIA_BUBBLE_STYLE : BOT_MEDIA_BUBBLE_STYLE;
  const fileBubbleStyle = isUser ? USER_FILE_BUBBLE_STYLE : BOT_FILE_BUBBLE_STYLE;
  const pressStartRef = useRef<number>(0);
  const copyableText =
    message.mediaType === "file"
      ? message.mediaUrl || ""
      : message.content?.trim() || "";

  const copyWithFallback = (text: string) => {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.setAttribute("readonly", "true");
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    textarea.style.pointerEvents = "none";
    textarea.style.top = "0";
    textarea.style.left = "0";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    textarea.setSelectionRange(0, text.length);

    let copied = false;
    try {
      copied = document.execCommand("copy");
    } finally {
      document.body.removeChild(textarea);
    }

    return copied;
  };

  const copyMessageToClipboard = async () => {
    if (!copyableText) return;

    try {
      if (navigator.clipboard?.writeText && window.isSecureContext) {
        await navigator.clipboard.writeText(copyableText);
      } else if (!copyWithFallback(copyableText)) {
        throw new Error("fallback copy failed");
      }

      toast.success("پیام کپی شد", {
        position: "bottom-center",
        style: chatToastStyle,
      });
    } catch {
      if (copyWithFallback(copyableText)) {
        toast.success("پیام کپی شد", {
          position: "bottom-center",
          style: chatToastStyle,
        });
        return;
      }

      toast.error("کپی پیام انجام نشد", {
        position: "bottom-center",
        style: chatToastStyle,
      });
    }
  };

  const startLongPressCopy = () => {
    if (!copyableText) return;
    pressStartRef.current = Date.now();
  };

  const stopLongPressCopy = () => {
    if (!copyableText) return;
    const pressDuration = Date.now() - pressStartRef.current;
    pressStartRef.current = 0;
    if (pressDuration >= 450) {
      void copyMessageToClipboard();
    }
  };

  const cancelLongPressCopy = () => {
    pressStartRef.current = 0;
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, delay: animationDelay }}
      className={`flex ${isBot ? "justify-end" : "justify-start"} items-start gap-2`}
    >
      {/* Message Bubble */}
      <div className={`max-w-[75%] ${isBot ? "ml-0" : "mr-0"}`}>
        {/* Text Message */}
        {message.mediaType === "text" && (
          <div
            className="relative rounded-[18px] px-5 py-3"
            style={textBubbleStyle}
            onPointerDown={startLongPressCopy}
            onPointerUp={stopLongPressCopy}
            onPointerLeave={cancelLongPressCopy}
            onPointerCancel={cancelLongPressCopy}
            onContextMenu={(event) => {
              if (!copyableText) return;
              event.preventDefault();
              void copyMessageToClipboard();
            }}
          >
            {isBot && message.isTyping && !message.content ? (
              <div className="flex items-center gap-1 py-1">
                <motion.span
                  className="h-2 w-2 rounded-full bg-white/70"
                  animate={{ opacity: [0.3, 1, 0.3] }}
                  transition={{ duration: 1.3, repeat: Infinity, delay: 0 }}
                />
                <motion.span
                  className="h-2 w-2 rounded-full bg-white/70"
                  animate={{ opacity: [0.3, 1, 0.3] }}
                  transition={{ duration: 1.3, repeat: Infinity, delay: 0.2 }}
                />
                <motion.span
                  className="h-2 w-2 rounded-full bg-white/70"
                  animate={{ opacity: [0.3, 1, 0.3] }}
                  transition={{ duration: 1.3, repeat: Infinity, delay: 0.4 }}
                />
              </div>
            ) : (
              <p className="text-white text-sm leading-relaxed whitespace-pre-line">
                <EmojiText text={message.content} />
                {isBot && message.isTyping && (
                  <span
                    className="ml-0.5 inline-block h-4 w-0.5 animate-pulse bg-white/70"
                    style={{ verticalAlign: "text-bottom" }}
                  />
                )}
              </p>
            )}
          </div>
        )}

        {/* Image Message */}
        {message.mediaType === "image" && message.content && (
          <div
            className="rounded-2xl p-3"
            style={mediaBubbleStyle}
            onPointerDown={startLongPressCopy}
            onPointerUp={stopLongPressCopy}
            onPointerLeave={cancelLongPressCopy}
            onPointerCancel={cancelLongPressCopy}
            onContextMenu={(event) => {
              if (!copyableText) return;
              event.preventDefault();
              void copyMessageToClipboard();
            }}
          >
            <div
              className="rounded-xl overflow-hidden"
              style={{
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.2)",
              }}
            >
              <img src={message.content} alt="تصویر" className="w-full h-auto max-h-64 object-cover" />
            </div>
          </div>
        )}

        {/* Audio Message */}
        {message.mediaType === "audio" && message.mediaUrl && (
          <AudioPlayer duration={message.duration || "0:00"} audioUrl={message.mediaUrl} />
        )}

        {/* Video Message */}
        {message.mediaType === "video" && message.content && message.mediaUrl && (
          <VideoPlayer thumbnailUrl={message.content} duration={message.duration || "0:00"} videoUrl={message.mediaUrl} />
        )}

        {/* File Message */}
        {message.mediaType === "file" && message.mediaUrl && (
          <div
            className="rounded-3xl px-5 py-4 flex items-center gap-3"
            style={fileBubbleStyle}
            onPointerDown={startLongPressCopy}
            onPointerUp={stopLongPressCopy}
            onPointerLeave={cancelLongPressCopy}
            onPointerCancel={cancelLongPressCopy}
            onContextMenu={(event) => {
              if (!copyableText) return;
              event.preventDefault();
              void copyMessageToClipboard();
            }}
          >
            <div
              className="w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0"
              style={{
                background: "linear-gradient(135deg, #FFD700 0%, #FFA500 100%)",
                boxShadow: "0 2px 8px rgba(255, 215, 0, 0.4)",
              }}
            >
              <Paperclip className="w-5 h-5 text-white" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-white text-sm font-bold truncate">{message.mediaUrl}</p>
              <p className="text-white/70 text-xs">فایل</p>
            </div>
            <button
              className="text-white hover:text-white/80 text-xs font-bold px-3 py-1 rounded-lg transition-all"
              style={{
                background: "rgba(255, 255, 255, 0.2)",
              }}
              aria-label="دانلود فایل"
            >
              دانلود
            </button>
          </div>
        )}

        {/* Action Buttons */}
        {message.buttons && message.buttons.length > 0 && (
          <div className="mt-3 space-y-2">
            {message.buttons.map((button) => (
              <motion.button
                key={button.id}
                whileTap={{ scale: 0.95 }}
                onClick={() => onButtonClick(button.id, button.action)}
                className="w-full rounded-[18px] px-4 py-3 text-center text-sm font-bold transition-all"
                style={{
                  background:
                    "linear-gradient(135deg, rgba(174, 117, 255, 0.96) 0%, rgba(138, 82, 238, 0.95) 46%, rgba(102, 55, 204, 0.94) 100%)",
                  boxShadow:
                    "0 0 18px rgba(155,108,241,0.4), 0 10px 20px rgba(24, 10, 54, 0.34), inset 0 1px 0 rgba(255,255,255,0.28)",
                  border: "1px solid rgba(212, 184, 255, 0.62)",
                  backdropFilter: "blur(12px)",
                  WebkitBackdropFilter: "blur(12px)",
                  color: "#FFFFFF",
                }}
                aria-label={button.label}
              >
                <EmojiText text={button.label} />
              </motion.button>
            ))}
          </div>
        )}

        {/* Timestamp */}
        <div className={`mt-1 text-xs ${isBot ? "text-left" : "text-right"}`} style={{ color: "rgba(255, 255, 255, 0.5)" }}>
          {timeDisplay}
        </div>
      </div>

      {/* Bot Avatar */}
      {isBot && (
        <div className="flex-shrink-0">
          <div
            className="flex h-12 w-12 items-center justify-center rounded-full border border-[#F0A6D8]/45"
            style={{
              background:
                "radial-gradient(circle at 50% 36%, rgba(255, 187, 232, 0.38) 0%, rgba(134, 74, 164, 0.28) 48%, rgba(26, 18, 54, 0.7) 100%)",
              boxShadow:
                "0 0 14px rgba(255,104,205,0.48), 0 0 28px rgba(255,104,205,0.22), inset 0 1px 0 rgba(255,255,255,0.22)",
            }}
          >
            <img
              src={chatbotAvatarIcon}
              alt="چت‌بات"
              className="h-[43px] w-[43px] object-contain"
            />
          </div>
        </div>
      )}
    </motion.div>
  );
}
