import { useMemo } from "react";
import { useEffect, useRef } from "react";
import { marked } from "marked";
import type { ChatMessage, UIButtonData } from "./types";

interface MessageListProps {
  messages: ChatMessage[];
  isTyping: boolean;
  onButtonClick: (button: UIButtonData) => void;
}

function formatTime(ts: number): string {
  const d = new Date(ts);
  const now = new Date();
  const sameDay = d.toDateString() === now.toDateString();
  return sameDay
    ? d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
    : d.toLocaleDateString([], {
        day: "numeric",
        month: "short",
        hour: "2-digit",
        minute: "2-digit",
      });
}

function formatSize(bytes?: number): string {
  if (!bytes) return "";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1048576).toFixed(1)} MB`;
}

function FileCard({ file }: { file: NonNullable<ChatMessage["attachments"]>[number] }) {
  const ext = file.mime_type?.split("/").pop()?.toUpperCase() || file.type;
  return (
    <div className="file-card">
      <span className="file-icon">📎</span>
      <div className="file-info">
        <div className="file-name">{file.filename || "file"}</div>
        <div className="file-meta">
          {[file.size ? formatSize(file.size) : "", ext, file.type]
            .filter(Boolean)
            .join(" · ")}
        </div>
      </div>
      {file.download_url && (
        <a
          className="file-dl"
          href={file.download_url}
          download={file.filename}
          target="_blank"
          rel="noreferrer"
        >
          ⬇ Скачать
        </a>
      )}
    </div>
  );
}

function MsgText({ text, parse_mode }: { text: string; parse_mode?: string }) {
  const html = useMemo(() => {
    if (parse_mode === "markdown") {
      return marked.parse(text, { breaks: true, gfm: true });
    }
    return null;
  }, [text, parse_mode]);

  if (html) {
    return <div className="msg-text" dangerouslySetInnerHTML={{ __html: html }} />;
  }
  return <div className="msg-text">{text}</div>;
}

function ButtonBar({
  buttons,
  onClick,
}: {
  buttons: UIButtonData[];
  onClick: (b: UIButtonData) => void;
}) {
  return (
    <div className="btns">
      {buttons.map((b, i) => (
        <button
          key={i}
          className={`btn btn-${b.style}`}
          onClick={() => onClick(b)}
        >
          {b.label}
        </button>
      ))}
    </div>
  );
}

export function MessageList({
  messages,
  isTyping,
  onButtonClick,
}: MessageListProps) {
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, isTyping]);

  if (messages.length === 0 && !isTyping) {
    return (
      <div className="message-list empty">
        <div className="empty-state">
          <p style={{ fontSize: 32, marginBottom: 8 }}>💬</p>
          <p>Чат пуст.</p>
          <p>Напишите что-нибудь, чтобы начать.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="message-list">
      {messages.map((msg) => (
        <div key={msg.id} className={`message message-${msg.from}`}>
          <div className="msg-hdr">
            <div className={`avatar avatar-${msg.from}`}>
              {msg.from === "user" ? "U" : "λ"}
            </div>
            <span className="msg-name">
              {msg.from === "user" ? "Вы" : "Lambda"}
            </span>
          </div>
          <MsgText text={msg.text} parse_mode={msg.parse_mode} />
          {msg.attachments && msg.attachments.length > 0 && (
            <div className="attach-list">
              {msg.attachments.map((f, i) => (
                <FileCard key={i} file={f} />
              ))}
            </div>
          )}
          {msg.buttons && msg.buttons.length > 0 && (
            <ButtonBar buttons={msg.buttons} onClick={onButtonClick} />
          )}
          <div className="msg-time">{formatTime(msg.timestamp)}</div>
        </div>
      ))}
      {isTyping && (
        <div className="message message-agent">
          <div className="typing-indicator">λ печатает</div>
        </div>
      )}
      <div ref={bottomRef} />
    </div>
  );
}
