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, RefreshCcw, Plus } from 'lucide';

/**
 * 스토리지 자산 목록 뷰
 */
export function renderStorageList(container: HTMLElement) {
  renderPageHeader(container, '스토리지');

  const fullList = sortAssets(state.masterData.storage);
  let sortState: SortState = { key: '', direction: 'asc' };
  let currentFilters = { keyword: '', loc: '', 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 class="text-center" data-sort="${ASSET_SCHEMA.HW_STATUS.key}">${ASSET_SCHEMA.HW_STATUS.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.CURRENT_USER.key}">${ASSET_SCHEMA.CURRENT_USER.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.ASSET_TYPE.key}">${ASSET_SCHEMA.ASSET_TYPE.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.VOLUME.key}">${ASSET_SCHEMA.VOLUME.ui}</th>
        <th data-sort="${ASSET_SCHEMA.MODEL_NAME.key}">${ASSET_SCHEMA.MODEL_NAME.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.SERIAL_NUM.key}">${ASSET_SCHEMA.SERIAL_NUM.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.LOCATION.key}">${ASSET_SCHEMA.LOCATION.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, ['MODEL_NAME', 'CURRENT_USER', 'SERIAL_NUM']);

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

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="8" class="text-center" style="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';

      const loc = asset[ASSET_SCHEMA.LOCATION.key] || '';
      const detail = asset[ASSET_SCHEMA.LOC_DETAIL.key] || '';
      const displayLoc = detail ? `${loc}(${detail})` : (loc || '-');

      tr.innerHTML = `
        <td class="text-center">${asset[ASSET_SCHEMA.HW_STATUS.key]||'-'}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.CURRENT_USER.key]||'-'}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.ASSET_TYPE.key]||'-'}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.VOLUME.key]||'-'}</td>
        <td>${formatInline(asset[ASSET_SCHEMA.MODEL_NAME.key]||asset[ASSET_SCHEMA.ASSET_NAME.key]||'-')}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.SERIAL_NUM.key]||'-'}</td>
        <td class="text-center">${displayLoc}</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: { RefreshCcw, Plus } });
  };

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

  // Populate Location 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]))).filter(Boolean).sort();
    orgUnits.forEach(dept => {
      const opt = document.createElement('option');
      opt.value = String(dept);
      opt.textContent = String(dept);
      deptSelect.appendChild(opt);
    });
  }

  updateTable();
}
