<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";

import { screenerApi, type Candidate, type CustomStrategy, type ScreenerCatalog, type ScreenerFormula, type ScreenerRun, type ScreenerWorkspace } from "../../shared/api/screener";
import EmptyState from "../../shared/components/EmptyState.vue";
import { useMarketStore } from "../../shared/stores/market";
import { useSessionStore } from "../../shared/stores/session";
import { useUiStore } from "../../shared/stores/ui";
import CustomPanel from "./CustomPanel.vue";
import StagePanel from "./StagePanel.vue";
import StrategyPanel from "./StrategyPanel.vue";

const session = useSessionStore();
const market = useMarketStore();
const ui = useUiStore();
const router = useRouter();
const mode = ref<"stage" | "curated" | "custom">("stage");
const catalog = ref<ScreenerCatalog | null>(null);
const workspace = ref<ScreenerWorkspace | null>(null);
const loading = ref(false);
const busy = ref(false);
const error = ref("");
const compiledFormula = ref<ScreenerFormula | null>(null);
const locked = () => !session.account?.smart_access;

async function load(): Promise<void> {
  loading.value = true;
  error.value = "";
  try {
    catalog.value = await screenerApi.catalog();
    workspace.value = locked() ? null : await screenerApi.workspace(market.selectedDate);
  } catch (reason) {
    error.value = reason instanceof Error ? reason.message : "智能选股数据读取失败";
  } finally {
    loading.value = false;
  }
}
async function saveCustom(name: string, formula: ScreenerFormula): Promise<void> {
  busy.value = true;
  try { await screenerApi.saveCustom(name, formula); ui.showToast("自定义策略已保存"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "保存失败"); }
  finally { busy.value = false; }
}
async function compileFormula(description: string): Promise<void> {
  busy.value = true;
  try {
    compiledFormula.value = (await screenerApi.compileFormula(description)).formula;
    ui.showToast("已转换为受控公式，请核对后保存");
  } catch (reason) {
    ui.showToast(reason instanceof Error ? reason.message : "公式转换失败");
  } finally { busy.value = false; }
}
async function runCustom(strategy: CustomStrategy): Promise<void> {
  busy.value = true;
  try { await screenerApi.runCustom(strategy.id, market.selectedDate); ui.showToast("选股计算已完成"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "执行失败"); }
  finally { busy.value = false; }
}
async function removeCustom(strategy: CustomStrategy): Promise<void> {
  busy.value = true;
  try { await screenerApi.deleteCustom(strategy.id); ui.showToast("自定义策略已删除"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "删除失败"); }
  finally { busy.value = false; }
}
async function track(run: ScreenerRun, candidate: Candidate): Promise<void> {
  try { await screenerApi.addTrack(run.id, candidate.identifier); ui.showToast(`${candidate.name} 已加入策略跟踪`); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "加入跟踪失败"); }
}

onMounted(load);
watch(() => market.selectedDate, load);
</script>

<template>
  <main class="page-frame screener-page">
    <header class="page-header market-page-header">
      <div><h1>智能选股</h1><p class="page-subtitle">数据日期 {{ workspace?.trade_date ?? market.selectedDate }} · 确定性条件与盘后归档</p></div>
      <div class="page-actions"><button class="tracking-entry" type="button" @click="router.push('/workspace/screener/tracking')"><span>持续</span><strong>策略跟踪</strong></button><div class="seg-control"><button type="button" :class="{ active: mode === 'stage' }" @click="mode = 'stage'">阶段选股</button><button type="button" :class="{ active: mode === 'curated' }" @click="mode = 'curated'">策略选股</button><button type="button" :class="{ active: mode === 'custom' }" @click="mode = 'custom'">自定义选股</button></div></div>
    </header>
    <div v-if="locked()" class="notice notice-warning membership-lock"><span><strong>智能选股仅对会员开放</strong>，开通会员后可查看盘后候选并使用自定义选股。</span><button class="btn btn-small" type="button" @click="ui.openDialog('membership')">查看会员状态</button></div>
    <div v-if="loading" class="card workspace-state">正在读取本地选股归档</div>
    <EmptyState v-else-if="error" class="card" title="智能选股暂不可用" :description="error" />
    <template v-else-if="catalog">
      <StagePanel v-if="mode === 'stage'" :strategies="catalog.stage" :runs="workspace?.stage_runs ?? []" :locked="locked()" @track="track" />
      <StrategyPanel v-else-if="mode === 'curated'" :strategies="catalog.curated" :runs="workspace?.curated_runs ?? []" :labels="catalog.factors" :locked="locked()" @track="track" />
      <CustomPanel v-else :factors="catalog.factors" :factor-groups="catalog.factor_groups" :strategies="workspace?.custom_strategies ?? []" :runs="workspace?.custom_runs ?? []" :compiled-formula="compiledFormula" :locked="locked()" :busy="busy" @compile="compileFormula" @save="saveCustom" @run="runCustom" @remove="removeCustom" @track="track" />
    </template>
  </main>
</template>
