import { state } from '../../core/state';
import { formatPrice } from '../../core/utils';
import { createIcons, Plus, Edit2, Trash2 } from 'lucide';
import { openDomainModal } from '../../components/Modal/DomainModal';

export function renderDomainList(container: HTMLElement) {
  container.innerHTML = '';
  
  const header = document.createElement('div');
  header.className = 'list-header';
  header.innerHTML = `
    <div class="list-title-area">
      <h2 class="list-title">도메인 관리</h2>
    </div>
  `;
  container.appendChild(header);

  const tableWrapper = document.createElement('div');
  tableWrapper.className = 'table-container';
  
  const table = document.createElement('table');
  table.innerHTML = `
    <thead>
      <tr>
        <th style="text-align:center; width:50px;">No.</th>
        <th style="text-align:center;">유형</th>
        <th style="text-align:center;">법인</th>
        <th style="text-align:left;">서비스명</th>
        <th style="text-align:left;">관리도메인</th>
        <th style="text-align:center;">시작일</th>
        <th style="text-align:center;">만료일</th>
        <th style="text-align:right;">금액</th>
        <th style="text-align:center;">담당자</th>
        <th style="text-align:center;">담당자(부)</th>
        <th style="text-align:left;">비고</th>
      </tr>
    </thead>
    <tbody>
      ${state.masterData.domain.length === 0 ? `
        <tr>
          <td colspan="11" style="text-align:center; padding: 3rem; color: var(--text-muted);">등록된 도메인 정보가 없습니다.</td>
        </tr>
      ` : state.masterData.domain.map((item, idx) => `
        <tr class="domain-row" data-id="${item.id}" style="cursor:pointer;">
          <td style="text-align:center;">${idx + 1}</td>
          <td style="text-align:center;"><span class="badge badge-${item.type}">${item.type}</span></td>
          <td style="text-align:center;">${item.corp || ''}</td>
          <td>${item.service_name || ''}</td>
          <td>${item.domain_name || ''}</td>
          <td style="text-align:center;">${item.start_date || ''}</td>
          <td style="text-align:center;">${item.expiry_date || ''}</td>
          <td style="text-align:right;">${formatPrice(item.price)}</td>
          <td style="text-align:center;">${item.manager_main || ''}</td>
          <td style="text-align:center;">${item.manager_sub || ''}</td>
          <td class="text-truncate" style="max-width:200px;">${item.remarks || ''}</td>
        </tr>
      `).join('')}
    </tbody>
  `;
  
  tableWrapper.appendChild(table);
  container.appendChild(tableWrapper);

  // 이벤트 바인딩
  table.querySelectorAll('.domain-row').forEach(row => {
    row.addEventListener('click', () => {
      const id = row.getAttribute('data-id');
      const item = state.masterData.domain.find(d => d.id === id);
      if (item) openDomainModal(item);
    });
  });

  createIcons({ icons: { Plus, Edit2, Trash2 } });
}
