import { state } from '../../core/state';
import { openSwModal } from '../../components/Modal/SWModal';

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

  const allSw = [...state.masterData.subSw, ...state.masterData.permSw].filter(sw => 
    sw.제품명?.includes(filterKeyword) || 
    sw.소프트웨어명?.includes(filterKeyword) ||
    sw.부서?.includes(filterKeyword)
  );

  container.innerHTML = `
    <div class="view-header">
      <div class="header-left">
        <h2>소프트웨어 자산 현황</h2>
        <span class="count-badge">총 ${allSw.length}건</span>
      </div>
      <div class="header-actions">
        <button id="btn-add-sw" class="btn btn-primary"><i data-lucide="plus"></i> S/W 등록</button>
      </div>
    </div>
    <div class="table-container">
      <table class="itam-table">
        <thead>
          <tr>
            <th>구분</th>
            <th>제품명</th>
            <th>관리조직</th>
            <th>수량</th>
            <th>구매일</th>
            <th>만료일</th>
            <th>금액</th>
            <th>비고</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          ${allSw.length === 0 ? '<tr><td colspan="9" class="empty-row">데이터가 없습니다.</td></tr>' : 
            allSw.map(sw => `
            <tr class="asset-row" data-id="${sw.id}" data-type="${sw.type}">
              <td><span class="type-badge ${sw.type === '구독SW' ? 'sub' : 'perm'}">${sw.type}</span></td>
              <td><strong>${sw.소프트웨어명 || sw.제품명 || '-'}</strong></td>
              <td>${sw.부서 || '-'}</td>
              <td>${sw.수량 || '1'}</td>
              <td>${sw.구매일 || '-'}</td>
              <td>${sw.만료일 || '-'}</td>
              <td>${sw.금액 || '-'}</td>
              <td><small>${sw.비고 || ''}</small></td>
              <td><button class="btn btn-sm btn-outline btn-detail" data-id="${sw.id}" data-type="${sw.type}">상세</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 type = (el as HTMLElement).getAttribute('data-type');
      const asset = [...state.masterData.subSw, ...state.masterData.permSw].find(a => a.id === id);
      if (asset) openSwModal(asset);
    });
  });

  document.getElementById('btn-add-sw')?.addEventListener('click', () => {
    const newSw: any = { 
      id: Math.random().toString(36).substring(2, 9), 
      type: '구독SW',
      수량: 1,
      부서: '전산팀'
    };
    openSwModal(newSw);
  });
}
