import { state } from '../../core/state';
import { dynamicSort, formatInline, getActionButtonsHTML, renderPageHeader } from '../../core/utils';
import { createIcons, Plus, Edit2, Trash2, RefreshCcw } from 'lucide';
import { openDomainModal } from '../../components/Modal/DomainModal';
import { setupTableSorting, SortState } from '../../core/tableHandler';
import { ASSET_SCHEMA } from '../../core/schema';
import { renderFilterBar, applyCommonFilters } from '../../core/filterHandler';

// 정렬 상태를 모듈 수준에서 관리하여 화면 갱신 시에도 유지되도록 함
let persistentSortState: SortState = { key: '', direction: 'asc' };

export function renderDomainList(container: HTMLElement) {
  renderPageHeader(container, '도메인');
  
  const fullList = state.masterData.domain;
  let currentFilters = { keyword: '', corp: '', dept: '', field: '' };

  // 검색바 추가
  const filterBar = document.createElement('div');
  filterBar.className = 'search-bar';
  container.appendChild(filterBar);

  const tableWrapper = document.createElement('div');
  tableWrapper.className = 'table-container';
  const table = document.createElement('table');
  table.innerHTML = `
    <thead>
      <tr>
        <th style="text-align:left;" data-sort="${ASSET_SCHEMA.DOMAIN_ADDR.key}">${ASSET_SCHEMA.DOMAIN_ADDR.ui}</th>
        <th style="text-align:left;" data-sort="${ASSET_SCHEMA.ASSET_PURPOSE.key}">${ASSET_SCHEMA.ASSET_PURPOSE.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.ASSET_TYPE.key}">${ASSET_SCHEMA.ASSET_TYPE.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.PURCHASE_CORP.key}">${ASSET_SCHEMA.PURCHASE_CORP.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.EXPIRED_DATE.key}">${ASSET_SCHEMA.EXPIRED_DATE.ui}</th>
        <th class="col-memo" data-sort="${ASSET_SCHEMA.MEMO.key}">${ASSET_SCHEMA.MEMO.ui}</th>
      </tr>
    </thead>
    <tbody id="dynamic-tbody"></tbody>
  `;
  
  tableWrapper.appendChild(table);
  container.appendChild(tableWrapper);
  const tbody = table.querySelector('tbody')!;

  const updateTable = () => {
    let filtered = applyCommonFilters(fullList, currentFilters, ['DOMAIN_ADDR', 'ASSET_PURPOSE', 'PRODUCT_NAME']);
    
    if (persistentSortState.key) {
      filtered = dynamicSort(filtered, persistentSortState.key, persistentSortState.direction);
    }

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; padding: 3rem; color: var(--text-muted);">등록된 도메인 정보가 없습니다.</td></tr>`;
      return;
    }

    filtered.forEach((item, idx) => {
      const tr = document.createElement('tr');
      tr.className = 'domain-row';
      tr.style.cursor = 'pointer';

      tr.innerHTML = `
        <td>${item[ASSET_SCHEMA.DOMAIN_ADDR.key] || ''}</td>
        <td>${item[ASSET_SCHEMA.ASSET_PURPOSE.key] || ''}</td>
        <td style="text-align:center;"><span class="badge badge-${item[ASSET_SCHEMA.ASSET_TYPE.key] === '관리중' ? 'primary' : 'muted'}">${item[ASSET_SCHEMA.ASSET_TYPE.key] || '-'}</span></td>
        <td style="text-align:center;">${item[ASSET_SCHEMA.PURCHASE_CORP.key] || ''}</td>
        <td style="text-align:center;">${item[ASSET_SCHEMA.EXPIRED_DATE.key] || ''}</td>
        <td class="col-memo">${formatInline(item[ASSET_SCHEMA.MEMO.key]||'-')}</td>
      `;
      tr.addEventListener('click', (e) => {
        openDomainModal(item);
      });
      tbody.appendChild(tr);
    });

    setupTableSorting(table, persistentSortState, (key, dir) => {
      persistentSortState = { key, direction: dir };
      updateTable();
    });

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

  renderFilterBar(filterBar, {
    keywordLabel: `통합 검색 (${ASSET_SCHEMA.DOMAIN_ADDR.ui}/${ASSET_SCHEMA.PRODUCT_NAME.ui})`,
    showCorp: true,
    showDept: true,
    onFilterChange: (filters) => {
      currentFilters = filters;
      updateTable();
    }
  });

  // Populate Dept Options
  const deptSelect = container.querySelector('#filter-dept') as HTMLSelectElement;
  if (deptSelect) {
    const orgUnits = Array.from(new Set(fullList.map(a => a[ASSET_SCHEMA.CURRENT_DEPT.key]))).filter(Boolean).sort();
    orgUnits.forEach(dept => {
      const opt = document.createElement('option');
      opt.value = String(dept);
      opt.textContent = String(dept);
      deptSelect.appendChild(opt);
    });
  }

  updateTable();
}

