import { state } from '../../core/state';
import { openHwModal } from '../../components/Modal/HWModal';
import { formatInline, createBadge, sortAssets } from '../../core/utils';
import { ASSET_SCHEMA, UI_TEXT } from '../../core/schema';
import { createIcons, RefreshCcw } from 'lucide';

/**
 * 스토리지 자산 목록 뷰
 * 라인 정렬 보정 및 헤더 통일
 */
export function renderStorageList(container: HTMLElement) {
  const fullList = sortAssets(state.masterData.storage);
  
  const filterBar = document.createElement('div');
  filterBar.className = 'search-bar';
  
  const corps = Array.from(new Set(fullList.map(a => (a as any)[ASSET_SCHEMA.CORP.key]))).filter(Boolean).sort();
  const orgUnits = Array.from(new Set(fullList.map(a => (a as any)[ASSET_SCHEMA.ORG.key]))).filter(Boolean).sort();

  filterBar.innerHTML = `
    <div class="search-item flex-1">
      <label>통합 검색 (${ASSET_SCHEMA.ASSET_CODE.ui}/${ASSET_SCHEMA.ORG.ui})</label>
      <input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
    </div>
    <div class="search-item">
      <label>${ASSET_SCHEMA.CORP.ui}</label>
      <select id="filter-corp"><option value="">전체 법인</option>${corps.map(c => `<option value="${c}">${c}</option>`).join('')}</select>
    </div>
    <div class="search-item">
      <label>${ASSET_SCHEMA.ORG.ui}</label>
      <select id="filter-org-unit"><option value="">전체 조직</option>${orgUnits.map(o => `<option value="${o}">${o}</option>`).join('')}</select>
    </div>
    <button id="btn-reset-filters" class="btn btn-outline btn-reset">
      <i data-lucide="refresh-ccw"></i> ${UI_TEXT.ACTION.RESET_FILTER}
    </button>
  `;
  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">No</th>
        <th class="text-center">${ASSET_SCHEMA.CORP.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.ORG.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.ASSET_CODE.ui}</th>
        <th>용도</th>
        <th>상세</th>
        <th class="text-center">${ASSET_SCHEMA.LOCATION.ui}</th>
        <th class="text-center">담당자(정/부)</th>
      </tr>
    </thead>
    <tbody id="dynamic-tbody"></tbody>
  `;
  
  tableWrapper.appendChild(table);
  container.appendChild(tableWrapper);
  const tbody = table.querySelector('tbody')!;

  const updateTable = () => {
    const keywordInput = document.getElementById('filter-keyword') as HTMLInputElement;
    const corpSelect = document.getElementById('filter-corp') as HTMLSelectElement;
    const orgSelect = document.getElementById('filter-org-unit') as HTMLSelectElement;

    const keyword = keywordInput ? keywordInput.value.toLowerCase().trim() : '';
    const corp = corpSelect ? corpSelect.value : '';
    const orgUnit = orgSelect ? orgSelect.value : '';

    const filtered = fullList.filter(asset => {
      const matchKeyword = !keyword || 
        String((asset as any)[ASSET_SCHEMA.ASSET_CODE.key]||'').toLowerCase().includes(keyword) || 
        String((asset as any)[ASSET_SCHEMA.ORG.key]||'').toLowerCase().includes(keyword);
      const matchCorp = !corp || (asset as any)[ASSET_SCHEMA.CORP.key] === corp;
      const matchOrg = !orgUnit || (asset as any)[ASSET_SCHEMA.ORG.key] === orgUnit;
      return matchKeyword && matchCorp && matchOrg;
    });

    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 mainManager = (asset as any)[ASSET_SCHEMA.MANAGER_MAIN.key] || '';
      const subManager = (asset as any)[ASSET_SCHEMA.MANAGER_SUB.key] || '';
      const managerHtml = [
        mainManager ? `${createBadge('정', 'primary')} ${mainManager}` : '', 
        subManager ? `${createBadge('부', 'muted')} ${subManager}` : ''
      ].filter(v => v !== '').join(' / ');
      
      tr.innerHTML = `
        <td class="text-center">${idx+1}</td>
        <td class="text-center">${(asset as any)[ASSET_SCHEMA.CORP.key]}</td>
        <td class="text-center">${(asset as any)[ASSET_SCHEMA.ORG.key]||'-'}</td>
        <td class="text-center">${(asset as any)[ASSET_SCHEMA.ASSET_CODE.key]}</td>
        <td>${formatInline(asset.용도)}</td>
        <td>${formatInline(asset.상세)}</td>
        <td class="text-center">${formatInline((asset as any)[ASSET_SCHEMA.LOCATION.key])}</td>
        <td class="text-center">${managerHtml || '-'}</td>
      `;
      tr.addEventListener('click', () => openHwModal(asset, 'view'));
      tbody.appendChild(tr);
    });
  };

  document.getElementById('filter-keyword')?.addEventListener('input', updateTable);
  document.getElementById('filter-corp')?.addEventListener('change', updateTable);
  document.getElementById('filter-org-unit')?.addEventListener('change', updateTable);
  document.getElementById('btn-reset-filters')?.addEventListener('click', () => {
    (document.getElementById('filter-keyword') as HTMLInputElement).value = '';
    (document.getElementById('filter-corp') as HTMLSelectElement).value = '';
    (document.getElementById('filter-org-unit') as HTMLSelectElement).value = '';
    updateTable();
  });

  updateTable();
  createIcons({ icons: { RefreshCcw } });
}
