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

/**
 * 스토리지 모달 초기화 및 로직 제어
 */
export function initStorageModal(renderContent: () => void, closeModals: () => void) {
  const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
  const btnSaveStorage = document.getElementById('btn-save-storage-asset') as HTMLButtonElement;
  const btnDeleteStorage = document.getElementById('btn-delete-storage-asset') as HTMLButtonElement;

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

    const newAsset: HardwareAsset = {
      id: id || Math.random().toString(36).substring(2, 9),
      type: '스토리지',
      법인: (document.getElementById('storage-법인') as HTMLSelectElement).value,
      storage유형: (document.getElementById('storage-유형') as HTMLSelectElement).value,
      자산코드: (document.getElementById('storage-자산코드') as HTMLInputElement).value,
      명칭: (document.getElementById('storage-명칭') as HTMLInputElement).value,
      위치: (document.getElementById('storage-위치') as HTMLInputElement).value,
      관리자: '',
      IP주소: (document.getElementById('storage-IP주소') as HTMLInputElement).value,
      MACaddress: (document.getElementById('storage-MAC주소') as HTMLInputElement).value,
      HW사양: '',
      OS: '',
      모델명: (document.getElementById('storage-모델명') as HTMLInputElement).value,
      용량: (document.getElementById('storage-용량') as HTMLInputElement).value,
      담당자_정: (document.getElementById('storage-담당자_정') as HTMLInputElement).value,
      담당자_부: (document.getElementById('storage-담당자_부') as HTMLInputElement).value,
      구매일: (document.getElementById('storage-구매일') as HTMLInputElement).value,
      금액: (document.getElementById('storage-금액') as HTMLInputElement).value,
      납품업체: (document.getElementById('storage-납품업체') as HTMLInputElement).value,
      품의서명
    };

    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();
  });

  // 삭제 버튼 이벤트
  btnDeleteStorage?.addEventListener('click', (e) => {
    e.preventDefault();
    const id = (document.getElementById('storage-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 openStorageModal(asset?: HardwareAsset) {
  const storageModal = document.getElementById('storage-asset-modal') as HTMLDivElement;
  const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
  const deleteBtn = document.getElementById('btn-delete-storage-asset')!;
  
  openModal('storage-asset-modal');
  storageForm.reset();
  
  if (asset) {
    document.getElementById('storage-modal-title')!.textContent = '스토리지 상세 정보 수정';
    deleteBtn.style.display = 'block';
    
    (document.getElementById('storage-asset-id') as HTMLInputElement).value = asset.id;
    (document.getElementById('storage-법인') as HTMLSelectElement).value = asset.법인;
    (document.getElementById('storage-유형') as HTMLSelectElement).value = asset.storage유형 || 'NAS';
    (document.getElementById('storage-자산코드') as HTMLInputElement).value = asset.자산코드;
    (document.getElementById('storage-명칭') as HTMLInputElement).value = asset.명칭;
    (document.getElementById('storage-위치') as HTMLInputElement).value = asset.위치 || '';
    (document.getElementById('storage-모델명') as HTMLInputElement).value = asset.모델명 || '';
    (document.getElementById('storage-용량') as HTMLInputElement).value = asset.용량 || '';
    (document.getElementById('storage-담당자_정') as HTMLInputElement).value = asset.담당자_정 || '';
    (document.getElementById('storage-담당자_부') as HTMLInputElement).value = asset.담당자_부 || '';
    (document.getElementById('storage-IP주소') as HTMLInputElement).value = asset.IP주소 || '';
    (document.getElementById('storage-MAC주소') as HTMLInputElement).value = asset.MACaddress || '';
    (document.getElementById('storage-구매일') as HTMLInputElement).value = asset.구매일 || '';
    (document.getElementById('storage-금액') as HTMLInputElement).value = asset.금액 ? Number(asset.금액.replace(/,/g, '')).toLocaleString() : '';
    (document.getElementById('storage-납품업체') as HTMLInputElement).value = asset.납품업체 || '';
    (document.getElementById('storage-품의서명') as HTMLElement).innerText = asset.품의서명 ? `📎${asset.품의서명}` : '';
  } else {
    document.getElementById('storage-modal-title')!.textContent = '새 스토리지 자산 추가';
    deleteBtn.style.display = 'none';
    (document.getElementById('storage-asset-id') as HTMLInputElement).value = '';
    (document.getElementById('storage-법인') as HTMLSelectElement).value = '한맥';
    (document.getElementById('storage-유형') as HTMLSelectElement).value = 'NAS';
    (document.getElementById('storage-품의서명') as HTMLElement).innerText = '';
  }
}
