import { createIcons, Download, Upload, FileSpreadsheet, Plus, X, LayoutDashboard, Monitor, Server, Database, Laptop, CalendarClock, Key, Cpu, Layers, Users, Paperclip, Edit2 } from 'lucide';
import { downloadTemplate, exportToExcel, parseExcel } from './excelHandler';
import { state } from './state';
import { initSidebar } from './components/Sidebar';
import { initBaseModal } from './components/Modal/BaseModal';
import { initPCModal, openPcModal } from './components/Modal/PCModal';
import { initHWModal, openHwModal } from './components/Modal/HWModal';
import { initStorageModal, openStorageModal } from './components/Modal/StorageModal';
import { initSWModal, openSwModal } from './components/Modal/SWModal';
import { initSWUserModal, openSwUserModal } from './components/Modal/SWUserModal';
import { renderDashboard } from './views/DashboardView';
import { renderTable } from './views/AssetTableView';

declare var Chart: any;

// --- DOM Elements ---
const mainContent = document.getElementById('main-content') as HTMLElement;
const uploadInput = document.getElementById('excel-upload') as HTMLInputElement;
const btnAddAsset = document.getElementById('btn-add-asset') as HTMLButtonElement;
const btnDownloadTemp = document.getElementById('btn-download-template') as HTMLButtonElement;
const btnExport = document.getElementById('btn-export-excel') as HTMLButtonElement;

// Initialize Icons
createIcons({
  icons: { Download, Upload, FileSpreadsheet, Plus, X, LayoutDashboard, Monitor, Server, Database, Laptop, CalendarClock, Key, Cpu, Layers, Users, Paperclip, Edit2 }
});

// Initialize Components
const { closeAllModals } = initBaseModal();
initSidebar(renderContent);
initPCModal(renderContent, closeAllModals);
initHWModal(renderContent, closeAllModals);
initStorageModal(renderContent, closeAllModals);
initSWModal(renderContent, closeAllModals);
initSWUserModal(renderContent, closeAllModals);

// Dashboard Detail 닫기 버튼 (공통 처리용)
const btnCloseDashboardDetail = document.getElementById('btn-close-dashboard-detail') as HTMLButtonElement;
btnCloseDashboardDetail?.addEventListener('click', () => {
  document.getElementById('dashboard-detail-modal')?.classList.add('hidden');
});

// Add Element Button
btnAddAsset?.addEventListener('click', () => {
  if (state.activeSubTab === '대시보드') return;
  if (state.activeCategory === 'hw') {
    if (state.activeSubTab === '개인PC') openPcModal();
    else if (state.activeSubTab === '스토리지') openStorageModal();
    else openHwModal();
  } else {
    openSwModal();
  }
});

// --- Excel Controls ---
btnDownloadTemp?.addEventListener('click', () => downloadTemplate());
btnExport?.addEventListener('click', () => exportToExcel(state.masterData));

uploadInput?.addEventListener('change', async (e) => {
  const file = (e.target as HTMLInputElement).files?.[0];
  if (!file) return;
  try {
    state.masterData = await parseExcel(file);
    renderContent();
    alert('모든 시트 데이터 연동 완료');
  } catch (error) {
    console.error(error);
    alert('엑셀 파싱 오류: 템플릿 양식이 다르거나 파일이 손상되었습니다.');
  } finally {
    uploadInput.value = '';
  }
});

/**
 * 전역 렌더링 함수 - 각 컴포넌트에서 호출하여 화면을 갱신합니다.
 */
function renderContent() {
  mainContent.innerHTML = ''; // 화면 초기화
  
  if (state.activeSubTab === '대시보드') {
    renderDashboard(mainContent);
  } else {
    renderTable(mainContent);
  }
}

// Initial Render
renderContent();
