<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api, type Project, type ObsidianSyncResult } from '../api'

const projects = ref<Project[]>([])
const vaultPaths = ref<Record<string, string>>({})
const deployCommands = ref<Record<string, string>>({})
const testCommands = ref<Record<string, string>>({})
const autoTestEnabled = ref<Record<string, boolean>>({})
const saving = ref<Record<string, boolean>>({})
const savingDeploy = ref<Record<string, boolean>>({})
const savingTest = ref<Record<string, boolean>>({})
const savingAutoTest = ref<Record<string, boolean>>({})
const syncing = ref<Record<string, boolean>>({})
const saveStatus = ref<Record<string, string>>({})
const saveDeployStatus = ref<Record<string, string>>({})
const saveTestStatus = ref<Record<string, string>>({})
const saveAutoTestStatus = ref<Record<string, string>>({})
const syncResults = ref<Record<string, ObsidianSyncResult | null>>({})
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    projects.value = await api.projects()
    for (const p of projects.value) {
      vaultPaths.value[p.id] = p.obsidian_vault_path ?? ''
      deployCommands.value[p.id] = p.deploy_command ?? ''
      testCommands.value[p.id] = p.test_command ?? ''
      autoTestEnabled.value[p.id] = !!(p.auto_test_enabled)
    }
  } catch (e) {
    error.value = String(e)
  }
})

async function saveVaultPath(projectId: string) {
  saving.value[projectId] = true
  saveStatus.value[projectId] = ''
  try {
    await api.patchProject(projectId, { obsidian_vault_path: vaultPaths.value[projectId] })
    saveStatus.value[projectId] = 'Saved'
  } catch (e) {
    saveStatus.value[projectId] = `Error: ${e}`
  } finally {
    saving.value[projectId] = false
  }
}

async function saveDeployCommand(projectId: string) {
  savingDeploy.value[projectId] = true
  saveDeployStatus.value[projectId] = ''
  try {
    await api.patchProject(projectId, { deploy_command: deployCommands.value[projectId] })
    saveDeployStatus.value[projectId] = 'Saved'
  } catch (e) {
    saveDeployStatus.value[projectId] = `Error: ${e}`
  } finally {
    savingDeploy.value[projectId] = false
  }
}

async function saveTestCommand(projectId: string) {
  savingTest.value[projectId] = true
  saveTestStatus.value[projectId] = ''
  try {
    await api.patchProject(projectId, { test_command: testCommands.value[projectId] })
    saveTestStatus.value[projectId] = 'Saved'
  } catch (e) {
    saveTestStatus.value[projectId] = `Error: ${e}`
  } finally {
    savingTest.value[projectId] = false
  }
}

async function toggleAutoTest(projectId: string) {
  autoTestEnabled.value[projectId] = !autoTestEnabled.value[projectId]
  savingAutoTest.value[projectId] = true
  saveAutoTestStatus.value[projectId] = ''
  try {
    await api.patchProject(projectId, { auto_test_enabled: autoTestEnabled.value[projectId] })
    saveAutoTestStatus.value[projectId] = 'Saved'
  } catch (e) {
    autoTestEnabled.value[projectId] = !autoTestEnabled.value[projectId]
    saveAutoTestStatus.value[projectId] = `Error: ${e}`
  } finally {
    savingAutoTest.value[projectId] = false
  }
}

async function runSync(projectId: string) {
  syncing.value[projectId] = true
  syncResults.value[projectId] = null
  saveStatus.value[projectId] = ''
  try {
    await api.patchProject(projectId, { obsidian_vault_path: vaultPaths.value[projectId] })
    syncResults.value[projectId] = await api.syncObsidian(projectId)
  } catch (e) {
    saveStatus.value[projectId] = `Sync error: ${e}`
  } finally {
    syncing.value[projectId] = false
  }
}
</script>

<template>
  <div>
    <h1 class="text-xl font-semibold text-gray-100 mb-6">Settings</h1>

    <div v-if="error" class="text-red-400 mb-4">{{ error }}</div>

    <div v-for="project in projects" :key="project.id" class="mb-6 p-4 border border-gray-700 rounded-lg">
      <div class="flex items-center gap-3 mb-3">
        <span class="font-medium text-gray-100">{{ project.name }}</span>
        <span class="text-xs text-gray-500 font-mono">{{ project.id }}</span>
      </div>

      <div class="mb-3">
        <label class="block text-xs text-gray-400 mb-1">Obsidian Vault Path</label>
        <input
          v-model="vaultPaths[project.id]"
          type="text"
          placeholder="/path/to/obsidian/vault"
          class="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-gray-200 font-mono focus:outline-none focus:border-gray-500"
        />
      </div>

      <div class="mb-3">
        <label class="block text-xs text-gray-400 mb-1">Deploy Command</label>
        <input
          v-model="deployCommands[project.id]"
          type="text"
          placeholder="git push origin main"
          class="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-gray-200 font-mono focus:outline-none focus:border-gray-500"
        />
        <p class="text-xs text-gray-600 mt-1">Команда выполняется через shell в директории проекта. Настраивается только администратором.</p>
      </div>

      <div class="flex items-center gap-3 flex-wrap mb-3">
        <button
          @click="saveDeployCommand(project.id)"
          :disabled="savingDeploy[project.id]"
          class="px-3 py-1.5 text-sm bg-gray-700 hover:bg-gray-600 text-gray-200 rounded disabled:opacity-50"
        >
          {{ savingDeploy[project.id] ? 'Saving…' : 'Save Deploy' }}
        </button>
        <span v-if="saveDeployStatus[project.id]" class="text-xs" :class="saveDeployStatus[project.id].startsWith('Error') ? 'text-red-400' : 'text-green-400'">
          {{ saveDeployStatus[project.id] }}
        </span>
      </div>

      <div class="mb-3">
        <label class="block text-xs text-gray-400 mb-1">Test Command</label>
        <input
          v-model="testCommands[project.id]"
          type="text"
          placeholder="make test"
          class="w-full bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-gray-200 font-mono focus:outline-none focus:border-gray-500"
        />
        <p class="text-xs text-gray-600 mt-1">Команда запуска тестов, выполняется через shell в директории проекта.</p>
      </div>

      <div class="flex items-center gap-3 flex-wrap mb-3">
        <button
          @click="saveTestCommand(project.id)"
          :disabled="savingTest[project.id]"
          class="px-3 py-1.5 text-sm bg-gray-700 hover:bg-gray-600 text-gray-200 rounded disabled:opacity-50"
        >
          {{ savingTest[project.id] ? 'Saving…' : 'Save Test' }}
        </button>
        <span v-if="saveTestStatus[project.id]" class="text-xs" :class="saveTestStatus[project.id].startsWith('Error') ? 'text-red-400' : 'text-green-400'">
          {{ saveTestStatus[project.id] }}
        </span>
      </div>

      <div class="flex items-center gap-3 mb-3">
        <label class="flex items-center gap-2 cursor-pointer select-none">
          <input
            type="checkbox"
            :checked="autoTestEnabled[project.id]"
            @change="toggleAutoTest(project.id)"
            :disabled="savingAutoTest[project.id]"
            class="w-4 h-4 rounded border-gray-600 bg-gray-800 accent-blue-500 cursor-pointer disabled:opacity-50"
          />
          <span class="text-sm text-gray-300">Auto-test</span>
          <span class="text-xs text-gray-500">— запускать тесты автоматически после pipeline</span>
        </label>
        <span v-if="saveAutoTestStatus[project.id]" class="text-xs" :class="saveAutoTestStatus[project.id].startsWith('Error') ? 'text-red-400' : 'text-green-400'">
          {{ saveAutoTestStatus[project.id] }}
        </span>
      </div>

      <div class="flex items-center gap-3 flex-wrap">
        <button
          @click="saveVaultPath(project.id)"
          :disabled="saving[project.id]"
          class="px-3 py-1.5 text-sm bg-gray-700 hover:bg-gray-600 text-gray-200 rounded disabled:opacity-50"
        >
          {{ saving[project.id] ? 'Saving…' : 'Save Vault' }}
        </button>

        <button
          @click="runSync(project.id)"
          :disabled="syncing[project.id] || !vaultPaths[project.id]"
          class="px-3 py-1.5 text-sm bg-indigo-700 hover:bg-indigo-600 text-white rounded disabled:opacity-50"
        >
          {{ syncing[project.id] ? 'Syncing…' : 'Sync Obsidian' }}
        </button>

        <span v-if="saveStatus[project.id]" class="text-xs" :class="saveStatus[project.id].startsWith('Error') ? 'text-red-400' : 'text-green-400'">
          {{ saveStatus[project.id] }}
        </span>
      </div>

      <div v-if="syncResults[project.id]" class="mt-3 p-3 bg-gray-900 rounded text-xs text-gray-300">
        <div>Exported: <span class="text-green-400 font-medium">{{ syncResults[project.id]!.exported_decisions }}</span> decisions</div>
        <div>Updated: <span class="text-green-400 font-medium">{{ syncResults[project.id]!.tasks_updated }}</span> tasks</div>
        <div v-if="syncResults[project.id]!.errors.length > 0" class="mt-1">
          <div v-for="err in syncResults[project.id]!.errors" :key="err" class="text-red-400">{{ err }}</div>
        </div>
      </div>

    </div>
  </div>
</template>
