<template>
  <div
    class="host-workspace-dialog-overlay"
    role="dialog"
    aria-modal="true"
    :aria-label="workspaceKind === 'project' ? '管理项目' : '管理工作区'"
    @click.self="handleOverlayClose"
  >
    <form class="host-workspace-dialog host-workspace-manage" @submit.prevent="submitCreate">
      <div class="host-workspace-dialog__header">
        <div class="host-workspace-dialog__title">
          {{ workspaceKind === 'project' ? '管理项目' : '管理工作区' }}
        </div>
        <button
          type="button"
          class="host-workspace-dialog__close"
          :disabled="busy"
          @click="$emit('close')"
        >
          关闭
        </button>
      </div>

      <div class="host-workspace-dialog__body">
        <section class="workspace-manage-section">
          <div class="workspace-manage-section__title">
            {{ workspaceKind === 'project' ? '新建项目' : '新建工作区' }}
          </div>
          <label v-if="workspaceKind !== 'project'" class="host-workspace-dialog__field">
            <span class="host-workspace-dialog__label">工作区路径</span>
            <input
              v-model="createPath"
              type="text"
              class="host-workspace-dialog__input"
              placeholder="请输入绝对路径或相对仓库路径"
              autocomplete="off"
              :disabled="busy"
            />
          </label>
          <label class="host-workspace-dialog__field">
            <span class="host-workspace-dialog__label">
              {{ workspaceKind === 'project' ? '项目名称' : '工作区名称（可选）' }}
            </span>
            <input
              v-model="createLabel"
              type="text"
              class="host-workspace-dialog__input"
              :placeholder="workspaceKind === 'project' ? '例如：客户 A 项目' : '例如：客户A项目'"
              autocomplete="off"
              :disabled="busy"
            />
          </label>
          <button type="submit" class="host-workspace-dialog__btn primary" :disabled="busy">
            {{ createSubmitting ? '创建中...' : (workspaceKind === 'project' ? '新建项目' : '新建工作区') }}
          </button>
        </section>

        <section class="workspace-manage-section">
          <div class="workspace-manage-section__title">
            {{ workspaceKind === 'project' ? '已有项目' : '已有工作区' }}
          </div>
          <div v-if="workspaces.length" class="workspace-manage-list">
            <div
              v-for="item in workspaces"
              :key="item.workspace_id"
              class="workspace-manage-row"
              :class="{ current: item.workspace_id === currentWorkspaceId }"
            >
              <div class="workspace-manage-main">
                <input
                  class="host-workspace-dialog__input workspace-manage-name"
                  :value="renameDrafts[item.workspace_id] ?? item.label"
                  :disabled="busy"
                  @input="setRenameDraft(item.workspace_id, ($event.target as HTMLInputElement).value)"
                />
                <div v-if="workspaceKind !== 'project'" class="workspace-manage-path">
                  {{ item.path || '（未配置路径）' }}
                </div>
                <div class="workspace-manage-badges">
                  <span v-if="item.workspace_id === defaultWorkspaceId" class="workspace-manage-badge default">
                    默认
                  </span>
                  <span v-if="Number(item.running_task_count || 0) > 0" class="workspace-manage-badge running">
                    运行中
                  </span>
                </div>
              </div>
              <div class="workspace-manage-actions">
                <button
                  type="button"
                  class="host-workspace-dialog__btn ghost"
                  :class="{ active: item.workspace_id === defaultWorkspaceId }"
                  :disabled="busy || item.workspace_id === defaultWorkspaceId"
                  @click="submitSetDefault(item)"
                >
                  {{ item.workspace_id === defaultWorkspaceId ? '已默认' : '设为默认' }}
                </button>
                <button
                  type="button"
                  class="host-workspace-dialog__btn ghost"
                  :disabled="busy || !hasRenameChange(item)"
                  @click="submitRename(item)"
                >
                  重命名
                </button>
                <button
                  type="button"
                  class="host-workspace-dialog__btn danger"
                  :disabled="busy || !canDelete(item)"
                  @click="$emit('delete', item)"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
          <div v-else class="workspace-manage-empty">
            {{ workspaceKind === 'project' ? '暂无项目' : '暂无工作区' }}
          </div>
        </section>

        <div v-if="errorMessage" class="host-workspace-dialog__error">{{ errorMessage }}</div>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';

defineOptions({ name: 'HostWorkspaceManageDialog' });

type WorkspaceItem = {
  workspace_id: string;
  label: string;
  path?: string;
  running_task_count?: number;
};

const props = defineProps<{
  workspaces: WorkspaceItem[];
  currentWorkspaceId?: string;
  defaultWorkspaceId?: string;
  workspaceKind?: 'workspace' | 'project';
  busy?: boolean;
  createSubmitting?: boolean;
  errorMessage?: string;
}>();

const emits = defineEmits<{
  (event: 'close'): void;
  (event: 'create', payload: { path: string; label: string }): void;
  (event: 'rename', payload: { workspace_id: string; label: string }): void;
  (event: 'delete', item: WorkspaceItem): void;
  (event: 'setDefault', payload: { workspace_id: string }): void;
}>();

const workspaceKind = props.workspaceKind || 'workspace';
const createPath = ref('');
const createLabel = ref('');
const renameDrafts = reactive<Record<string, string>>({});

watch(
  () => props.workspaces,
  (items) => {
    for (const item of items || []) {
      renameDrafts[item.workspace_id] = item.label || item.workspace_id;
    }
  },
  { immediate: true }
);

const handleOverlayClose = () => {
  if (props.busy) return;
  emits('close');
};

const setRenameDraft = (workspaceId: string, value: string) => {
  renameDrafts[workspaceId] = value;
};

const hasRenameChange = (item: WorkspaceItem) => {
  const draft = String(renameDrafts[item.workspace_id] ?? '').trim();
  return !!draft && draft !== String(item.label || '').trim();
};

const canDelete = (item: WorkspaceItem) => {
  if (Number(item.running_task_count || 0) > 0) return false;
  if (workspaceKind === 'project' && item.workspace_id === 'default') return false;
  return true;
};

const submitCreate = () => {
  emits('create', {
    path: createPath.value.trim(),
    label: createLabel.value.trim()
  });
};

const submitRename = (item: WorkspaceItem) => {
  emits('rename', {
    workspace_id: item.workspace_id,
    label: String(renameDrafts[item.workspace_id] ?? '').trim()
  });
};

const submitSetDefault = (item: WorkspaceItem) => {
  if (item.workspace_id === props.defaultWorkspaceId) return;
  emits('setDefault', { workspace_id: item.workspace_id });
};
</script>

<style scoped>
.host-workspace-dialog-overlay {
  position: fixed;
  inset: 0;
  z-index: 1300;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: var(--theme-overlay-scrim);
  backdrop-filter: blur(10px);
}

.host-workspace-dialog {
  width: min(680px, 96vw);
  height: min(760px, 92vh);
  border-radius: 18px;
  border: 1px solid var(--theme-control-border-strong);
  background: var(--theme-surface-card);
  box-shadow: var(--theme-shadow-soft);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.host-workspace-dialog__header,
.host-workspace-dialog__actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 16px 18px;
  border-bottom: 1px solid var(--theme-control-border);
}

.host-workspace-dialog__title {
  font-size: 16px;
  font-weight: 700;
  color: var(--claude-text);
}

.host-workspace-dialog__close,
.host-workspace-dialog__btn {
  border: 1px solid var(--theme-control-border-strong);
  background: transparent;
  color: var(--claude-text-secondary);
  border-radius: 10px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
}

.host-workspace-dialog__close:disabled,
.host-workspace-dialog__btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.host-workspace-dialog__body {
  padding: 16px 18px;
  display: grid;
  grid-template-rows: auto minmax(0, 1fr) auto;
  gap: 16px;
  overflow: hidden;
}

.workspace-manage-section {
  display: grid;
  gap: 10px;
}

.workspace-manage-section__title {
  font-size: 13px;
  font-weight: 700;
  color: var(--claude-text-secondary);
}

.host-workspace-dialog__field {
  display: grid;
  gap: 6px;
}

.host-workspace-dialog__label,
.workspace-manage-path {
  font-size: 12px;
  color: var(--claude-text-secondary);
}

.host-workspace-dialog__input {
  border: 1px solid var(--theme-control-border-strong);
  border-radius: 10px;
  background: var(--theme-surface-soft);
  color: var(--claude-text);
  padding: 9px 11px;
  font-size: 14px;
  line-height: 1.4;
  outline: none;
}

.host-workspace-dialog__input:focus {
  border-color: var(--claude-accent);
  box-shadow: 0 0 0 2px color-mix(in srgb, var(--claude-accent) 20%, transparent);
}

.host-workspace-dialog__btn.primary {
  justify-self: flex-start;
  background: var(--claude-accent);
  border-color: var(--claude-accent-strong);
  color: var(--on-accent);
}

.host-workspace-dialog__btn.danger {
  color: var(--state-danger);
  border-color: color-mix(in srgb, var(--state-danger) 45%, var(--theme-control-border-strong));
}

.workspace-manage-list {
  display: grid;
  align-content: start;
  gap: 8px;
  min-height: 0;
  max-height: 100%;
  overflow: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.workspace-manage-list::-webkit-scrollbar {
  display: none;
}

.workspace-manage-row {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 10px;
  padding: 10px;
  border: 1px solid var(--theme-control-border);
  border-radius: 12px;
  background: var(--theme-surface-soft);
}

.workspace-manage-row.current {
  border-color: color-mix(in srgb, var(--claude-accent) 45%, var(--theme-control-border));
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--claude-accent) 18%, transparent);
}

.workspace-manage-main {
  display: grid;
  gap: 6px;
  min-width: 0;
}

.workspace-manage-name {
  width: 100%;
}

.workspace-manage-actions,
.workspace-manage-badges {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
}

.workspace-manage-badge {
  font-size: 11px;
  color: var(--claude-text-secondary);
  border: 1px solid var(--theme-control-border);
  border-radius: 999px;
  padding: 2px 7px;
}

.workspace-manage-badge.running {
  color: var(--claude-accent);
}

.workspace-manage-badge.default {
  color: var(--state-success);
  border-color: color-mix(in srgb, var(--state-success) 45%, var(--theme-control-border-strong));
}

.workspace-manage-empty {
  font-size: 13px;
  color: var(--claude-text-secondary);
}

.host-workspace-dialog__error {
  font-size: 13px;
  color: var(--state-danger);
}

@media (max-width: 640px) {
  .workspace-manage-row {
    grid-template-columns: 1fr;
  }
}
</style>
