import type { ProjectRole } from "@qjclaw/shared-types"
import { Fragment } from "react"
import { renderRoleIcon } from "../chat/roleIconPaths"

export interface CollaborationHandoff {
  fromRoleId: string
  toRoleId: string
  label: string
}

interface RoleCollaborationFlowProps {
  roles: ProjectRole[]
  handoffs: CollaborationHandoff[]
  activeRoleId?: string
  isStreaming?: boolean
}

export function RoleCollaborationFlow({ roles, handoffs, activeRoleId, isStreaming }: RoleCollaborationFlowProps) {
  if (!roles || roles.length === 0) return null

  const handoffByFromId = new Map(handoffs.map((h) => [h.fromRoleId, h]))

  return (
    <div className="role-collaboration-flow">
      <div className="collab-header">
        <span className="collab-label">运营团队</span>
      </div>
      <div className="collab-pipeline">
        {roles.map((role, index) => {
          const isActive = isStreaming && activeRoleId === role.id
          const handoff = handoffByFromId.get(role.id)
          return (
            <Fragment key={role.id}>
              <div
                className={`collab-role-card${isActive ? " collab-role-active" : ""}`}
                title={`${role.name}：${role.description}`}
              >
                <div className="collab-role-icon" aria-hidden="true">
                  {renderRoleIcon(role.icon, { width: 22, height: 22, strokeWidth: 1.6 })}
                </div>
                <div className="collab-role-body">
                  <strong className="collab-role-name">{role.name}</strong>
                  <span className="collab-role-desc">{role.description}</span>
                </div>
                {isActive ? (
                  <span className="collab-role-dot active" aria-label="工作中" />
                ) : null}
              </div>
              {handoff ? (
                <div className="collab-connector">
                  <div className="collab-connector-line" aria-hidden="true">
                    <span className="collab-connector-arrow" />
                  </div>
                  <span className="collab-handoff-label">{handoff.label}</span>
                </div>
              ) : index < roles.length - 1 ? (
                <div className="collab-connector">
                  <div className="collab-connector-line" aria-hidden="true">
                    <span className="collab-connector-arrow" />
                  </div>
                </div>
              ) : null}
            </Fragment>
          )
        })}
      </div>
    </div>
  )
}
