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 renderMobileList(container: HTMLElement) {
  renderPageHeader(container, 'PC');

  const fullList = sortAssets(state.masterData.mobile || []);
  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.HW_STATUS.key}">${ASSET_SCHEMA.HW_STATUS.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.MODEL_NAME.key}">${ASSET_SCHEMA.MODEL_NAME.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.LOCATION.key}">${ASSET_SCHEMA.LOCATION.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.PURCHASE_DATE.key}">${ASSET_SCHEMA.PURCHASE_DATE.ui}</th>
        <th style="text-align:center;" data-sort="${ASSET_SCHEMA.PURCHASE_AMOUNT.key}">${ASSET_SCHEMA.PURCHASE_AMOUNT.ui}</th>
        <th style="text-align:center;">담당자</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, ['MODEL_NAME']);

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

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

    filtered.forEach((asset: any, idx: number) => {
      const tr = document.createElement('tr');
      tr.style.cursor = 'pointer';
      
      const mainManager = asset[ASSET_SCHEMA.MANAGER_MAIN.key] || '';
      
      tr.innerHTML = `
        <td style="text-align:center;">${asset[ASSET_SCHEMA.HW_STATUS.key] || '운영중'}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.PURCHASE_CORP.key] || ''}</td>
        <td>${asset[ASSET_SCHEMA.MODEL_NAME.key] || ''}</td>
        <td style="text-align:center;">${(asset[ASSET_SCHEMA.LOCATION.key] || '') + (asset[ASSET_SCHEMA.LOC_DETAIL.key] ? `(${asset[ASSET_SCHEMA.LOC_DETAIL.key]})` : (asset[ASSET_SCHEMA.LOCATION.key] ? '' : '-'))}</td>
        <td style="text-align:center;">${asset[ASSET_SCHEMA.PURCHASE_DATE.key] || ''}</td>
        <td style="text-align:right;">${Number(asset[ASSET_SCHEMA.PURCHASE_AMOUNT.key]||0).toLocaleString()}</td>
        <td style="text-align:center;">${mainManager}</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})`,
    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();
}

