import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';

export function renderPcList(filterKeyword: string = '') {
  const container = document.getElementById('view-container');
  if (!container) return;

  const pcs = state.masterData.pc.filter(pc => 
    pc.자산코드?.includes(filterKeyword) || 
    pc.사용자?.includes(filterKeyword) || 
    pc.모델명?.includes(filterKeyword) ||
    pc.실사용조직?.includes(filterKeyword)
  );

  container.innerHTML = `
    <div class="view-header">
      <div class="header-left">
        <h2>개인PC 자산 현황</h2>
        <span class="count-badge">총 ${pcs.length}대</span>
      </div>
      <div class="header-actions">
        <button id="btn-add-pc" class="btn btn-primary"><i data-lucide="plus"></i> 신규 등록</button>
      </div>
    </div>
    <div class="table-container">
      <table class="itam-table">
        <thead>
          <tr>
            <th>구매법인</th>
            <th>자산번호</th>
            <th>실사용조직</th>
            <th>사용자</th>
            <th>모델명</th>
            <th>사양 (CPU/RAM)</th>
            <th>도입일</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          ${pcs.length === 0 ? '<tr><td colspan="8" class="empty-row">데이터가 없습니다.</td></tr>' : 
            pcs.map(pc => `
            <tr class="asset-row" data-id="${pc.id}">
              <td>${pc.법인 || '-'}</td>
              <td><span class="code-link">${pc.자산코드 || pc.관리번호 || '미부여'}</span></td>
              <td>${pc.실사용조직 || pc.현사용조직 || '-'}</td>
              <td>${pc.사용자 || '-'}</td>
              <td>${pc.모델명 || '-'}</td>
              <td><small>${pc.CPU || '-'} / ${pc.RAM || '-'}</small></td>
              <td>${pc.도입일 || pc.구매일 || '-'}</td>
              <td><button class="btn btn-sm btn-outline btn-detail" data-id="${pc.id}">상세</button></td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;

  // 이벤트 바인딩
  container.querySelectorAll('.asset-row, .btn-detail').forEach(el => {
    el.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = (el as HTMLElement).getAttribute('data-id');
      const asset = state.masterData.pc.find(a => a.id === id);
      if (asset) openHwModal(asset, 'view');
    });
  });

  document.getElementById('btn-add-pc')?.addEventListener('click', () => {
    const newPc: any = { 
      id: Math.random().toString(36).substring(2, 9), 
      type: '개인PC',
      법인: 'HM',
      관리조직: '전산팀',
      상태: '사용중'
    };
    openHwModal(newPc, 'add');
  });
}
