"use client";

import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { Clock, FileText, Pause, Pencil, X } from "lucide-react";

import { Button, buttonVariants } from "@/components/ui/button";
import { FIELD_TEXT } from "@/components/ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

import type { QueuedMessage } from "../events";
import { USER_BUBBLE_SHAPE_CLASS, USER_FILE_CHIP_CLASS } from "./UserBubble";

const QUEUE_ACTION_CLASS = buttonVariants({ variant: "ghost", size: "icon-xs", className: "text-ink-4" });

/**
 * 消息流底部的排队消息组: 上方一行说明, 下面每条一个描边气泡, 靠右排.
 * 有条目在原地修改时说明换成「修改中」, 保存之前整队先不发出.
 */
export const QueuedMessages = ({
  queue,
  editingId,
  onCancel,
  onEdit,
  onSaveEdit,
  onCancelEdit,
}: {
  queue: QueuedMessage[];
  /** 正在原地修改的那条; null 表示没有. */
  editingId: string | null;
  onCancel?: (id: string) => void;
  onEdit?: (id: string) => void;
  onSaveEdit?: (id: string, text: string) => void;
  onCancelEdit?: () => void;
}) => {
  if (queue.length === 0) return null;
  const editing = editingId !== null;

  return (
    <div className="flex flex-col items-end gap-2">
      <div className="flex items-center gap-1 text-caption text-muted-foreground">
        {editing ? <Pause size={12} aria-hidden="true" /> : <Clock size={12} aria-hidden="true" />}
        <span>{editing ? "修改中 · 保存之前先不发出" : "排队中 · 点停止可立即发出第 1 条"}</span>
      </div>
      {queue.map((q) => (
        <QueuedBubble
          key={q.id}
          item={q}
          editing={q.id === editingId}
          onCancel={onCancel}
          onEdit={onEdit}
          onSaveEdit={onSaveEdit}
          onCancelEdit={onCancelEdit}
        />
      ))}
    </div>
  );
};

/**
 * 一条排队消息: 描边气泡, 字用弱色, 气泡内右侧是编辑 (铅笔) 与取消排队 (×).
 * 不给 onEdit / onCancel 时对应按钮不显示. editing 时气泡原地变成修改框, 附件照常显示.
 */
export const QueuedBubble = ({
  item,
  editing = false,
  onCancel,
  onEdit,
  onSaveEdit,
  onCancelEdit,
}: {
  item: QueuedMessage;
  editing?: boolean;
  onCancel?: (id: string) => void;
  onEdit?: (id: string) => void;
  onSaveEdit?: (id: string, text: string) => void;
  onCancelEdit?: () => void;
}) => {
  const images = item.attachments.filter((a) => a.kind === "image");
  const files = item.attachments.filter((a) => a.kind === "file");
  const hasText = item.text.trim().length > 0;
  const hasActions = onEdit != null || onCancel != null;

  return (
    <div className={cn("flex max-w-[85%] flex-col items-end gap-2 md:max-w-[75%]", editing && "w-full")}>
      {files.length > 0 && (
        <div className="flex flex-wrap justify-end gap-2 w-full">
          {files.map((f) => (
            <span key={f.url} className={USER_FILE_CHIP_CLASS}>
              <FileText size={16} className="shrink-0 text-muted-foreground" />
              <span className="max-w-[200px] truncate">{f.name ?? "文件附件"}</span>
            </span>
          ))}
        </div>
      )}
      {images.length > 0 && (
        <div className="flex flex-wrap justify-end gap-2 w-full">
          {images.map((img) => (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              key={img.url}
              src={img.url}
              alt={img.name ?? "图片附件"}
              className="block max-w-[160px] max-h-[160px] w-auto h-auto object-cover rounded-xl border border-border"
            />
          ))}
        </div>
      )}
      {editing ? (
        <QueuedEditor item={item} onSave={onSaveEdit} onCancel={onCancelEdit} />
      ) : (
        (hasText || hasActions) && (
          <div
            className={cn(
              USER_BUBBLE_SHAPE_CLASS,
              "flex items-start gap-1.5 border border-border-strong text-muted-foreground",
              hasActions && "pr-1.5",
            )}
          >
            {hasText && <span className="min-w-0">{item.text}</span>}
            {hasActions && (
              <div className="flex shrink-0 items-center">
                {onEdit && (
                  <Tooltip>
                    <TooltipTrigger
                      type="button"
                      onClick={() => onEdit(item.id)}
                      aria-label="编辑这条排队消息"
                      className={QUEUE_ACTION_CLASS}
                    >
                      <Pencil className="size-3.5" />
                    </TooltipTrigger>
                    <TooltipContent>编辑</TooltipContent>
                  </Tooltip>
                )}
                {onCancel && (
                  <Tooltip>
                    <TooltipTrigger
                      type="button"
                      onClick={() => onCancel(item.id)}
                      aria-label="取消这条排队消息"
                      className={QUEUE_ACTION_CLASS}
                    >
                      <X className="size-3.5" />
                    </TooltipTrigger>
                    <TooltipContent>取消排队</TooltipContent>
                  </Tooltip>
                )}
              </div>
            )}
          </div>
        )
      )}
    </div>
  );
};

/**
 * 排队消息的原地修改框: 只改文字, 附件不动. 文本框随内容长高.
 * Cmd/Ctrl+Enter 保存, Esc 取消; 文字为空且没有附件时不能保存.
 */
const QueuedEditor = ({
  item,
  onSave,
  onCancel,
}: {
  item: QueuedMessage;
  onSave?: (id: string, text: string) => void;
  onCancel?: () => void;
}) => {
  const [draft, setDraft] = useState(item.text);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const canSave = draft.trim().length > 0 || item.attachments.length > 0;

  useEffect(() => {
    const el = textareaRef.current;
    if (!el) return;
    el.focus();
    el.setSelectionRange(el.value.length, el.value.length);
  }, []);

  const save = () => {
    if (canSave) onSave?.(item.id, draft);
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.nativeEvent.isComposing) return;
    if (e.key === "Escape") {
      // 修改框里的 Esc 只用来取消修改, 不再往外传: 页面上「连按两次 Esc 停止这一轮」不该把它算进去
      e.preventDefault();
      e.stopPropagation();
      onCancel?.();
    } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
      e.preventDefault();
      save();
    }
  };

  return (
    <div
      role="group"
      aria-label="修改排队消息"
      onKeyDown={handleKeyDown}
      className={cn(USER_BUBBLE_SHAPE_CLASS, "flex w-full flex-col gap-2.5 border border-primary bg-card text-foreground")}
    >
      <textarea
        ref={textareaRef}
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        aria-label="排队消息内容"
        className={cn(FIELD_TEXT, "block w-full resize-none bg-transparent outline-none field-sizing-content")}
      />
      <div className="flex justify-end gap-2">
        <Button variant="ghost" size="sm" onClick={onCancel}>
          取消
        </Button>
        <Button size="sm" disabled={!canSave} onClick={save}>
          保存
        </Button>
      </div>
    </div>
  );
};
