"use client";

/**
 * src/components/artifacts/KnowledgeArtifact.tsx
 *
 * 知识检索结果展示 —— 支持图片、视频、步骤、详情展开。
 * 对应 Artifact type: "knowledge_lesson"
 */

import {
  BookOpen,
  ChevronDown,
  FileText,
  Image as ImageIcon,
  Play,
} from "lucide-react";
import { useState } from "react";
import type {
  ArtifactComponentProps,
  InteractionArtifact,
  KnowledgeBlock,
  KnowledgeLessonProps,
  MediaRef,
} from "@/lib/artifacts/types";

function cx(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

// ── MediaBlock ───────────────────────────────────────────────────────────────

function MediaCard({ ref: mediaRef }: { ref: MediaRef }) {
  const isVideo = mediaRef.type === "video";
  return (
    <div className="flex items-start gap-3 rounded-lg border border-zinc-200 bg-zinc-50 p-3">
      <div
        className={cx(
          "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md",
          isVideo ? "bg-blue-100 text-blue-600" : "bg-emerald-100 text-emerald-600",
        )}
      >
        {isVideo ? <Play className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}
      </div>
      <div className="min-w-0">
        <p className="text-sm font-semibold text-zinc-900">{mediaRef.title}</p>
        {mediaRef.description && (
          <p className="mt-0.5 text-xs text-zinc-500">{mediaRef.description}</p>
        )}
        {mediaRef.url && (
          <a
            href={mediaRef.url}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-1 inline-flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-800"
          >
            <FileText className="h-3 w-3" />
            {isVideo ? "播放视频" : "查看图片"}
          </a>
        )}
      </div>
    </div>
  );
}

// ── KnowledgeBlock renderer ───────────────────────────────────────────────────

function BlockView({ block }: { block: KnowledgeBlock }) {
  const [open, setOpen] = useState(block.type !== "details" || Boolean(block.defaultOpen));

  if (block.type === "summary") {
    return (
      <p className="rounded-lg border border-zinc-200 bg-white p-4 text-sm leading-7 text-zinc-700">
        {block.text}
      </p>
    );
  }

  if (block.type === "key_points") {
    return (
      <div className="rounded-lg border border-zinc-200 bg-white p-4">
        <p className="mb-3 text-xs font-semibold uppercase tracking-widest text-zinc-500">关键点</p>
        <div className="grid gap-2 sm:grid-cols-2 md:grid-cols-3">
          {block.items.map((item) => (
            <div
              key={item}
              className="flex items-start gap-2 rounded-md bg-zinc-50 px-3 py-2 text-sm text-zinc-700"
            >
              <span className="mt-1 h-1.5 w-1.5 flex-shrink-0 rounded-full bg-zinc-400" />
              {item}
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (block.type === "steps") {
    return (
      <div className="rounded-lg border border-zinc-200 bg-white p-4">
        <p className="mb-4 text-xs font-semibold uppercase tracking-widest text-zinc-500">
          处理步骤
        </p>
        <div className="space-y-4">
          {block.steps.map((step, index) => (
            <div key={step.title} className="grid grid-cols-[32px_1fr] gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-zinc-950 text-sm font-bold text-white">
                {index + 1}
              </div>
              <div>
                <p className="font-semibold text-zinc-950">{step.title}</p>
                <p className="mt-1 text-sm leading-6 text-zinc-600">{step.body}</p>
                {step.media && step.media.length > 0 && (
                  <div className="mt-3 grid gap-2">
                    {step.media.map((m) => (
                      <MediaCard key={m.title} ref={m} />
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (block.type === "media") {
    return (
      <div className="grid gap-2">
        {block.media.map((m) => (
          <MediaCard key={m.title} ref={m} />
        ))}
      </div>
    );
  }

  if (block.type === "details") {
    return (
      <div className="rounded-lg border border-zinc-200 bg-white">
        <button
          type="button"
          className="flex w-full items-center justify-between p-4 text-left"
          onClick={() => setOpen((v) => !v)}
        >
          <span className="font-semibold text-zinc-950">{block.title}</span>
          <ChevronDown
            className={cx("h-4 w-4 text-zinc-500 transition", open && "rotate-180")}
          />
        </button>
        {open && (
          <p className="border-t border-zinc-100 p-4 text-sm leading-7 text-zinc-600">
            {block.markdown}
          </p>
        )}
      </div>
    );
  }

  if (block.type === "citations") {
    return (
      <div className="rounded-lg bg-zinc-50 p-4">
        <p className="mb-2 text-xs font-semibold uppercase tracking-widest text-zinc-500">
          引用文档
        </p>
        <div className="flex flex-wrap gap-2">
          {block.citations.map((c) => (
            <span
              key={`${c.title}_${c.location}`}
              className="rounded-full bg-white px-3 py-1 text-xs text-zinc-600 shadow-sm"
            >
              {c.title} · {c.location}
            </span>
          ))}
        </div>
      </div>
    );
  }

  return null;
}

// ── 主组件 ────────────────────────────────────────────────────────────────────

export function KnowledgeArtifact({
  artifact,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "knowledge_lesson" }>>) {
  const props = artifact.props as KnowledgeLessonProps;

  return (
    <section className="w-full max-w-5xl">
      {/* Header */}
      <div className="mb-4 flex items-center gap-3">
        <div className="flex h-11 w-11 items-center justify-center rounded-lg bg-emerald-600 text-white">
          <BookOpen className="h-5 w-5" />
        </div>
        <div>
          <p className="text-xs font-semibold uppercase tracking-[0.18em] text-zinc-500">
            知识检索
          </p>
          <h2 className="text-2xl font-semibold text-zinc-950">{artifact.title}</h2>
        </div>
      </div>

      <div className="rounded-lg border border-zinc-200 bg-white shadow-sm">
        {/* Conclusion */}
        <div className="border-b border-zinc-100 bg-emerald-50 p-5">
          <p className="text-xs font-semibold text-emerald-700">先看结论</p>
          <h3 className="mt-1 text-xl font-semibold text-emerald-950">{props.conclusion}</h3>
        </div>

        {/* Blocks */}
        <div className="space-y-4 p-5">
          {props.blocks.map((block, i) => (
            <BlockView block={block} key={i} />
          ))}
        </div>
      </div>
    </section>
  );
}
