<template>
  <PageLayout title="포트폴리오 리밸런싱" subtitle="목표 비중을 조정하고 리밸런싱을 실행합니다.">
    <KsFormSection title="현재 구성">
      <DataGridShell :rows="currentPositions" :columns="positionColumns" empty-message="보유 종목이 없습니다." />
      <p class="ks-stack"><strong>포트폴리오 총 평가액:</strong> {{ formatCurrency(totalValue, 'USD') }}</p>
    </KsFormSection>

    <KsFormSection title="목표 비중 설정">
      <KsFormGrid :columns="1" aria-label="리밸런싱 설정">
        <KsNumberField v-model="driftThreshold" label="허용 이탈 임계값 %" :min="0" :max="50" :max-fraction-digits="0" />
      </KsFormGrid>

      <div class="targets ks-stack">
        <div v-for="(target, idx) in targetWeights" :key="idx" class="target-row">
          <KsTextField v-model="target.symbol" label="종목코드" :input-id="`target-symbol-${idx}`" />
          <KsNumberField v-model="target.targetPercent" label="목표 비중 %" :min="0" :max="100" :max-fraction-digits="0" :input-id="`target-percent-${idx}`" />
          <KsButton severity="danger" label="삭제" @click="removeTarget(idx)" />
        </div>
      </div>

      <template #actions>
        <KsButton severity="secondary" label="종목 추가" @click="addTarget" />
        <KsButton severity="primary" label="리밸런싱 실행" @click="triggerRebalance" />
      </template>
    </KsFormSection>

    <KsFormSection v-if="jobResult" title="리밸런싱 대기열 등록됨">
      <dl class="ks-stack">
        <dt>Job ID</dt><dd class="mono">{{ jobResult.jobId }}</dd>
        <dt>상태</dt><dd><KsStatusTag :value="jobResult.status" severity="info" /></dd>
        <dt>예상 거래 건수</dt><dd>{{ formatQuantity(jobResult.estimatedTradeCount, 0) }}</dd>
        <dt>예상 비용</dt><dd>{{ formatCurrency(jobResult.estimatedCost, 'USD') }}</dd>
      </dl>
    </KsFormSection>
  </PageLayout>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import PageLayout from '../../../shared/ui/layouts/PageLayout.vue'
import DataGridShell from '../../../shared/ui/DataGridShell.vue'
import { KsButton, KsFormGrid, KsFormSection, KsNumberField, KsStatusTag, KsTextField } from '../../../shared/ui/components'
import type { UiGridColumn } from '../../../shared/ui/adapter/contracts'
import { formatCurrency, formatPercent, formatQuantity } from '../../../shared/formatters/financial'

interface Position {
  symbol: string
  quantity: number
  marketPrice: number
  marketValue: number
  weightPercent: number
}

interface TargetWeight {
  symbol: string
  targetPercent: number
}

interface JobResult {
  jobId: string
  status: string
  estimatedTradeCount: number
  estimatedCost: number
}

// Mock data
const currentPositions = ref<Position[]>([
  { symbol: 'AAPL', quantity: 100, marketPrice: 150.25, marketValue: 15025, weightPercent: 35.3 },
  { symbol: 'MSFT', quantity: 80, marketPrice: 320.50, marketValue: 25640, weightPercent: 60.2 },
  { symbol: 'GOOGL', quantity: 50, marketPrice: 140.75, marketValue: 7037.5, weightPercent: 16.5 },
])

const positionColumns = computed<UiGridColumn[]>(() => [
  { field: 'symbol', header: '종목코드' },
  { field: 'quantity', header: '수량', formatter: value => formatQuantity(value as number, 0) },
  { field: 'marketPrice', header: '현재가', formatter: value => formatCurrency(value as number, 'USD') },
  { field: 'marketValue', header: '평가금액', formatter: value => formatCurrency(value as number, 'USD') },
  { field: 'weightPercent', header: '비중', formatter: value => formatPercent((value as number) / 100, 1) }
])

const driftThreshold = ref(5)
const targetWeights = ref<TargetWeight[]>([
  { symbol: 'AAPL', targetPercent: 40 },
  { symbol: 'MSFT', targetPercent: 35 },
  { symbol: 'GOOGL', targetPercent: 25 },
])
const jobResult = ref<JobResult | null>(null)

const totalValue = ref(42700)

const addTarget = () => {
  targetWeights.value.push({ symbol: '', targetPercent: 0 })
}

const removeTarget = (idx: number) => {
  targetWeights.value.splice(idx, 1)
}

const triggerRebalance = async () => {
  // Mock API call
  jobResult.value = {
    jobId: '550e8400-e29b-41d4-a716-446655440001',
    status: 'Queued',
    estimatedTradeCount: 3,
    estimatedCost: 127.35,
  }
}
</script>

<style scoped>
.target-row { display: flex; align-items: end; gap: var(--ks-space-3); }
.target-row > :first-child { flex: 1; }
.mono { font-family: monospace; }
dl.ks-stack { display: grid; grid-template-columns: auto 1fr; gap: var(--ks-space-2) var(--ks-space-4); }
dl.ks-stack dt { font-weight: 600; color: var(--ks-color-text-muted); }
dl.ks-stack dd { margin: 0; }
</style>
