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

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

  const servers = state.masterData.server.filter(s => 
    s.자산코드?.includes(filterKeyword) || 
    s.모델명?.includes(filterKeyword) ||
    s.IP주소?.includes(filterKeyword) ||
    s.실사용조직?.includes(filterKeyword)
  );

  container.innerHTML = `
    <div class="view-header">
      <div class="header-left">
        <h2>서버 자산 현황</h2>
        <span class="count-badge">총 ${servers.length}대</span>
      </div>
      <div class="header-actions">
        <button id="btn-add-server" 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>IP 주소</th>
            <th>모델명</th>
            <th>상태</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          ${servers.length === 0 ? '<tr><td colspan="8" class="empty-row">데이터가 없습니다.</td></tr>' : 
            servers.map(s => `
            <tr class="asset-row" data-id="${s.id}">
              <td>${s.법인 || 'HM'}</td>
              <td><span class="code-link">${s.자산코드 || '미부여'}</span></td>
              <td>${s.서버용도 || '-'}</td>
              <td>${s.실사용조직 || '-'}</td>
              <td><code>${s.IP주소 || '-'}</code></td>
              <td>${s.모델명 || '-'}</td>
              <td><span class="status-badge ${s.상태 === '사용중' ? 'active' : ''}">${s.상태 || '운영'}</span></td>
              <td><button class="btn btn-sm btn-outline btn-detail" data-id="${s.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.server.find(a => a.id === id);
      if (asset) openHwModal(asset, 'view');
    });
  });

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