import { openModal, closeModals } from './BaseModal';
import { createIcons, X, Check, Database, Save, FileSpreadsheet, Layers, RefreshCcw } from 'lucide';
import { state, loadMasterDataFromDB } from '../../core/state';
import { TYPE_PREFIX_MAP, LOCATION_DATA } from './SharedData';
import { ASSET_SCHEMA } from '../../core/schema';

let parsedData: any = null;
let currentTab: string = '';
let onSuccessCallback: (() => void) | null = null;
let hasAttemptedBulkGenerate: boolean = false;

const UPLOAD_PREVIEW_MODAL_HTML = `
  <div id="upload-preview-modal" class="modal-overlay hidden">
    <div class="modal-content wide" style="width: 95vw; max-width: 1500px; height: 90vh; display: flex; flex-direction: column;">
      <div class="modal-header">
        <div style="display:flex; align-items:center; gap:0.75rem;">
          <div style="background:rgba(255,255,255,0.2); padding:0.5rem; border-radius:8px;">
            <i data-lucide="file-spreadsheet" style="width:20px; height:20px; color:white;"></i>
          </div>
          <div>
            <h2 id="upload-preview-title" style="color:white;">데이터 업로드 최종 검토</h2>
            <p style="font-size:12px; color:rgba(255,255,255,0.8); margin-top:2px;">수정 가능한 텍스트는 <span style="color:#ff3d00; font-weight:700;">다홍색(#FF3D00)</span>으로 표시됩니다.</p>
          </div>
        </div>
        <button id="btn-close-upload-preview" class="btn-icon" style="color:white;"><i data-lucide="x"></i></button>
      </div>
      
      <div class="modal-body" style="display:flex; padding:0; overflow:hidden; flex: 1;">
        <div id="upload-tab-sidebar" style="width:200px; border-right:1px solid var(--border-color); background:#fafafa; padding:1.5rem 1rem; overflow-y:auto; flex-shrink: 0;">
          <div style="font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase; margin-bottom:1rem; letter-spacing:0.05em;">카테고리</div>
          <div id="upload-tabs-container" style="display:flex; flex-direction:column; gap:0.4rem;"></div>
        </div>

        <div style="flex:1; display:flex; flex-direction:column; background:white; overflow:hidden;">
          <div id="upload-preview-stats" style="padding:1rem 1.5rem; border-bottom:1px solid var(--border-color); display:flex; justify-content:space-between; align-items:center; background:white;">
            <div style="display:flex; align-items:center; gap:0.5rem;">
              <span id="current-tab-name" style="font-weight:700; font-size:16px;">선택된 탭 없음</span>
              <span id="current-tab-count" class="badge badge-primary">0건</span>
              <button id="btn-bulk-generate-codes" class="btn btn-outline btn-sm hidden" style="margin-left:1rem; height:28px; font-size:12px; padding:0 0.75rem;">
                <i data-lucide="refresh-ccw" style="width:14px; height:14px; margin-right:4px;"></i> 자산코드 일괄 생성
              </button>
            </div>
            <div id="upload-warning-text" style="font-size:12px; color:#dc2626; font-weight:600; display:none;">
              * 자산번호가 누락된 항목이 있습니다. 일괄 생성을 눌러주세요.
            </div>
          </div>
          
          <div id="upload-preview-table-wrapper" style="flex:1; overflow:auto; padding:0;"></div>
        </div>
      </div>

      <div class="modal-footer" style="background:#f9fafb; border-top:1px solid var(--border-color); flex-shrink: 0;">
        <div style="display:flex; gap:0.75rem; width:100%; justify-content:flex-end;">
          <button id="btn-cancel-upload" class="btn btn-outline" style="height:40px; padding:0 1.5rem;">취소</button>
          <button id="btn-confirm-upload" class="btn btn-primary" style="height:40px; padding:0 2rem;">
            <i data-lucide="save"></i> 최종 데이터 저장하기
          </button>
        </div>
      </div>
    </div>
  </div>
`;

export function initUploadPreviewModal(onSuccess?: () => void) {
  if (onSuccess) onSuccessCallback = onSuccess;
  if (!document.getElementById('upload-preview-modal')) {
    document.body.insertAdjacentHTML('beforeend', UPLOAD_PREVIEW_MODAL_HTML);
  }
  document.getElementById('btn-close-upload-preview')?.addEventListener('click', closeModals);
  document.getElementById('btn-cancel-upload')?.addEventListener('click', closeModals);
  document.getElementById('btn-confirm-upload')?.addEventListener('click', () => confirmUpload());
  document.getElementById('btn-bulk-generate-codes')?.addEventListener('click', () => generateBulkCodes());
}

export function openUploadPreview(data: any) {
  parsedData = data;
  hasAttemptedBulkGenerate = false;
  const tabNames = Object.keys(data);
  if (tabNames.length === 0) { alert('업로드할 데이터가 없습니다.'); return; }
  currentTab = tabNames[0];
  renderTabs();
  renderCurrentTable();
  openModal('upload-preview-modal');
  createIcons({ icons: { X, Check, Database, Save, FileSpreadsheet, Layers, RefreshCcw } });
}

function renderTabs() {
  const container = document.getElementById('upload-tabs-container');
  if (!container) return;
  container.innerHTML = '';
  Object.keys(parsedData).forEach(tab => {
    const btn = document.createElement('div');
    btn.className = `upload-tab-btn ${tab === currentTab ? 'active' : ''}`;
    btn.style.cssText = `
      padding: 0.6rem 0.8rem; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500;
      display: flex; justify-content: space-between; align-items: center; transition: all 0.2s;
      background: ${tab === currentTab ? 'white' : 'transparent'};
      color: ${tab === currentTab ? 'var(--primary-color)' : 'var(--text-main)'};
      box-shadow: ${tab === currentTab ? '0 2px 4px rgba(0,0,0,0.05)' : 'none'};
      border: 1px solid ${tab === currentTab ? 'var(--border-color)' : 'transparent'};
    `;
    btn.innerHTML = `<span>${tab}</span><span style="font-size:11px; opacity:0.6;">${parsedData[tab].length}</span>`;
    btn.onclick = () => { syncCurrentDataFromDOM(); currentTab = tab; renderTabs(); renderCurrentTable(); };
    container.appendChild(btn);
  });
}

function renderCurrentTable() {
  const tableWrapper = document.getElementById('upload-preview-table-wrapper');
  const tabNameEl = document.getElementById('current-tab-name');
  const tabCountEl = document.getElementById('current-tab-count');
  const warningText = document.getElementById('upload-warning-text');
  if (!tableWrapper || !tabNameEl || !tabCountEl) return;

  const data = parsedData[currentTab];
  tabNameEl.textContent = currentTab;
  tabCountEl.textContent = `${data.length}건`;

  const generateBtn = document.getElementById('btn-bulk-generate-codes');
  const isHwTab = ['개인PC', '서버', '스토리지', '전산비품', '모바일기기'].includes(currentTab);
  if (generateBtn) { isHwTab ? generateBtn.classList.remove('hidden') : generateBtn.classList.add('hidden'); }

  if (!data || data.length === 0) {
    tableWrapper.innerHTML = '<div style="padding:4rem; text-align:center; color:var(--text-muted);">표시할 데이터가 없습니다.</div>';
    return;
  }

  const rawHeaders = Object.keys(data[0]).filter(k => k !== 'id' && k !== 'type' && k !== '상세용도');
  const headerMap: Record<string, string> = {};
  Object.values(ASSET_SCHEMA).forEach(item => { headerMap[item.key] = item.ui; });

  const centerCols = ['No.', '구매법인', '자산번호', '현 사용조직', '설치위치', '보관위치', '상세위치', '담당자', '구매연월', '현재상태'];
  const locations = Object.keys(LOCATION_DATA);

  let hasAnyMissingCode = false;

  let tableHTML = `
    <table class="preview-table" id="upload-data-table" style="width:100%; border-collapse:collapse; min-width:max-content; table-layout:auto;">
      <thead style="position:sticky; top:0; z-index:10; background:#f8fafc; box-shadow:0 1px 0 var(--border-color);">
        <tr>
          <th style="padding:0.8rem 1rem; text-align:center; font-size:12px; border-bottom:1px solid var(--border-color); width:50px; background:#FAFAFA;">No.</th>
          ${rawHeaders.map(h => {
            const label = headerMap[h] || h;
            const isCenter = centerCols.includes(label);
            return `<th data-key="${h}" style="padding:0.8rem 1rem; text-align:${isCenter ? 'center' : 'left'}; font-size:12px; border-bottom:1px solid var(--border-color); color:var(--text-muted); font-weight:600; background:#FAFAFA;">${label}</th>`;
          }).join('')}
        </tr>
      </thead>
      <tbody>
        ${data.map((row: any, idx: number) => {
          const isCodeMissing = isHwTab && !row[ASSET_SCHEMA.ASSET_CODE.key];
          if (isCodeMissing) hasAnyMissingCode = true;
          const showRedBox = hasAttemptedBulkGenerate && isCodeMissing;
          const trStyle = showRedBox ? 'outline: 2px solid #ff3d00; outline-offset: -2px; background: #fff5f2;' : 'border-bottom:1px solid #f1f5f9;';

          return `
            <tr data-id="${row.id}" style="${trStyle}">
              <td style="padding:0.8rem 1rem; text-align:center; font-size:13px; color:var(--text-muted); background:#fafafa;">${idx + 1}</td>
              ${rawHeaders.map(h => {
                const label = headerMap[h] || h;
                const isCenter = centerCols.includes(label);
                const isCodeCol = h === ASSET_SCHEMA.ASSET_CODE.key;
                const isLocCol = h === ASSET_SCHEMA.LOCATION.key || h === ASSET_SCHEMA.STORE_LOC.key;
                const isDetailLocCol = h === ASSET_SCHEMA.DETAIL_LOCATION.key;
                const fontColor = isCodeCol ? '#111111' : '#ff3d00';
                
                if (isLocCol) {
                  return `
                    <td style="padding:0; min-width:120px; border-right:1px solid #f8fafc;">
                      <select class="preview-select loc-select" data-key="${h}" style="width:100%; height:36px; border:none; background:transparent; padding:0 0.5rem; font-size:13px; color:#ff3d00; font-weight:600; outline:none; cursor:pointer;">
                        <option value="">선택</option>
                        ${locations.map(loc => `<option value="${loc}" ${String(row[h]||'').trim() === loc ? 'selected' : ''}>${loc}</option>`).join('')}
                      </select>
                    </td>
                  `;
                } else if (isDetailLocCol) {
                  const parentLocKey = row[ASSET_SCHEMA.LOCATION.key] ? ASSET_SCHEMA.LOCATION.key : ASSET_SCHEMA.STORE_LOC.key;
                  const currentLoc = String(row[parentLocKey] || '').trim();
                  const subLocs = LOCATION_DATA[currentLoc] || [];
                  return `
                    <td style="padding:0; min-width:120px; border-right:1px solid #f8fafc;">
                      <select class="preview-select detail-select" data-key="${h}" style="width:100%; height:36px; border:none; background:transparent; padding:0 0.5rem; font-size:13px; color:#ff3d00; font-weight:600; outline:none; cursor:pointer;">
                        <option value="">선택</option>
                        ${subLocs.map(sl => `<option value="${sl}" ${String(row[h]||'').trim() === sl ? 'selected' : ''}>${sl}</option>`).join('')}
                        ${(row[h] && !subLocs.includes(String(row[h]).trim())) ? `<option value="${row[h]}" selected>${row[h]}</option>` : ''}
                      </select>
                    </td>
                  `;
                } else {
                  return `<td contenteditable="${!isCodeCol}" data-key="${h}" style="padding:0.8rem 1rem; font-size:13px; text-align:${isCenter ? 'center' : 'left'}; outline:none; color: ${fontColor} !important; border-right:1px solid #f8fafc;">${row[h] || ''}</td>`;
                }
              }).join('')}
            </tr>
          `;
        }).join('')}
      </tbody>
    </table>
  `;

  tableWrapper.innerHTML = tableHTML;
  if (warningText) warningText.style.display = (hasAttemptedBulkGenerate && hasAnyMissingCode) ? 'block' : 'none';
  
  // ─── 드롭다운 실시간 연동 이벤트 ───
  tableWrapper.querySelectorAll('.loc-select').forEach(sel => {
    sel.addEventListener('change', (e) => {
      const target = e.target as HTMLSelectElement;
      const tr = target.closest('tr')!;
      const detailSel = tr.querySelector('.detail-select') as HTMLSelectElement;
      if (detailSel) {
        const subLocs = LOCATION_DATA[target.value] || [];
        detailSel.innerHTML = '<option value="">선택</option>' + subLocs.map(sl => `<option value="${sl}">${sl}</option>`).join('');
        // 데이터 객체도 즉시 동기화
        syncCurrentDataFromDOM();
      }
    });
  });

  // 편집 포커스 스타일
  tableWrapper.querySelectorAll('td[contenteditable="true"]').forEach(td => {
    td.addEventListener('focus', () => (td as HTMLElement).style.background = '#fff8f6');
    td.addEventListener('blur', () => (td as HTMLElement).style.background = 'transparent');
  });
}

function syncCurrentDataFromDOM() {
  const table = document.getElementById('upload-data-table') as HTMLTableElement;
  if (!table) return;
  const rows = table.querySelectorAll('tbody tr');
  const data = parsedData[currentTab];
  rows.forEach((tr) => {
    const asset = data.find((a: any) => a.id === tr.getAttribute('data-id'));
    if (asset) {
      tr.querySelectorAll('td[contenteditable="true"]').forEach(td => {
        const key = td.getAttribute('data-key')!;
        asset[key] = td.textContent?.trim() || '';
      });
      tr.querySelectorAll('select.preview-select').forEach(sel => {
        const key = sel.getAttribute('data-key')!;
        asset[key] = (sel as HTMLSelectElement).value;
      });
    }
  });
}

async function confirmUpload() {
  syncCurrentDataFromDOM();
  const tabNames = Object.keys(parsedData);
  const hwTabs = ['개인PC', '서버', '스토리지', '전산비품', '모바일기기'];
  for (const tab of tabNames) {
    if (hwTabs.includes(tab)) {
      const missingCodeRows = parsedData[tab].filter((r: any) => !r[ASSET_SCHEMA.ASSET_CODE.key]);
      if (missingCodeRows.length > 0) {
        alert(`[${tab}] 카테고리에 자산번호가 누락된 항목이 있습니다.\n번호를 생성하거나 수정한 후 다시 시도해주세요.`);
        hasAttemptedBulkGenerate = true;
        renderCurrentTable();
        return;
      }
    }
  }

  const confirmBtn = document.getElementById('btn-confirm-upload') as HTMLButtonElement;
  if (confirmBtn) { confirmBtn.disabled = true; confirmBtn.innerHTML = '저장 중...'; }

  try {
    let successCount = 0;
    const API_BASE = `http://${location.hostname}:3000`;
    for (const tab of tabNames) {
      const data = parsedData[tab];
      let endpoint = '';
      if (tab === '개인PC') endpoint = `${API_BASE}/api/pc/batch`;
      else if (tab === '서버') endpoint = `${API_BASE}/api/server/batch`;
      else if (tab === '스토리지') endpoint = `${API_BASE}/api/storage/batch`;
      else if (tab === '전산비품') endpoint = `${API_BASE}/api/equip/batch`;
      else if (tab === '모바일기기') endpoint = `${API_BASE}/api/mobile/batch`;
      else if (tab === '구독SW') endpoint = `${API_BASE}/api/sw/sub/batch`;
      else if (tab === '영구SW') endpoint = `${API_BASE}/api/sw/perm/batch`;
      else if (tab === '클라우드') endpoint = `${API_BASE}/api/cloud/batch`;
      else if (tab === '도메인') endpoint = `${API_BASE}/api/ops/domain/batch`;
      if (endpoint) {
        const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
        if (response.ok) successCount++;
      }
    }
    if (successCount > 0) { if (onSuccessCallback) onSuccessCallback(); closeModals(); alert(`${successCount}개 카테고리의 데이터가 성공적으로 업로드되었습니다.`); }
    else { alert('데이터 업로드에 실패했습니다.'); }
  } catch (err) { alert('업로드 중 오류가 발생했습니다.'); }
  finally { if (confirmBtn) { confirmBtn.disabled = false; confirmBtn.innerHTML = '<i data-lucide="save"></i> 최종 데이터 저장하기'; createIcons({ icons: { Save } }); } }
}

async function generateBulkCodes() {
  syncCurrentDataFromDOM();
  const data = parsedData[currentTab];
  if (!data) return;
  hasAttemptedBulkGenerate = true;
  const generateBtn = document.getElementById('btn-bulk-generate-codes') as HTMLButtonElement;
  if (generateBtn) { generateBtn.disabled = true; generateBtn.innerHTML = '생성 중...'; }
  try {
    const rowsToProcess = data.filter((r: any) => !r[ASSET_SCHEMA.ASSET_CODE.key]);
    if (rowsToProcess.length === 0) { alert('이미 모든 항목에 자산코드가 부여되어 있습니다.'); return; }
    const groups: Record<string, any[]> = {};
    rowsToProcess.forEach((r: any) => {
      const type = r.상세용도 || r.유형 || r.type || 'ETC';
      const typeCode = TYPE_PREFIX_MAP[type] || 'ETC';
      const purchaseYM = String(r[ASSET_SCHEMA.PURCHASE_YM.key] || '').replace(/[^0-9]/g, '');
      if (purchaseYM.length < 6) return;
      const prefix = `${typeCode}-${purchaseYM.substring(0, 6)}-`;
      if (!groups[prefix]) groups[prefix] = [];
      groups[prefix].push(r);
    });
    for (const prefix in groups) {
      const rows = groups[prefix];
      const res = await fetch(`http://${location.hostname}:3000/api/generate-asset-code?prefix=${prefix}`);
      const result = await res.json();
      if (result.nextCode) {
        let baseNum = parseInt(result.nextCode.replace(prefix, ''));
        rows.forEach((r, idx) => { r[ASSET_SCHEMA.ASSET_CODE.key] = `${prefix}${(baseNum + idx).toString().padStart(4, '0')}`; });
      }
    }
    renderCurrentTable();
    alert('자산코드 생성이 완료되었습니다.');
  } catch (err) { alert('자산코드 생성 중 오류가 발생했습니다.'); }
  finally { if (generateBtn) { generateBtn.disabled = false; generateBtn.innerHTML = '<i data-lucide="refresh-ccw"></i> 자산코드 일괄 생성'; createIcons({ icons: { RefreshCcw } }); } }
}
