<script lang="ts">
  import { onMount } from 'svelte'
  import { goto } from '$app/navigation'
  import { accountApi } from '$lib/api/account'
  import { formatPrice, formatRate, priceClass } from '$lib/utils'
  import type { AccountBalance, PendingOrder, OrderHistory } from '$lib/api/types'

  let balance = $state<AccountBalance | null>(null)
  let pending = $state<PendingOrder[]>([])
  let history = $state<OrderHistory[]>([])
  let loading = $state(true)
  let activeTab = $state<'balance' | 'pending' | 'history'>('balance')

  onMount(async () => {
    await loadData()
  })

  async function loadData() {
    loading = true
    try {
      balance = await accountApi.getBalance()
    } catch (e) {
      console.error(e)
    } finally {
      loading = false
    }
  }

  async function loadPending() {
    try {
      pending = (await accountApi.getPending()) ?? []
    } catch {}
  }

  async function loadHistory() {
    try {
      history = (await accountApi.getHistory()) ?? []
    } catch {}
  }

  function setTab(tab: typeof activeTab) {
    activeTab = tab
    if (tab === 'pending') loadPending()
    if (tab === 'history') loadHistory()
  }

  // 매매구분 표시 (1:매도, 2:매수)
  function tradeTypeLabel(tp: string): string {
    if (tp === '1') return '매도'
    if (tp === '2') return '매수'
    return tp
  }

  function tradeTypeClass(tp: string): string {
    if (tp === '1') return 'text-blue-400'
    if (tp === '2') return 'text-red-400'
    return 'text-gray-300'
  }

  // 시간 포맷 (HHmmss → HH:mm:ss)
  function formatTm(tm: string): string {
    if (!tm || tm.length < 6) return tm || ''
    return `${tm.slice(0, 2)}:${tm.slice(2, 4)}:${tm.slice(4, 6)}`
  }

  // 미체결 주문 취소
  async function cancelOrder(order: PendingOrder) {
    if (!confirm(`${order.stkNm} 주문을 취소하시겠습니까?`)) return
    try {
      await accountApi.cancel(order.ordNo, order.stkCd, parseInt(order.osoQty) || 0)
      await loadPending()
    } catch (e) {
      alert(e instanceof Error ? e.message : '주문 취소 실패')
    }
  }
</script>

<svelte:head>
  <title>자산 현황 - 주식 시세</title>
</svelte:head>

<h1 class="text-xl font-bold text-white mb-4">자산 현황</h1>

{#if loading}
  <div class="flex items-center justify-center h-64 text-gray-400">로딩 중...</div>
{:else if balance}
  <!-- 요약 카드 -->
  <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
    {#each [
      { label: '총 자산', value: balance.totalAsset, fmt: 'price' },
      { label: '예수금', value: balance.deposit, fmt: 'price' },
      { label: '주식 평가액', value: balance.stockValue, fmt: 'price' },
      { label: '평가 손익', value: balance.profitLoss, fmt: 'profit' },
    ] as card}
      <div class="bg-gray-800 rounded-xl px-4 py-4">
        <div class="text-xs text-gray-400 mb-1">{card.label}</div>
        <div class="text-xl font-bold {card.fmt === 'profit' ? priceClass(card.value) : 'text-white'}">
          {card.value >= 0 && card.fmt === 'profit' ? '+' : ''}{formatPrice(card.value)}
        </div>
        {#if card.fmt === 'profit'}
          <div class="text-sm {priceClass(balance.profitRate)}">
            {formatRate(balance.profitRate)}
          </div>
        {/if}
      </div>
    {/each}
  </div>

  <!-- 탭 -->
  <div class="flex gap-1 mb-4 border-b border-gray-700 pb-1">
    {#each [['balance', '보유종목'], ['pending', '미체결'], ['history', '주문내역']] as [tab, label]}
      <button
        onclick={() => setTab(tab as typeof activeTab)}
        class="px-4 py-2 text-sm rounded-t transition-colors {activeTab === tab ? 'text-blue-400 border-b-2 border-blue-400' : 'text-gray-400 hover:text-white'}"
      >{label}</button>
    {/each}
  </div>

  {#if activeTab === 'balance'}
    <div class="bg-gray-800 rounded-xl overflow-hidden">
      <table>
        <thead>
          <tr>
            <th class="px-4 py-3 text-left text-xs font-medium text-gray-400">종목</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">수량</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">매수가</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">현재가</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">평가손익</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">수익률</th>
            <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">평가금액</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-700">
          {#each balance.stocks as stock (stock.code)}
            <tr
              class="cursor-pointer hover:bg-gray-700 transition-colors"
              onclick={() => goto(`/stock/${stock.code}`)}
            >
              <td class="px-4 py-3">
                <div class="text-sm font-medium text-white">{stock.name}</div>
                <div class="text-xs text-gray-500">{stock.code}</div>
              </td>
              <td class="px-3 py-3 text-right text-sm text-gray-300">{stock.qty.toLocaleString()}</td>
              <td class="px-3 py-3 text-right text-sm font-mono text-gray-300">{formatPrice(stock.buyPrice)}</td>
              <td class="px-3 py-3 text-right text-sm font-mono {priceClass(stock.profitRate)}">{formatPrice(stock.curPrice)}</td>
              <td class="px-3 py-3 text-right text-sm {priceClass(stock.profitLoss)}">
                {stock.profitLoss >= 0 ? '+' : ''}{formatPrice(stock.profitLoss)}
              </td>
              <td class="px-3 py-3 text-right text-sm {priceClass(stock.profitRate)}">{formatRate(stock.profitRate)}</td>
              <td class="px-3 py-3 text-right text-sm text-gray-300">{formatPrice(stock.value)}</td>
            </tr>
          {:else}
            <tr>
              <td colspan="7" class="px-4 py-8 text-center text-gray-500">보유 종목 없음</td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>

  {:else if activeTab === 'pending'}
    <div class="bg-gray-800 rounded-xl overflow-hidden">
      {#if pending.length === 0}
        <div class="p-8 text-center text-gray-500">미체결 주문 없음</div>
      {:else}
        <table>
          <thead>
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-400">종목</th>
              <th class="px-3 py-3 text-center text-xs font-medium text-gray-400">구분</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">주문가</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">주문수량</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">미체결</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">체결가</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">체결량</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">시간</th>
              <th class="px-3 py-3 text-center text-xs font-medium text-gray-400"></th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700">
            {#each pending as order (order.ordNo)}
              <tr class="hover:bg-gray-700 transition-colors">
                <td class="px-4 py-3">
                  <div class="text-sm font-medium text-white">{order.stkNm}</div>
                  <div class="text-xs text-gray-500">{order.stkCd}</div>
                </td>
                <td class="px-3 py-3 text-center text-sm font-medium {tradeTypeClass(order.trdeTp)}">
                  {order.ioTpNm || tradeTypeLabel(order.trdeTp)}
                </td>
                <td class="px-3 py-3 text-right text-sm font-mono text-gray-300">
                  {parseInt(order.ordPric).toLocaleString()}
                </td>
                <td class="px-3 py-3 text-right text-sm text-gray-300">{order.ordQty}</td>
                <td class="px-3 py-3 text-right text-sm text-yellow-400">{order.osoQty}</td>
                <td class="px-3 py-3 text-right text-sm font-mono text-gray-300">
                  {parseInt(order.cntrPric) > 0 ? parseInt(order.cntrPric).toLocaleString() : '-'}
                </td>
                <td class="px-3 py-3 text-right text-sm text-gray-300">
                  {parseInt(order.cntrQty) > 0 ? order.cntrQty : '-'}
                </td>
                <td class="px-3 py-3 text-right text-xs text-gray-400">{formatTm(order.tm)}</td>
                <td class="px-3 py-3 text-center">
                  <button
                    onclick={() => cancelOrder(order)}
                    class="text-xs px-2 py-1 rounded bg-red-900/50 hover:bg-red-800/50 text-red-300 transition-colors"
                  >취소</button>
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      {/if}
    </div>

  {:else}
    <div class="bg-gray-800 rounded-xl overflow-hidden">
      {#if history.length === 0}
        <div class="p-8 text-center text-gray-500">오늘 주문 내역 없음</div>
      {:else}
        <table>
          <thead>
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-400">종목</th>
              <th class="px-3 py-3 text-center text-xs font-medium text-gray-400">구분</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">주문가</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">주문수량</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">체결가</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">체결량</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">미체결</th>
              <th class="px-3 py-3 text-center text-xs font-medium text-gray-400">상태</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">수수료</th>
              <th class="px-3 py-3 text-right text-xs font-medium text-gray-400">시간</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-700">
            {#each history as order (order.ordNo + order.ordTm)}
              <tr class="hover:bg-gray-700 transition-colors">
                <td class="px-4 py-3">
                  <div class="text-sm font-medium text-white">{order.stkNm}</div>
                  <div class="text-xs text-gray-500">{order.stkCd}</div>
                </td>
                <td class="px-3 py-3 text-center text-sm font-medium {tradeTypeClass(order.trdeTp)}">
                  {order.ioTpNm || tradeTypeLabel(order.trdeTp)}
                </td>
                <td class="px-3 py-3 text-right text-sm font-mono text-gray-300">
                  {parseInt(order.ordPric).toLocaleString()}
                </td>
                <td class="px-3 py-3 text-right text-sm text-gray-300">{order.ordQty}</td>
                <td class="px-3 py-3 text-right text-sm font-mono text-gray-300">
                  {parseInt(order.cntrPric) > 0 ? parseInt(order.cntrPric).toLocaleString() : '-'}
                </td>
                <td class="px-3 py-3 text-right text-sm text-gray-300">
                  {parseInt(order.cntrQty) > 0 ? order.cntrQty : '-'}
                </td>
                <td class="px-3 py-3 text-right text-sm {parseInt(order.osoQty) > 0 ? 'text-yellow-400' : 'text-gray-500'}">
                  {parseInt(order.osoQty) > 0 ? order.osoQty : '0'}
                </td>
                <td class="px-3 py-3 text-center">
                  <span class="text-xs px-2 py-0.5 rounded {
                    order.ordStt === '체결' ? 'bg-green-900/50 text-green-400' :
                    order.ordStt === '확인' ? 'bg-blue-900/50 text-blue-400' :
                    'bg-gray-700 text-gray-400'
                  }">{order.ordStt || '-'}</span>
                </td>
                <td class="px-3 py-3 text-right text-xs text-gray-400">
                  {parseInt(order.trdeCmsn) + parseInt(order.trdeTax) > 0
                    ? (parseInt(order.trdeCmsn) + parseInt(order.trdeTax)).toLocaleString()
                    : '-'}
                </td>
                <td class="px-3 py-3 text-right text-xs text-gray-400">{formatTm(order.ordTm)}</td>
              </tr>
            {/each}
          </tbody>
        </table>
      {/if}
    </div>
  {/if}
{:else}
  <div class="bg-gray-800 rounded-xl p-8 text-center text-gray-500">
    계좌 정보를 불러올 수 없습니다.
  </div>
{/if}