"use client";

import { ChevronRight } from "lucide-react";
import type { PersonaState } from "@/shared/ai-elements/persona";
import { cn } from "@/lib/utils";
import {
  MAP_CONTROL_SURFACE_CLASS_NAME,
  MAP_MAJOR_PANEL_RADIUS_CLASS_NAME
} from "@/features/map/core/components/map-control-styles";
import { AgentPersona } from "./agent-persona";

type AgentCollapsedRailProps = {
  personaState?: PersonaState;
  statusLabel?: string;
  onExpand: () => void;
};

export function AgentCollapsedRail({ personaState, statusLabel = "Agent", onExpand }: AgentCollapsedRailProps) {
  const state = getCollapsedAgentState(statusLabel, personaState);

  return (
    <aside className={cn("agent-rail-enter pointer-events-auto w-[188px] p-2", MAP_MAJOR_PANEL_RADIUS_CLASS_NAME, MAP_CONTROL_SURFACE_CLASS_NAME)}>
      <div className="agent-panel-control agent-rail-item rounded-2xl p-2">
        <div className="flex items-center gap-2">
          <AgentPersona
            className="h-10 w-10"
            fallbackClassName="h-10 w-10"
            state={personaState}
            statusLabel={statusLabel}
          />
          <div className="min-w-0 flex-1">
            <p className="truncate text-xs font-semibold text-slate-950">HydroAgent</p>
            <p className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs font-semibold text-slate-500">
              <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", state.dotClassName)} />
              <span className="truncate" title={statusLabel}>{state.label}</span>
            </p>
          </div>
          <button
            type="button"
            aria-label="展开 Agent 面板"
            title="展开 Agent 面板"
            onClick={onExpand}
            className="agent-panel-primary-icon grid h-9 w-9 shrink-0 place-items-center rounded-xl transition"
          >
            <ChevronRight size={17} aria-hidden="true" />
          </button>
        </div>
      </div>
    </aside>
  );
}

function getCollapsedAgentState(statusLabel: string, personaState?: PersonaState) {
  if (personaState === "asleep" || /失败|不可用|错误|降级/.test(statusLabel)) {
    return {
      label: "离线",
      dotClassName: "bg-red-500"
    };
  }

  if (personaState === "listening") {
    return {
      label: "待确认",
      dotClassName: "bg-orange-500"
    };
  }

  if (personaState === "thinking") {
    return {
      label: "处理中",
      dotClassName: "bg-blue-500"
    };
  }

  return {
    label: "在线",
    dotClassName: "bg-emerald-500"
  };
}
