import ReactMarkdown from "react-markdown";
import { useState } from "react";
import type { Goal } from "../../types/goal";
import type { Edge, Message } from "../../types/message";
import styles from "./DetailPanel.module.css";
import { ImagePreviewModal } from "../ImagePreview/ImagePreviewModal";
import { extractImagesFromMessage } from "../../utils/imageExtraction";

interface DetailPanelProps {
  node: Goal | Message | null;
  edge: Edge | null;
  messages?: Message[];
  onClose: () => void;
}

export const DetailPanel = ({ node, edge, messages = [], onClose }: DetailPanelProps) => {
  const [previewImage, setPreviewImage] = useState<string | null>(null);

  console.log("DetailPanel - node:", node);
  console.log("DetailPanel - edge:", edge);
  console.log("DetailPanel - messages:", messages);

  const renderImages = (msg: Message) => {
    const images = extractImagesFromMessage(msg);
    if (images.length === 0) return null;
    return (
      <div className="grid grid-cols-3 gap-2 mt-2">
        {images.map((img, idx) => (
          <img
            key={idx}
            src={img.url}
            alt={img.alt || "Extracted"}
            referrerPolicy="no-referrer"
            className="w-full h-20 object-cover rounded border border-gray-200 cursor-pointer hover:opacity-80 transition-opacity bg-gray-50"
            onClick={() => setPreviewImage(img.url)}
          />
        ))}
      </div>
    );
  };

  const renderResultImages = (imageUrls: string[]) => {
    if (!imageUrls || imageUrls.length === 0) return null;
    const normalized = imageUrls
      .map((raw) => String(raw))
      .map((raw) => raw.replace(/^[\s`'"]+|[\s`'"]+$/g, ""))
      .filter((url) => url.startsWith("http") || url.startsWith("data:"));
    if (normalized.length === 0) return null;
    return (
      <div className="grid grid-cols-4 gap-2 mt-2">
        {normalized.map((url, idx) => (
          <img
            key={`${url}-${idx}`}
            src={url}
            alt={`Image ${idx + 1}`}
            referrerPolicy="no-referrer"
            className="w-full h-16 object-cover rounded border border-gray-200 cursor-pointer hover:opacity-80 transition-opacity bg-gray-50"
            onClick={() => setPreviewImage(url)}
            onError={(e) => {
              (e.target as HTMLImageElement).style.display = "none";
            }}
          />
        ))}
      </div>
    );
  };

  const normalizeImageUrl = (raw: unknown) => String(raw).replace(/^[\s`'"]+|[\s`'"]+$/g, "");

  const getValidImageUrls = (values: unknown[]): string[] => {
    return values.map((v) => normalizeImageUrl(v)).filter((url) => url.startsWith("http") || url.startsWith("data:"));
  };

  const title = node ? "节点详情" : edge ? "连线详情" : "详情";

  const renderMessageContent = (content: Message["content"]) => {
    if (!content) return "";
    if (typeof content === "string") return <ReactMarkdown>{content}</ReactMarkdown>;

    const hasText = !!content.text;
    const hasToolCalls = content.tool_calls && content.tool_calls.length > 0;
    const hasToolResult = !!content.tool_name && !!content.result;

    if (hasText || hasToolCalls || hasToolResult) {
      return (
        <>
          {hasText && <ReactMarkdown>{content.text!}</ReactMarkdown>}
          {hasToolCalls && (
            <div className={styles.toolCalls}>
              {content.tool_calls!.map((call, idx) => {
                const anyCall = call as unknown as Record<string, unknown>;
                const fn = anyCall.function as Record<string, unknown> | undefined;
                const name =
                  (fn && (fn.name as string)) ||
                  (anyCall.name as string) ||
                  ((content as unknown as Record<string, unknown>).tool_name as string) ||
                  `tool_${idx}`;
                let args: unknown =
                  (fn && fn.arguments) ||
                  anyCall.arguments ||
                  (content as unknown as Record<string, unknown>).arguments;
                if (typeof args === "string") {
                  try {
                    args = JSON.parse(args);
                  } catch {
                    // keep as string if JSON.parse fails
                  }
                }
                const key = (anyCall.id as string) || `${name}-${idx}`;
                return (
                  <div
                    key={key}
                    className={styles.toolCall}
                  >
                    <div className={styles.toolName}>工具调用: {name}</div>
                    <pre className={styles.toolArgs}>{JSON.stringify(args, null, 2)}</pre>
                  </div>
                );
              })}
            </div>
          )}
          {hasToolResult && (
            <div className={styles.toolResult}>
              <div className={styles.toolName}>工具: {content.tool_name}</div>
              <div className={styles.resultContent}>
                {(() => {
                  let resultData: unknown = content.result;

                  const tryParseEmbeddedJson = (text: string): unknown | null => {
                    const firstArray = text.indexOf("[");
                    const lastArray = text.lastIndexOf("]");
                    if (firstArray !== -1 && lastArray !== -1 && lastArray > firstArray) {
                      const sliced = text.slice(firstArray, lastArray + 1);
                      try {
                        return JSON.parse(sliced);
                      } catch {
                        return null;
                      }
                    }
                    const firstObj = text.indexOf("{");
                    const lastObj = text.lastIndexOf("}");
                    if (firstObj !== -1 && lastObj !== -1 && lastObj > firstObj) {
                      const sliced = text.slice(firstObj, lastObj + 1);
                      try {
                        return JSON.parse(sliced);
                      } catch {
                        return null;
                      }
                    }
                    return null;
                  };

                  if (typeof resultData === "string") {
                    const raw = resultData;
                    try {
                      resultData = JSON.parse(raw);
                    } catch {
                      const embedded = tryParseEmbeddedJson(raw);
                      if (embedded !== null) {
                        resultData = embedded;
                      } else {
                        return <ReactMarkdown>{raw}</ReactMarkdown>;
                      }
                    }
                  }

                  const renderStructuredResult = (value: unknown, field?: string): JSX.Element => {
                    if (Array.isArray(value)) {
                      if (field === "images") {
                        const urls = getValidImageUrls(value);
                        if (urls.length > 0) {
                          return <div>{renderResultImages(urls)}</div>;
                        }
                      }
                      return (
                        <div className="space-y-2">
                          {value.map((item, idx) => (
                            <div
                              key={`${field || "arr"}-${idx}`}
                              className="pl-2 border-l border-slate-200"
                            >
                              <div className="text-xs text-slate-500 mb-1">[{idx}]</div>
                              {renderStructuredResult(item)}
                            </div>
                          ))}
                        </div>
                      );
                    }

                    if (value && typeof value === "object") {
                      return (
                        <div className="space-y-2">
                          {Object.entries(value as Record<string, unknown>).map(([k, v]) => (
                            <div key={k}>
                              <div className="text-xs text-slate-500">{k}</div>
                              <div className="pl-2">{renderStructuredResult(v, k)}</div>
                            </div>
                          ))}
                        </div>
                      );
                    }

                    if (typeof value === "string") {
                      return <span className="whitespace-pre-wrap break-all">{value}</span>;
                    }

                    if (typeof value === "number" || typeof value === "boolean") {
                      return <span>{String(value)}</span>;
                    }

                    if (value === null) {
                      return <span>null</span>;
                    }

                    return <span>{String(value)}</span>;
                  };

                  return renderStructuredResult(resultData);
                })()}
              </div>
            </div>
          )}
        </>
      );
    }

    return <ReactMarkdown>{JSON.stringify(content)}</ReactMarkdown>;
  };

  const isGoal = (node: Goal | Message): node is Goal => {
    // Message 有 message_id 或 role 字段，Goal 没有
    // 优先判断是否为 Message，排除后才是 Goal
    return !("message_id" in node) && !("role" in node) && "status" in node;
  };

  const isMessageNode = (node: Goal | Message): node is Message =>
    "message_id" in node || "role" in node || "sequence" in node;

  const renderKnowledge = (knowledge: Goal["knowledge"]) => {
    if (!knowledge || knowledge.length === 0) return null;

    return (
      <div className={styles.knowledgeList}>
        {knowledge.map((item) => (
          <div
            key={item.id}
            className={styles.knowledgeItem}
          >
            <div className={styles.knowledgeHeader}>
              <span className={styles.knowledgeId}>{item.id}</span>
              <div className={styles.knowledgeMetrics}>
                {item.score !== undefined && <span className={styles.metricScore}>⭐ {item.score}</span>}
                {item.quality_score !== undefined && (
                  <span className={styles.metricQuality}>✨ {item.quality_score.toFixed(1)}</span>
                )}
                {item.metrics?.helpful !== undefined && (
                  <span className={styles.metricHelpful}>👍 {item.metrics.helpful}</span>
                )}
                {item.metrics?.harmful !== undefined && (
                  <span className={styles.metricHarmful}>👎 {item.metrics.harmful}</span>
                )}
              </div>
            </div>
            {item.tags?.type && item.tags.type.length > 0 && (
              <div className={styles.knowledgeTags}>
                {item.tags.type.map((tag) => (
                  <span
                    key={tag}
                    className={styles.tag}
                  >
                    {tag}
                  </span>
                ))}
              </div>
            )}
            <div className={styles.knowledgeScenario}>
              <strong>场景:</strong> {item.scenario}
            </div>
            <div className={styles.knowledgeContent}>
              <ReactMarkdown>{item.content}</ReactMarkdown>
            </div>
          </div>
        ))}
      </div>
    );
  };

  return (
    <aside className={styles.panel}>
      <div className={styles.header}>
        <div className={styles.title}>{title}</div>
        <button
          className={styles.close}
          onClick={onClose}
          aria-label="关闭"
        >
          ×
        </button>
      </div>
      <div className={styles.content}>
        {node && (
          <>
            <div className={styles.sectionTitle}>节点</div>
            <div className={styles.section}>
              <div className={styles.label}>ID</div>
              <div className={styles.value}>{isMessageNode(node) ? node.message_id || node.id : node.id}</div>
            </div>
            {isMessageNode(node) && extractImagesFromMessage(node).length > 0 && (
              <div className={styles.section}>
                <div className={styles.label}>图片</div>
                {renderImages(node)}
              </div>
            )}

            {isGoal(node) ? (
              <>
                <div className={styles.section}>
                  <div className={styles.label}>目标描述</div>
                  <div className={styles.value}>{node.description}</div>
                </div>
                {node.reason && (
                  <div className={styles.section}>
                    <div className={styles.label}>创建理由</div>
                    <div className={styles.value}>{node.reason}</div>
                  </div>
                )}
                {node.summary && (
                  <div className={styles.section}>
                    <div className={styles.label}>总结</div>
                    <div className={styles.value}>{node.summary}</div>
                  </div>
                )}
                <div className={styles.section}>
                  <div className={styles.label}>状态</div>
                  <div className={styles.value}>{node.status}</div>
                </div>
                {node.knowledge && node.knowledge.length > 0 && (
                  <div className={styles.section}>
                    <div className={styles.sectionTitle}>相关知识</div>
                    {renderKnowledge(node.knowledge)}
                  </div>
                )}
              </>
            ) : (
              <>
                {node.description && (
                  <div className={styles.section}>
                    <div className={styles.label}>描述</div>
                    <div className={styles.value}>{node.description}</div>
                  </div>
                )}
                {node.role && (
                  <div className={styles.section}>
                    <div className={styles.label}>角色</div>
                    <div className={styles.value}>{node.role}</div>
                  </div>
                )}
                <div className={styles.section}>
                  <div className={styles.label}>内容</div>
                  <div className={styles.value}>{node.content && renderMessageContent(node.content)}</div>
                </div>
                {node.goal_id && (
                  <div className={styles.section}>
                    <div className={styles.label}>所属目标</div>
                    <div className={styles.value}>{node.goal_id}</div>
                  </div>
                )}
                {node.tokens !== undefined && node.tokens !== null && (
                  <div className={styles.section}>
                    <div className={styles.label}>Token数</div>
                    <div className={styles.value}>{node.tokens}</div>
                  </div>
                )}
              </>
            )}
          </>
        )}
        {messages && messages.length > 0 && (
          <div className={styles.messages}>
            <div className={styles.sectionTitle}>边</div>
            {messages.map((msg, idx) => (
              <div
                key={msg.id || idx}
                className={styles.messageItem}
              >
                <div className={styles.section}>
                  <div className={styles.label}>描述</div>
                  <div className={styles.value}>{msg.description || "-"}</div>
                </div>
                <div className={styles.section}>
                  <div className={styles.label}>内容</div>
                  <div className={styles.value}>{msg.content && renderMessageContent(msg.content)}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <ImagePreviewModal
        visible={!!previewImage}
        onClose={() => setPreviewImage(null)}
        src={previewImage || ""}
      />
    </aside>
  );
};
