<template>
  <div class="dev-layout" :class="currentTheme">
    <header class="app-header">
      <div class="brand">
        <h1>Code Editor</h1>
      </div>

      <div class="header-controls">
        <button
          class="icon-btn"
          @click="toggleQuestionPanel"
          :title="showQuestionPanel ? '隐藏试题' : '显示试题'"
          :class="{ active: showQuestionPanel }"
        >
          试题面板
        </button>
        <button class="icon-btn" @click="switchTheme" title="切换主题">
          {{ currentTheme === "vs-dark" ? "🌙" : "☀️" }} 主题
        </button>
        <button class="icon-btn" @click="resetCode" title="重置代码">
          重置
        </button>
      </div>
    </header>

    <div class="workspace">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载题目...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <p>{{ error }}</p>
        <button @click="location.reload()" class="retry-btn">重试</button>
      </div>
        <!-- :enable-file-system="true" -->


      <SmartCodeEditor
        v-else-if="question"
        v-model="code"
        :language="currentLanguage"
        :theme="currentTheme"
        :question="question"
        :config="editorConfig"
        :enable-run="true"
        :custom-runner="runCodeOnBackend"
        :custom-submit-runner="runCodeOnBackend"
        :enable-language-switch="true"
        :show-question-panel="showQuestionPanel"
        @submit="handleSubmit"
        @language-change="handleLanguageChange"
      />
    </div>

    <footer class="status-bar">
      <div class="left-items">
        <span class="item">{{ currentLanguage }}</span>
        <span class="item">{{ code?.length || 0 }} chars</span>
      </div>
      <div class="right-items">
        <span class="item">Theme: {{ currentTheme }}</span>
        <span class="item">Version: 1.0.0</span>
      </div>
    </footer>
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from "vue";
import SmartCodeEditor from "./adapters/vue/SmartCodeEditor.vue";

export default defineComponent({
  name: "DevApp",
  components: {
    SmartCodeEditor,
  },
  setup() {
    const question = ref(null);
    const loading = ref(true);
    const error = ref("");
    const questionId = ref(1);
    onMounted(async () => {
      try {
        const urlParams = new URLSearchParams(window.location.search);
        const qidParam = urlParams.get("question_id");
        questionId.value = qidParam ? parseInt(qidParam, 10) : 1;

        const res = await fetch(
          `http://192.168.60.98:8080/api/v1/question?question_id=${questionId.value}`,
        );
        if (!res.ok) {
          throw new Error("Failed to fetch question");
        }
        question.value = await res.json();

        if (question.value && question.value.defaultLanguage) {
          const lang = question.value.defaultLanguage;
          const template = question.value.languageTemplates[lang];

          if (template) {
            code.value = template; // 加载题目对应的代码模板
            currentLanguage.value = lang; // 同步语言选择
          }
        }
      } catch (e) {
        error.value = "无法加载题目，请确保后端服务已启动 (cargo run)";
        console.error(e);
      } finally {
        loading.value = false;
      }
    });

    const code = ref("");

    const currentLanguage = ref("javascript");
    const currentTheme = ref("vs");
    const showQuestionPanel = ref(true);

    const useQuestionMode = ref(false);

    const editorConfig = computed(() => ({
      questionMarkdown: {
        editable: true,
        placeholder: "用 Markdown 编写题目...",
      },
    }));

    const runCodeOnBackend = async (
      code,
      language,
      testCases,
      isSubmit = false,
    ) => {
      try {
        const payload = {
          language,
          code,
          stdin: "",
          testCases: isSubmit ? null : testCases,
          questionId: questionId.value,
        };

        return await submitCodeAsync(payload);
      } catch (error) {
        console.error("Backend error:", error);
        return {
          output: "",
          error: `后端连接失败: ${error.message}`,
          executionTime: 0,
          status: "error",
        };
      }
    };

    const submitCodeAsync = async (payload) => {
      try {
        const submitResponse = await fetch(
          "http://192.168.60.98:8080/api/v1/submit",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          },
        );

        if (!submitResponse.ok) {
          throw new Error(`提交失败: HTTP ${submitResponse.status}`);
        }

        const { submit_id, status } = await submitResponse.json();

        // 第二步：轮询结果
        return await pollResult(submit_id);
      } catch (error) {
        console.error("提交错误:", error);
        return {
          output: "",
          error: `提交失败: ${error.message}`,
          executionTime: 0,
          status: "error",
        };
      }
    };

    // 轮询结果
    const pollResult = async (submitId, maxAttempts = 60, interval = 1000) => {
      for (let attempt = 0; attempt < maxAttempts; attempt++) {
        try {
          const response = await fetch(
            `http://192.168.60.98:8080/api/v1/result/${submitId}`,
          );

          if (!response.ok) {
            throw new Error(`查询失败: HTTP ${response.status}`);
          }

          const data = await response.json();

          // 检查状态
          if (data.status === "completed") {
            const result = data.result;
            return {
              output: result.stdout || "",
              error: result.error || result.stderr || "",
              executionTime: result.execution_time_ms,
              status: result.exit_code === 0 ? "success" : "error",
              testResults: result.test_results || [],
            };
          } else if (data.status === "error") {
            return {
              output: "",
              error: data.error || "代码执行出错",
              executionTime: 0,
              status: "error",
            };
          } else if (data.status === "pending" || data.status === "running") {
            // 继续等待
            await new Promise((resolve) => setTimeout(resolve, interval));
            continue;
          }
        } catch (error) {
          console.error("轮询错误:", error);
          // 继续尝试
          await new Promise((resolve) => setTimeout(resolve, interval));
        }
      }

      // 超时
      return {
        output: "",
        error: "执行超时，请稍后重试",
        executionTime: 0,
        status: "error",
      };
    };

    const handleSubmit = (data) => {
      console.log("Code submitted:", data);
    };

    const handleLanguageChange = (language) => {
      currentLanguage.value = language;
    };

    const toggleQuestionPanel = () => {
      showQuestionPanel.value = !showQuestionPanel.value;
    };

    const toggleMode = () => {
      useQuestionMode.value = !useQuestionMode.value;
    };

    const switchTheme = () => {
      currentTheme.value = currentTheme.value === "vs-dark" ? "vs" : "vs-dark";
    };

    const resetCode = () => {
      code.value = `// 编写你的代码\nconsole.log("Hello, World!");`;
    };

    const testAPI = () => {
      console.log("=== API 测试 ===");
      console.log("Length:", code.value.length);
      console.log("Lang:", currentLanguage.value);
    };

    return {
      editorConfig,
      code,
      currentLanguage,
      currentTheme,
      showQuestionPanel,
      useQuestionMode,
      question,
      runCodeOnBackend,
      handleSubmit,
      handleLanguageChange,
      toggleQuestionPanel,
      toggleMode,
      switchTheme,
      resetCode,
      testAPI,
    };
  },
});
</script>

<style scoped>
/* 全局布局变量 (Scoped styles will apply to elements within this component) */
.dev-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: var(--panel-bg);
  color: var(--text-color);
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  overflow: hidden;
  transition:
    background 0.3s,
    color 0.3s;
}

/* Header 样式 */
.app-header {
  height: 48px;
  background: var(--header-bg);
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  user-select: none;
  transition:
    background 0.3s,
    border-color 0.3s;
}

.brand {
  display: flex;
  align-items: center;
  gap: 8px;
}

.brand h1 {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.tag {
  font-size: 10px;
  background: #0e639c;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
}

.header-controls {
  display: flex;
  gap: 8px;
}

.icon-btn {
  background: transparent;
  border: 1px solid transparent;
  color: var(--text-color);
  padding: 4px 10px;
  font-size: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.icon-btn:hover {
  background: var(--hover-bg);
}

.icon-btn.active {
  background: var(--active-bg);
  border-color: var(--border-color);
}

/* 工作区布局 */
.workspace {
  flex: 1;
  overflow: hidden;
  position: relative;
  background: #F5F6F7;
}

/* 加载状态 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-color);
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 255, 255, 0.1);
  border-top-color: var(--accent-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-container p,
.error-container p {
  font-size: 16px;
  opacity: 0.8;
  margin: 10px 0;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.retry-btn {
  margin-top: 20px;
  padding: 10px 24px;
  background: var(--accent-color);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: opacity 0.2s;
}

.retry-btn:hover {
  opacity: 0.9;
}

/* 状态栏 */
.status-bar {
  height: 24px;
  background: #007acc;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  font-size: 12px;
  font-family: sans-serif;
}

.left-items,
.right-items {
  display: flex;
  gap: 16px;
}

.item {
  display: flex;
  align-items: center;
  gap: 6px;
}
</style>

<style>
/* Global styles */
:root {
  --header-height: 48px;
  --status-bar-height: 24px;

  /* Dark Theme Default */
  --panel-bg: #1e1e1e;
  --header-bg: #252526;
  --text-color: #cccccc;
  --border-color: #333;
  --hover-bg: #3c3c3c;
  --active-bg: #37373d;
  --accent-color: #0e639c;
}

/* Light Theme Overrides */
.vs {
  --panel-bg: #ffffff;
  --header-bg: #f3f3f3;
  --text-color: #333333;
  --border-color: #e0e0e0;
  --hover-bg: #e8e8e8;
  --active-bg: #d4d4d4;
}

body {
  margin: 0;
}
</style>
