import React, { useCallback, useMemo } from 'react';

import useStudioStore from '../../../../Store/Studio/StudioSlice';
import useCharacterStore from '../../../../Store/SideBarLeft/CharacterSlice';
import { resolveBoundCharacterName } from '../../../Studio/studioRunUtils';

import './StudioRunControls.css';

function StudioRunControls() {
  const {
    projects,
    meta,
    runProjectId,
    currentRun,
    runLoading,
    runCreating,
    runAdvancing,
    runSessionEntered,
    setRunProjectId,
    setRunSessionEntered,
    fetchWorkflowVariables,
    fetchRuns,
    selectRun,
    createRun,
  } = useStudioStore();

  const characters = useCharacterStore((s) => s.characters);

  const boundCharacterName = useMemo(() => {
    return resolveBoundCharacterName({
      boundCharacterVar: currentRun?.workflowVariables?.['workflow.boundCharacter'],
      characterId: meta?.characterId,
      characters,
    });
  }, [currentRun?.workflowVariables, meta?.characterId, characters]);

  const handleProjectChange = useCallback(
    async (e) => {
      const projectId = e.target.value;
      setRunProjectId(projectId);
      setRunSessionEntered(false);
      await fetchWorkflowVariables(projectId);
      const list = await fetchRuns(projectId);
      if (list[0]?.id) {
        await selectRun(list[0].id);
      }
    },
    [
      setRunProjectId,
      setRunSessionEntered,
      fetchWorkflowVariables,
      fetchRuns,
      selectRun,
    ]
  );

  const handleNewRun = useCallback(async () => {
    if (!runProjectId) return;
    setRunSessionEntered(false);
    await createRun(runProjectId);
  }, [runProjectId, setRunSessionEntered, createRun]);

  const inSession = runSessionEntered && !!currentRun;

  return (
    <div className="studio-run-topbar-controls">
      <label className="studio-run-topbar-label">
        <span className="studio-run-topbar-label-text">项目</span>
        <select
          className="studio-run-topbar-select"
          value={runProjectId || ''}
          onChange={handleProjectChange}
          disabled={runLoading || runCreating || runAdvancing}
          aria-label="选择 Studio 项目"
        >
          {projects.length === 0 ? (
            <option value="">暂无项目</option>
          ) : (
            projects.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))
          )}
        </select>
      </label>

      <button
        type="button"
        className="studio-run-topbar-btn studio-run-topbar-btn--primary"
        onClick={handleNewRun}
        disabled={!runProjectId || runCreating || runAdvancing}
      >
        {runCreating ? '创建中…' : '新开会话'}
      </button>

      {boundCharacterName ? (
        <div className="studio-run-topbar-character" title="绑定角色卡">
          <span className="studio-run-topbar-character-icon" aria-hidden="true">
            🎭
          </span>
          <span className="studio-run-topbar-character-name">{boundCharacterName}</span>
        </div>
      ) : null}

      {inSession ? (
        <button
          type="button"
          className="studio-run-topbar-btn studio-run-topbar-btn--ghost"
          onClick={() => setRunSessionEntered(false)}
        >
          退出会话
        </button>
      ) : null}
    </div>
  );
}

export default StudioRunControls;
