import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline, sortAssets, dynamicSort, renderPageHeader } from '../../core/utils';
import { ASSET_SCHEMA, UI_TEXT } from '../../core/schema';
import { setupTableSorting, SortState } from '../../core/tableHandler';
import { renderFilterBar, applyCommonFilters } from '../../core/filterHandler';
import { createIcons, Paperclip, RefreshCcw, Plus } from 'lucide';

export function renderPcList(container: HTMLElement) {
  renderPageHeader(container, 'PC');

  // asset_pc 데이터 중 '서버PC' 유형은 제외하고 렌더링 (서버 리스트에서 보여줌)
  const fullList = sortAssets((state.masterData.pc || []).filter((a: any) => a.asset_type !== '서버PC'));
  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');
  table.innerHTML = `
    <thead>
      <tr>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.CURRENT_USER.key}">${ASSET_SCHEMA.CURRENT_USER.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.CPU.key}">${ASSET_SCHEMA.CPU.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.MAINBOARD.key}">${ASSET_SCHEMA.MAINBOARD.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.RAM.key}">${ASSET_SCHEMA.RAM.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.GPU.key}">${ASSET_SCHEMA.GPU.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SSD1.key}">SSD1</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.SSD2.key}">SSD2</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.HDD1.key}">HDD1</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.HDD2.key}">HDD2</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.HDD3.key}">HDD3</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.HDD4.key}">HDD4</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.MAC_ADDR.key}">${ASSET_SCHEMA.MAC_ADDR.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, ['CURRENT_DEPT', 'CURRENT_USER', 'MODEL_NAME', 'MAC_ADDR', 'MANAGER_MAIN']);

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

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="13" style="text-align:center; padding: 3rem; color: var(--text-muted);">${UI_TEXT.MESSAGES.NO_DATA}</td></tr>`;
      return;
    }

    filtered.forEach((asset, idx) => {
      const tr = document.createElement('tr');
      tr.style.cursor = 'pointer';
      
      tr.innerHTML = `
        <td style="text-align:center;">${asset[ASSET_SCHEMA.CURRENT_USER.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.CPU.key]||''}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.MAINBOARD.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.RAM.key]||''}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.GPU.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.SSD1.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.SSD2.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.HDD1.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.HDD2.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.HDD3.key]||'-'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.HDD4.key]||'-'}</td>
        <td style="text-align:center; font-family:monospace; font-size:11px;">${asset[ASSET_SCHEMA.MAC_ADDR.key]||'-'}</td>
        <td class="col-memo">${formatInline(asset[ASSET_SCHEMA.MEMO.key]||'-')}</td>
      `;
      tr.addEventListener('click', () => openHwModal(asset, 'view'));
      tbody.appendChild(tr);
    });

    setupTableSorting(table, sortState, (key, dir) => {
      sortState = { key, direction: dir };
      updateTable();
    });
    createIcons({ icons: { Paperclip, RefreshCcw, Plus } });
  };

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

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

  // 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] || a['현사용부서'] || a['현사용조직']))).filter(Boolean).sort();
    orgUnits.forEach(dept => {
      const opt = document.createElement('option');
      opt.value = String(dept);
      opt.textContent = String(dept);
      deptSelect.appendChild(opt);
    });
  }

  updateTable();
}
