<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {
  SelectDirectory,
  GetSettings,
  AddProjectConfig,
  RemoveProjectConfig,
  UpdateProjectConfig,
  UpdateServiceCommon,
  SaveSettings
} from '../../wailsjs/go/backend/App'

interface ProjectConfig {
  name: string
  path: string
}

interface AppSettings {
  theme: string
  language: string
  notifications: boolean
  autoStart: boolean
  modelBasePath: string
  databases?: any[]
  projects?: ProjectConfig[]
}

const settings = reactive<AppSettings>({
  theme: 'light',
  language: 'zh-CN',
  notifications: true,
  autoStart: false,
  modelBasePath: '',
  projects: []
})

const projectForm = reactive<ProjectConfig>({
  name: '',
  path: ''
})

const updateForm = reactive({
  commitId: '',
  selectedProjects: [] as string[]
})

const isUpdating = ref(false)
const output = ref('')
const projectDialogVisible = ref(false)
const editingProjectIndex = ref(-1)

onMounted(async () => {
  try {
    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.modelBasePath = loadedSettings.modelBasePath || ''
    if (loadedSettings.projects) {
      settings.projects = loadedSettings.projects
    }
  } catch (error) {
    console.error('Failed to load settings:', error)
  }
})

async function selectProjectPath() {
  try {
    const path = await SelectDirectory('选择项目路径', projectForm.path)
    if (path) {
      projectForm.path = path
      const pathParts = path.replace(/\\/g, '/').split('/')
      projectForm.name = pathParts[pathParts.length - 1] || ''
    }
  } catch (error) {
    console.error('Failed to select directory:', error)
  }
}

function openAddProjectDialog() {
  editingProjectIndex.value = -1
  projectForm.name = ''
  projectForm.path = ''
  projectDialogVisible.value = true
}

function openEditProjectDialog(index: number) {
  editingProjectIndex.value = index
  const project = settings.projects![index]
  projectForm.name = project.name
  projectForm.path = project.path
  projectDialogVisible.value = true
}

async function handleAddProject() {
  if (!projectForm.name) {
    ElMessage.warning('请输入项目名称')
    return
  }

  if (!projectForm.path) {
    ElMessage.warning('请选择项目路径')
    return
  }

  try {
    if (editingProjectIndex.value === -1) {
      await AddProjectConfig(projectForm.name, projectForm.path)
      ElMessage.success('添加成功')
    } else {
      await UpdateProjectConfig(settings.projects![editingProjectIndex.value].name, projectForm.name, projectForm.path)
      ElMessage.success('更新成功')
    }
    projectDialogVisible.value = false

    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.modelBasePath = loadedSettings.modelBasePath || ''
    if (loadedSettings.projects) {
      settings.projects = loadedSettings.projects
    }
  } catch (error) {
    console.error('Failed to save project config:', error)
    ElMessage.error('保存失败')
  }
}

async function handleDeleteProject(index: number) {
  const project = settings.projects![index]
  try {
    await RemoveProjectConfig(project.name)
    ElMessage.success('删除成功')

    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.modelBasePath = loadedSettings.modelBasePath || ''
    if (loadedSettings.projects) {
      settings.projects = loadedSettings.projects
    }
  } catch (error) {
    console.error('Failed to delete project config:', error)
    ElMessage.error('删除失败')
  }
}

async function updateCommonVersion() {
  if (!updateForm.commitId) {
    ElMessage.warning('请输入 Commit ID')
    return
  }

  if (updateForm.selectedProjects.length === 0) {
    ElMessage.warning('请至少选择一个项目')
    return
  }

  isUpdating.value = true
  output.value = '正在更新 Common 版本...\n'

  try {
    const result = await UpdateServiceCommon(updateForm.commitId, updateForm.selectedProjects)
    output.value = result
  } catch (error) {
    console.error('Failed to update common version:', error)
    output.value = `更新失败: ${error}`
  } finally {
    isUpdating.value = false
  }
}

async function saveSettings() {
  try {
    const currentSettings = await GetSettings() as any
    currentSettings.modelBasePath = settings.modelBasePath
    currentSettings.projects = settings.projects
    await SaveSettings(currentSettings)
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('Failed to save settings:', error)
    ElMessage.error('设置保存失败')
  }
}
</script>

<template>
  <div class="update-common-container">
    <el-card class="update-version-card">
      <template #header>
        <div class="card-header">
          <span>更新 Common 版本</span>
        </div>
      </template>
      <el-form label-width="140px" class="settings-form">
        <el-form-item label="Commit ID">
          <el-input
              v-model="updateForm.commitId"
              placeholder="请输入 Commit ID"
              clearable
          />
        </el-form-item>
        <el-form-item label="选择项目">
          <el-checkbox-group v-model="updateForm.selectedProjects">
            <el-checkbox
                v-for="project in settings.projects"
                :key="project.name"
                :label="project.name"
            >
              {{ project.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="updateCommonVersion"
              :loading="isUpdating"
          >
            更新 Common 版本
          </el-button>
        </el-form-item>
        <el-form-item label="执行输出">
          <el-input
              v-model="output"
              type="textarea"
              :rows="10"
              placeholder="更新结果将显示在这里"
              readonly
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="project-card">
      <template #header>
        <div class="card-header">
          <span>项目配置管理</span>
          <el-button type="primary" size="small" @click="openAddProjectDialog">添加配置</el-button>
        </div>
      </template>
      <el-form label-width="140px" class="settings-form">
        <el-form-item label="Go Module Name">
          <el-input
              v-model="settings.modelBasePath"
              placeholder="请输入 Go Module Name，例如：git.hlsq.asia/mmorpg/service-common"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="settings.projects" style="width: 100%">
        <el-table-column prop="name" label="项目名称"/>
        <el-table-column prop="path" label="项目路径" show-overflow-tooltip/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="openEditProjectDialog(scope.$index)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteProject(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="projectDialogVisible"
        :title="editingProjectIndex === -1 ? '添加项目配置' : '编辑项目配置'"
        width="500px"
    >
      <el-form label-width="120px">
        <el-form-item label="项目名称">
          <el-input
              v-model="projectForm.name"
              placeholder="自动从路径提取，也可手动修改"
              clearable
          />
        </el-form-item>
        <el-form-item label="项目路径">
          <el-input
              v-model="projectForm.path"
              placeholder="请输入或选择项目路径（需包含 go.mod 文件）"
              clearable
          >
            <template #append>
              <el-button @click="selectProjectPath">选择文件夹</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="projectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddProject">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.update-common-container {
  padding: 20px;
}

.update-common-card,
.project-card,
.update-version-card {
  max-width: 900px;
  margin: 20px auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.settings-form {
  padding: 20px 0;
}
</style>
