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

/**
 * 클라우드(운영 서비스) 자산 목록 뷰
 */
export function renderCloudList(container: HTMLElement) {
  renderPageHeader(container, '클라우드');

  const fullList = state.masterData.cloud || [];
  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 data-sort="${ASSET_SCHEMA.PRODUCT_NAME.key}">${ASSET_SCHEMA.PRODUCT_NAME.ui}</th>
        <th data-sort="${ASSET_SCHEMA.ASSET_PURPOSE.key}">${ASSET_SCHEMA.ASSET_PURPOSE.ui}</th>
        <th data-sort="${ASSET_SCHEMA.PURCHASE_VENDOR.key}">${ASSET_SCHEMA.PURCHASE_VENDOR.ui}</th>
        <th class="text-center" data-sort="${ASSET_SCHEMA.PURCHASE_AMOUNT.key}">${ASSET_SCHEMA.PURCHASE_AMOUNT.ui}</th>
        <th class="col-memo" data-sort="${ASSET_SCHEMA.MEMO.key}">${ASSET_SCHEMA.MEMO.ui}</th>
      </tr>
    </thead>
    <tbody id="cloud-tbody"></tbody>
  `;
  
  tableWrapper.appendChild(table);
  container.appendChild(tableWrapper);
  const tbody = table.querySelector('tbody')!;

  const updateTable = () => {
    let filtered = applyCommonFilters(fullList, currentFilters, ['PRODUCT_NAME', 'ASSET_PURPOSE', 'PURCHASE_VENDOR']);

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

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="5" 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';
      
      tr.innerHTML = `
        <td>${asset[ASSET_SCHEMA.PRODUCT_NAME.key]||''}</td>
        <td>${asset[ASSET_SCHEMA.ASSET_PURPOSE.key]||''}</td>
        <td>${asset[ASSET_SCHEMA.PURCHASE_VENDOR.key]||''}</td>
        <td class="text-right" style="font-weight:600;">₩ ${asset[ASSET_SCHEMA.PURCHASE_AMOUNT.key] ? Number(String(asset[ASSET_SCHEMA.PURCHASE_AMOUNT.key]).replace(/,/g, '')).toLocaleString() : '0'}</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: { Cloud, CreditCard, DollarSign, RefreshCcw, Plus } });
  };

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

