import { state } from '../../state';
import { HardwareAsset } from '../../excelHandler';
import { openModal } from './BaseModal';

/**
 * 하드웨어(서버, 전산비품 등) 모달 초기화 및 로직 제어
 */
export function initHWModal(renderContent: () => void, closeModals: () => void) {
  const hwForm = document.getElementById('hw-asset-form') as HTMLFormElement;
  const btnSaveHw = document.getElementById('btn-save-hw-asset') as HTMLButtonElement;
  const btnDeleteHw = document.getElementById('btn-delete-hw-asset') as HTMLButtonElement;

  // 저장 버튼 이벤트
  btnSaveHw?.addEventListener('click', (e) => {
    e.preventDefault();
    if (!hwForm.checkValidity()) { hwForm.reportValidity(); return; }
    
    const id = (document.getElementById('hw-asset-id') as HTMLInputElement).value;
    const fileInput = document.getElementById('hw-품의서') as HTMLInputElement;
    const 품의서명 = fileInput.files && fileInput.files.length > 0 ? fileInput.files[0].name : (document.getElementById('hw-품의서명') as HTMLElement).innerText.replace('📎', '');

    const newAsset: HardwareAsset = {
      id: id || Math.random().toString(36).substring(2, 9),
      type: (document.getElementById('hw-asset-type') as HTMLInputElement).value,
      법인: (document.getElementById('hw-법인') as HTMLInputElement).value,
      자산코드: (document.getElementById('hw-자산코드') as HTMLInputElement).value,
      명칭: (document.getElementById('hw-명칭') as HTMLInputElement).value,
      위치: (document.getElementById('hw-위치') as HTMLInputElement).value,
      관리자: (document.getElementById('hw-관리자') as HTMLInputElement).value,
      IP주소: (document.getElementById('hw-IP주소') as HTMLInputElement).value,
      MACaddress: (document.getElementById('hw-MACaddress') as HTMLInputElement).value,
      OS: (document.getElementById('hw-OS') as HTMLInputElement).value,
      HW사양: (document.getElementById('hw-HW사양') as HTMLTextAreaElement).value,
      구매일: (document.getElementById('hw-구매일') as HTMLInputElement).value,
      금액: (document.getElementById('hw-금액') as HTMLInputElement).value,
      납품업체: (document.getElementById('hw-납품업체') as HTMLInputElement).value,
      품의서명,
      비품유형: (document.getElementById('hw-asset-type') as HTMLInputElement).value === '전산비품' 
        ? (document.getElementById('hw-비품유형') as HTMLSelectElement).value : undefined
    };

    if (id) {
      const idx = state.masterData.hw.findIndex(a => a.id === id);
      if(idx !== -1) state.masterData.hw[idx] = newAsset;
    } else {
      state.masterData.hw.push(newAsset);
    }
    
    closeModals();
    renderContent();
  });

  // 삭제 버튼 이벤트
  btnDeleteHw?.addEventListener('click', (e) => {
    e.preventDefault();
    const id = (document.getElementById('hw-asset-id') as HTMLInputElement).value;
    if (confirm('삭제하시겠습니까?')) {
      state.masterData.hw = state.masterData.hw.filter(a => a.id !== id);
      closeModals();
      renderContent();
    }
  });
}

/**
 * 하드웨어 상세 모달 열기
 * @param asset 수정 시 자산 데이터, 신규 시 undefined
 */
export function openHwModal(asset?: HardwareAsset) {
  const hwModal = document.getElementById('hw-asset-modal') as HTMLDivElement;
  const hwForm = document.getElementById('hw-asset-form') as HTMLFormElement;
  const deleteBtn = document.getElementById('btn-delete-hw-asset')!;
  
  openModal('hw-asset-modal');
  hwForm.reset();
  
  if (asset) {
    document.getElementById('hw-modal-title')!.textContent = '자산 상세 정보 수정';
    deleteBtn.style.display = 'block';
    
    (document.getElementById('hw-asset-id') as HTMLInputElement).value = asset.id;
    (document.getElementById('hw-asset-type') as HTMLInputElement).value = asset.type;
    (document.getElementById('hw-법인') as HTMLInputElement).value = asset.법인;
    (document.getElementById('hw-자산코드') as HTMLInputElement).value = asset.자산코드;
    (document.getElementById('hw-명칭') as HTMLInputElement).value = asset.명칭;
    (document.getElementById('hw-위치') as HTMLInputElement).value = asset.위치;
    (document.getElementById('hw-관리자') as HTMLInputElement).value = asset.관리자;
    (document.getElementById('hw-IP주소') as HTMLInputElement).value = asset.IP주소;
    (document.getElementById('hw-MACaddress') as HTMLInputElement).value = asset.MACaddress;
    (document.getElementById('hw-OS') as HTMLInputElement).value = asset.OS;
    (document.getElementById('hw-HW사양') as HTMLTextAreaElement).value = asset.HW사양;
    (document.getElementById('hw-구매일') as HTMLInputElement).value = asset.구매일 || '';
    (document.getElementById('hw-금액') as HTMLInputElement).value = asset.금액 ? Number(asset.금액.replace(/,/g, '')).toLocaleString() : '';
    (document.getElementById('hw-납품업체') as HTMLInputElement).value = asset.납품업체 || '';
    (document.getElementById('hw-품의서명') as HTMLElement).innerText = asset.품의서명 ? `📎${asset.품의서명}` : '';
    (document.getElementById('hw-비품유형') as HTMLSelectElement).value = asset.비품유형 || '노트북';
  } else {
    document.getElementById('hw-modal-title')!.textContent = `새 ${state.activeSubTab} 자산 추가`;
    deleteBtn.style.display = 'none';
    (document.getElementById('hw-asset-id') as HTMLInputElement).value = '';
    (document.getElementById('hw-asset-type') as HTMLInputElement).value = state.activeSubTab;
    (document.getElementById('hw-품의서명') as HTMLElement).innerText = '';
    (document.getElementById('hw-비품유형') as HTMLSelectElement).value = '노트북';
  }
  
  // 전산비품일 경우 유형 선택 필드 노출
  if (state.activeSubTab === '전산비품') {
    document.getElementById('hw-비품유형-group')!.style.display = 'block';
  } else {
    document.getElementById('hw-비품유형-group')!.style.display = 'none';
  }
}
