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

import { marketApi, type MarketEntity } from "../../shared/api/market";
import { reviewApi, type ReviewWorkspace, type TradeEntry, type WatchItem } from "../../shared/api/review";
import BaseDialog from "../../shared/components/BaseDialog.vue";
import EmptyState from "../../shared/components/EmptyState.vue";
import MarketEntityLink from "../../shared/market/MarketEntityLink.vue";
import { useMarketStore } from "../../shared/stores/market";
import { useUiStore } from "../../shared/stores/ui";
import TradeDialog from "./TradeDialog.vue";

const market = useMarketStore();
const ui = useUiStore();
const data = ref<ReviewWorkspace | null>(null);
const loading = ref(true);
const error = ref("");
const historyOpen = ref(false);
const tradeDialog = ref(false);
const editingTrade = ref<TradeEntry | null>(null);
const watchDialog = ref(false);
const watchQuery = ref("");
const watchResults = ref<MarketEntity[]>([]);
const daily = ref({ summary: "", content: "", plan: "" });
let searchTimer: ReturnType<typeof setTimeout> | undefined;

const summary = computed(() => data.value?.trade_summary);
function display(value: number | null | undefined, suffix = ""): string {
  return value === null || value === undefined ? "" : `${value.toFixed(2)}${suffix}`;
}
async function load(): Promise<void> {
  loading.value = true;
  error.value = "";
  try {
    data.value = await reviewApi.workspace(market.selectedDate);
    daily.value = {
      summary: data.value.daily?.summary ?? "",
      content: data.value.daily?.content ?? "",
      plan: data.value.daily?.plan ?? "",
    };
  } catch (reason) {
    error.value = reason instanceof Error ? reason.message : "复盘记录读取失败";
  } finally { loading.value = false; }
}
async function saveDaily(): Promise<void> {
  try {
    await reviewApi.saveNote({
      trade_date: market.selectedDate, code: "", stock_name: "", ...daily.value,
    });
    ui.showToast("每日复盘已保存");
    await load();
  } catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "保存失败"); }
}
function searchWatch(): void {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(async () => {
    const query = watchQuery.value.trim();
    if (!query) { watchResults.value = []; return; }
    try {
      const result = await marketApi.search(query);
      watchResults.value = result.groups.find((group) => group.entity_type === "stock")?.items ?? [];
    } catch { watchResults.value = []; }
  }, 160);
}
async function addWatch(item: MarketEntity): Promise<void> {
  try {
    await reviewApi.addWatch(item.identifier);
    watchDialog.value = false;
    watchQuery.value = "";
    watchResults.value = [];
    ui.showToast(`${item.name} 已加入自选`);
    await load();
  } catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "添加失败"); }
}
async function saveRemark(item: WatchItem, event: Event): Promise<void> {
  try {
    await reviewApi.saveRemark(item.identifier, (event.target as HTMLInputElement).value);
    ui.showToast("跟踪备注已保存");
  } catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "保存失败"); }
}
async function removeWatch(item: WatchItem): Promise<void> {
  if (!await ui.askConfirmation({ title: "移出自选", message: `确定移出 ${item.name}？`, confirmLabel: "移出" })) return;
  try { await reviewApi.removeWatch(item.identifier); ui.showToast("已移出自选"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "操作失败"); }
}
function openTrade(row: TradeEntry | null = null): void { editingTrade.value = row; tradeDialog.value = true; }
async function saveTrade(value: Omit<TradeEntry, "action_label" | "emotion_label">): Promise<void> {
  try { await reviewApi.saveTrade(value); tradeDialog.value = false; ui.showToast("交易记录已保存"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "保存失败"); }
}
async function deleteTrade(row: TradeEntry): Promise<void> {
  if (!await ui.askConfirmation({ title: "删除交易记录", message: `确定删除 ${row.name} 的交易记录？`, confirmLabel: "删除" })) return;
  try { await reviewApi.deleteTrade(row.id); ui.showToast("交易记录已删除"); await load(); }
  catch (reason) { ui.showToast(reason instanceof Error ? reason.message : "删除失败"); }
}
watch(() => market.selectedDate, load);
onMounted(load);
</script>

<template>
  <main class="page-frame review-page">
    <header class="page-header review-heading">
      <div><h1>我的复盘</h1><p class="page-subtitle">数据日期 {{ data?.trade_date ?? market.selectedDate }} · 当前账号私有</p></div>
      <div class="review-heading-actions">
        <button class="btn mobile-only" type="button" @click="ui.openDialog('alerts')">提醒中心</button>
        <button class="btn mobile-only" type="button" @click="ui.openDialog('assistant')">复盘助手</button>
        <button class="btn btn-primary" type="button" @click="watchDialog = true">添加自选</button>
      </div>
    </header>
    <div v-if="loading" class="card workspace-state">正在读取个人复盘记录</div>
    <EmptyState v-else-if="error" class="card" title="复盘记录暂不可用" :description="error" />
    <template v-else-if="data">
      <section class="card review-watch-card">
        <header class="card-header"><h2>自选追踪</h2><span class="tag">{{ data.watchlist.length }} 只</span></header>
        <div v-if="data.watchlist.length" class="data-table-wrap review-watch-table"><table class="data-table"><thead><tr><th>标记</th><th>代码</th><th>股票</th><th>板块</th><th class="numeric">今日涨幅（%）</th><th class="numeric">5日涨幅（%）</th><th class="numeric">竞价关注分</th><th>跟踪备注</th><th>操作</th></tr></thead><tbody><tr v-for="item in data.watchlist" :key="item.identifier"><td class="watch-star">★</td><td><MarketEntityLink :entity="{ entity_type: 'stock', identifier: item.identifier, code: item.code, name: item.name, sector: item.sector }" /></td><td>{{ item.name }}</td><td>{{ item.sector ?? "" }}</td><td class="numeric" :class="item.pct_chg !== null && item.pct_chg >= 0 ? 'up' : 'down'">{{ display(item.pct_chg) }}</td><td class="numeric" :class="item.return_5d !== null && item.return_5d >= 0 ? 'up' : 'down'">{{ display(item.return_5d) }}</td><td class="numeric">{{ display(item.attention_score) }}</td><td><input :value="item.remark" class="review-remark" maxlength="500" aria-label="跟踪备注" @change="saveRemark(item, $event)" /></td><td><div class="table-actions"><button class="btn btn-small" type="button" @click="removeWatch(item)">移除</button></div></td></tr></tbody></table></div>
        <EmptyState v-else title="暂无自选" description="添加股票后可集中查看涨幅、竞价关注分和跟踪备注。" />
      </section>

      <div class="review-main-grid">
        <section class="card trade-card">
          <header class="card-header"><h2>交易日志</h2><span class="tag">{{ data.trades.length }} 条</span><button class="btn btn-primary btn-small review-card-action" type="button" @click="openTrade()">交易日志</button></header>
          <div class="review-summary"><div><span>总记录</span><strong>{{ summary?.total }}</strong></div><div><span>已实现</span><strong>{{ summary?.realized }}</strong></div><div><span>胜率</span><strong>{{ summary?.win_rate === null ? "" : display(summary?.win_rate, "%") }}</strong></div><div><span>累计盈亏</span><strong>{{ display(summary?.pnl_amount) }}</strong></div><div><span>平均仓位</span><strong>{{ summary?.average_position === null ? "" : display(summary?.average_position, "%") }}</strong></div></div>
          <div v-if="data.trades.length" class="trade-scroll"><table class="data-table"><thead><tr><th>日期</th><th>代码</th><th>股票</th><th>动作</th><th class="numeric">价格（元）</th><th class="numeric">仓位（%）</th><th class="numeric">盈亏（%）</th><th>操作</th></tr></thead><tbody><tr v-for="row in data.trades" :key="row.id"><td>{{ row.trade_date }}</td><td><MarketEntityLink :entity="{ entity_type: 'stock', identifier: row.code, code: row.code, name: row.name, sector: null }" /></td><td>{{ row.name }}</td><td>{{ row.action_label }}</td><td class="numeric">{{ display(row.price) }}</td><td class="numeric">{{ display(row.position_pct) }}</td><td class="numeric" :class="row.pnl_pct !== null && row.pnl_pct >= 0 ? 'up' : 'down'">{{ display(row.pnl_pct) }}</td><td><div class="table-actions"><button class="btn btn-small" type="button" @click="openTrade(row)">编辑</button><button class="btn btn-small" type="button" @click="deleteTrade(row)">删除</button></div></td></tr></tbody></table></div>
          <EmptyState v-else title="暂无交易日志" description="记录交易后，摘要与明细会保留在当前页面。" />
        </section>

        <section class="card daily-review-card">
          <header class="card-header"><h2>每日复盘</h2><span class="tag">{{ market.selectedDate }}</span></header>
          <form class="daily-review-form" @submit.prevent="saveDaily">
            <label class="field"><span class="field-label">今日盘面一句话</span><textarea v-model="daily.summary" class="textarea daily-short" maxlength="500"></textarea></label>
            <label class="field"><span class="field-label">今日做对了什么 / 做错了什么</span><textarea v-model="daily.content" class="textarea" maxlength="5000"></textarea></label>
            <label class="field"><span class="field-label">明日策略</span><textarea v-model="daily.plan" class="textarea" maxlength="2000"></textarea></label>
            <div class="form-actions"><button class="btn btn-primary" type="submit">保存复盘</button></div>
          </form>
        </section>
      </div>

      <section class="card review-history-card">
        <button class="review-history-toggle" type="button" :aria-expanded="historyOpen" @click="historyOpen = !historyOpen"><span>最近复盘</span><span>{{ historyOpen ? "收起" : `展开 ${data.history.length} 条` }}</span></button>
        <div v-if="historyOpen" class="review-history-list"><article v-for="note in data.history" :key="note.id"><time>{{ note.trade_date }}</time><strong>{{ note.summary || "未填写盘面一句话" }}</strong><p>{{ note.content }}</p><small>{{ note.plan }}</small></article><EmptyState v-if="!data.history.length" title="暂无每日复盘" description="保存后会按日期显示在这里。" /></div>
      </section>
    </template>
  </main>

  <BaseDialog v-if="watchDialog" title="添加自选" @close="watchDialog = false">
    <div class="form-grid"><label class="field"><span class="field-label">股票代码或名称</span><input v-model="watchQuery" class="input" autofocus @input="searchWatch" /></label><div class="watch-search-results"><button v-for="item in watchResults" :key="item.identifier" type="button" @click="addWatch(item)"><span><strong>{{ item.name }}</strong><small>{{ item.code }} · {{ item.sector || "行业待补" }}</small></span><span>添加</span></button><p v-if="watchQuery && !watchResults.length" class="muted">暂无匹配股票</p></div></div>
  </BaseDialog>
  <TradeDialog v-if="tradeDialog" :value="editingTrade" :date="market.selectedDate" @close="tradeDialog = false" @save="saveTrade" />
</template>
