import { state } from '../../core/state';
import { openSwModal } from '../../components/Modal/SWModal';
import { ASSET_SCHEMA, UI_TEXT } from '../../core/schema';
import { createIcons, Cloud, CreditCard, DollarSign, RefreshCcw } from 'lucide';

/**
 * 클라우드(운영 서비스) 자산 목록 뷰
 * 라인 정렬 보정 및 헤더 통일
 */
export function renderCloudList(container: HTMLElement) {
  const getFullList = () => state.masterData.cloud || [];
  
  const filterBar = document.createElement('div');
  filterBar.className = 'search-bar';
  filterBar.innerHTML = `
    <div class="search-item flex-1">
      <label>통합 검색 (${ASSET_SCHEMA.PRODUCT.ui}/부서/${ASSET_SCHEMA.ACCOUNT.ui})</label>
      <input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
    </div>
    <div class="search-item">
      <label>${ASSET_SCHEMA.PAY_METHOD.ui}</label>
      <select id="filter-payment">
        <option value="">전체 결제수단</option>
        <option value="법인카드">법인카드</option>
        <option value="인보이스">인보이스 (월별송금)</option>
      </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>${ASSET_SCHEMA.PLATFORM.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.CORP.ui}</th>
        <th class="text-center">담당부서</th>
        <th>용도(프로젝트)</th>
        <th>${ASSET_SCHEMA.ACCOUNT.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.PAY_METHOD.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.PAY_DAY.ui}</th>
        <th class="text-center">${ASSET_SCHEMA.BILLING.ui}</th>
        <th>${ASSET_SCHEMA.REMARKS.ui}</th>
      </tr>
    </thead>
    <tbody id="cloud-tbody"></tbody>
  `;
  
  tableWrapper.appendChild(table);
  container.appendChild(tableWrapper);
  const tbody = table.querySelector('tbody')!;

  const updateTable = () => {
    const keywordInput = document.getElementById('filter-keyword') as HTMLInputElement;
    const paymentSelect = document.getElementById('filter-payment') as HTMLSelectElement;

    const keyword = keywordInput ? keywordInput.value.toLowerCase().trim() : '';
    const payment = paymentSelect ? paymentSelect.value : '';

    const filtered = getFullList().filter(asset => {
      const kwMatch = !keyword || 
        (asset[ASSET_SCHEMA.PRODUCT.key] || '').toLowerCase().includes(keyword) || 
        (asset.부서 || '').toLowerCase().includes(keyword) || 
        (asset[ASSET_SCHEMA.ACCOUNT.key] || '').toLowerCase().includes(keyword);
      const payMatch = !payment || asset[ASSET_SCHEMA.PAY_METHOD.key] === payment;
      return kwMatch && payMatch;
    });

    tbody.innerHTML = '';
    if (filtered.length === 0) {
      tbody.innerHTML = `<tr><td colspan="10" 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 payMethod = asset[ASSET_SCHEMA.PAY_METHOD.key];
      const paymentBadge = payMethod === '법인카드' 
        ? `<span style="color:#6366f1; font-weight:600;"><i data-lucide="credit-card" style="width:14px; height:14px; vertical-align:middle; margin-right:4px;"></i>법인카드</span>`
        : (payMethod === '인보이스' 
            ? '<span style="color:#10b981; font-weight:600;"><i data-lucide="dollar-sign" style="width:14px; height:14px; vertical-align:middle; margin-right:4px;"></i>인보이스</span>'
            : '<span style="color:var(--text-muted)">미설정</span>');

      tr.innerHTML = `
        <td class="text-center">${idx+1}</td>
        <td style="font-weight:600; color:var(--primary-color)"><i data-lucide="cloud" style="width:14px; height:14px; vertical-align:middle; margin-right:4px;"></i> ${asset[ASSET_SCHEMA.PLATFORM.key]||'미지정'}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.CORP.key]||''}</td>
        <td class="text-center">${asset.부서||''}</td>
        <td>${asset[ASSET_SCHEMA.PRODUCT.key]||''}</td>
        <td>${asset[ASSET_SCHEMA.ACCOUNT.key]||''}</td>
        <td class="text-center">${paymentBadge}</td>
        <td class="text-center">${asset[ASSET_SCHEMA.PAY_DAY.key] ? asset[ASSET_SCHEMA.PAY_DAY.key] + '일' : ''}</td>
        <td class="text-right" style="font-weight:600;">₩ ${asset[ASSET_SCHEMA.BILLING.key] ? Number(String(asset[ASSET_SCHEMA.BILLING.key]).replace(/,/g, '')).toLocaleString() : '0'}</td>
        <td>${asset[ASSET_SCHEMA.REMARKS.key]||''}</td>
      `;
      
      tr.addEventListener('click', () => openSwModal(asset, 'view'));
      tbody.appendChild(tr);
    });
    createIcons({ icons: { Cloud, CreditCard, DollarSign, RefreshCcw } });
  };

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

  updateTable();
}
