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

export function renderSwList(container: HTMLElement) {
  const isInternal = state.activeSubTab === '내부';
  renderPageHeader(container, isInternal ? '내부' : '외부');
  
  const fullList = sortAssets(isInternal ? state.masterData.swInternal : state.masterData.swExternal);
  
  let sortState: SortState = { key: '', direction: 'asc' };
  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');
  
  if (isInternal) {
    table.innerHTML = `
      <thead>
        <tr>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SW_FIELD.key}">${ASSET_SCHEMA.SW_FIELD.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.DEV_OBJ.key}">${ASSET_SCHEMA.DEV_OBJ.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SW_STATUS.key}">${ASSET_SCHEMA.SW_STATUS.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SW_TYPE.key}">${ASSET_SCHEMA.SW_TYPE.ui}</th>
          <th class="col-memo" data-sort="${ASSET_SCHEMA.MEMO.key}">${ASSET_SCHEMA.MEMO.ui}</th>
        </tr>
      </thead>
      <tbody id="dynamic-tbody"></tbody>
    `;
  } else {
    table.innerHTML = `
      <thead>
        <tr>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.PRODUCT_NAME.key}">자산명</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.ASSET_TYPE.key}">유형</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SW_STATUS.key}">${ASSET_SCHEMA.SW_STATUS.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SW_FIELD.key}">${ASSET_SCHEMA.SW_FIELD.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.CURRENT_DEPT.key}">${ASSET_SCHEMA.CURRENT_DEPT.ui}</th>
          <th style="text-align:center;">${ASSET_SCHEMA.CURRENT_USER.ui}</th>
          <th style="text-align:center;">${ASSET_SCHEMA.PREV_USER.ui}</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.PURCHASE_DATE.key}">구매연월</th>
          <th style="text-align:center;">시작일</th>
          <th style="text-align:center;" data-sort="${ASSET_SCHEMA.EXPIRED_DATE.key}">만료일</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, ['PRODUCT_NAME', 'CURRENT_USER', 'CURRENT_DEPT']);

    if (sortState.key) {
      filtered = dynamicSort(filtered, sortState.key, sortState.direction);
    }

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="${isInternal ? 5 : 11}" style="text-align:center; padding: 3rem; color: var(--text-muted);">검색 결과가 없습니다.</td></tr>`;
      return;
    }

    filtered.forEach((asset, idx) => {
      if (isInternal) {
        const tr = document.createElement('tr');
        tr.style.cursor = 'pointer';
        tr.innerHTML = `
          <td style="text-align:center;">${asset[ASSET_SCHEMA.SW_FIELD.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.DEV_OBJ.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.SW_STATUS.key]||'보유중'}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.SW_TYPE.key]||'내부'}</td>
          <td class="col-memo">${formatInline(asset[ASSET_SCHEMA.MEMO.key]||'-')}</td>
        `;
        tr.addEventListener('click', () => openSwModal(asset, 'view'));
        tbody.appendChild(tr);
      } else {
        const tr = document.createElement('tr');
        tr.style.cursor = 'pointer';
        
        tr.innerHTML = `
          <td>${asset[ASSET_SCHEMA.PRODUCT_NAME.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.ASSET_TYPE.key]||'외부'}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.SW_STATUS.key]||'사용중'}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.SW_FIELD.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.CURRENT_DEPT.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.CURRENT_USER.key]||'-'}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.PREV_USER.key]||'-'}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.PURCHASE_DATE.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.PURCHASE_DATE.key]||''}</td>
          <td style="text-align:center;">${asset[ASSET_SCHEMA.EXPIRED_DATE.key]||''}</td>
          <td class="col-memo">${formatInline(asset[ASSET_SCHEMA.MEMO.key]||'-')}</td>
        `;
        tr.addEventListener('click', () => openSwModal(asset, 'view'));
        tbody.appendChild(tr);
      }
    });

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

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

  renderFilterBar(filterBar, {
    keywordLabel: `통합 검색 (${ASSET_SCHEMA.PRODUCT_NAME.ui}/${ASSET_SCHEMA.CURRENT_DEPT.ui})`,
    showField: true,
    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();
}

