import { useState } from "react"
import type React from "react"
import { KnowledgeIcon } from "@/components/Option/Knowledge/KnowledgeIcon"

type Props = {
  index: number
  source: {
    name?: string
    url?: string
    mode?: string
    type?: string
    pageContent?: string
    content?: string
    doId?: string
    description?: string
  }
  onSourceClick?: (source: any) => void
}

export const MessageSource: React.FC<Props> = ({
  index,
  source,
  onSourceClick
}) => {
  // Add state for tracking and content visibility
  const [showContent, setShowContent] = useState(false)

  if (source?.mode === "rag" || source?.mode === "chat") {
    return (
      <button
        onClick={() => {
          onSourceClick && onSourceClick(source)
        }}
        className="inline-flex gap-2   cursor-pointer transition-shadow duration-300 ease-in-out hover:shadow-lg  items-center rounded-md bg-gray-100 p-1 text-xs text-gray-800 border border-gray-300 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100 opacity-80 hover:opacity-100">
        <KnowledgeIcon type={source.type} className="h-3 w-3" />
        <span className="text-xs">{source.name}</span>
      </button>
    )
  }

  const onContextMenu = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation
    setShowContent(true)
  }

  return (
    <div className="block items-center gap-1 text-xs text-gray-800 dark:text-gray-100 mb-1">
      <span className="text-xs font-medium"></span>{" "}
      <a
        href={source?.url}
        target="_blank"
        onContextMenu={onContextMenu}
        className="inline-block cursor-pointer transition-shadow duration-300 ease-in-out hover:shadow-lg  items-center rounded-md bg-gray-100 p-1 text-xs text-gray-800 border border-gray-300 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100 opacity-80 hover:opacity-100">
        {source.doId ? (
          <>
            <span className="text-xs">
              [{index + 1}] doid: {source.doId}
            </span>
            <br />
            <span className="text-xs">{source.name}</span>
            {showContent && (
              <div className="mt-2 p-2 border-t border-gray-200 dark:border-gray-700">
                {source.content || source.pageContent || source.description}
              </div>
            )}
          </>
        ) : (
          <>
            <span className="text-xs">
              [{index + 1}] {source.name}
            </span>
            {showContent && (
              <div className="mt-2 p-2 border-t border-gray-200 dark:border-gray-700">
                {source.content || source.pageContent}
              </div>
            )}
          </>
        )}
      </a>
    </div>
  )
}
