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

/**
 * 개인PC 모달 초기화 및 로직 제어
 */
export function initPCModal(renderContent: () => void, closeModals: () => void) {
  const pcModal = document.getElementById('pc-asset-modal') as HTMLDivElement;
  const pcForm = document.getElementById('pc-asset-form') as HTMLFormElement;
  const btnSavePc = document.getElementById('btn-save-pc-asset') as HTMLButtonElement;
  const btnDeletePc = document.getElementById('btn-delete-pc-asset') as HTMLButtonElement;

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

    const newAsset: HardwareAsset = {
      id: id || Math.random().toString(36).substring(2, 9),
      type: '개인PC',
      법인: (document.getElementById('pc-법인') as HTMLSelectElement).value,
      자산코드: (document.getElementById('pc-자산코드') as HTMLInputElement).value,
      명칭: '',
      위치: (document.getElementById('pc-위치') as HTMLInputElement).value,
      관리자: '',
      IP주소: '',
      MACaddress: '',
      HW사양: '',
      OS: '',
      사용자: (document.getElementById('pc-사용자') as HTMLInputElement).value,
      CPU: (document.getElementById('pc-CPU') as HTMLInputElement).value,
      GPU: (document.getElementById('pc-GPU') as HTMLInputElement).value,
      RAM: (document.getElementById('pc-RAM') as HTMLInputElement).value,
      SSD1: (document.getElementById('pc-SSD1') as HTMLInputElement).value,
      SSD2: (document.getElementById('pc-SSD2') as HTMLInputElement).value,
      HDD1: (document.getElementById('pc-HDD1') as HTMLInputElement).value,
      HDD2: (document.getElementById('pc-HDD2') as HTMLInputElement).value,
      구매일: (document.getElementById('pc-구매일') as HTMLInputElement).value,
      금액: (document.getElementById('pc-금액') as HTMLInputElement).value,
      납품업체: (document.getElementById('pc-납품업체') 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();
  });

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

/**
 * 개인PC 상세 모달 열기
 * @param asset 수정 시 자산 데이터, 신규 시 undefined
 */
export function openPcModal(asset?: HardwareAsset) {
  const pcModal = document.getElementById('pc-asset-modal') as HTMLDivElement;
  const pcForm = document.getElementById('pc-asset-form') as HTMLFormElement;
  const deleteBtn = document.getElementById('btn-delete-pc-asset')!;
  
  openModal('pc-asset-modal');
  pcForm.reset();
  
  if (asset) {
    document.getElementById('pc-modal-title')!.textContent = '개인PC 상세 정보 수정';
    deleteBtn.style.display = 'block';
    
    (document.getElementById('pc-asset-id') as HTMLInputElement).value = asset.id;
    (document.getElementById('pc-법인') as HTMLSelectElement).value = asset.법인;
    (document.getElementById('pc-자산코드') as HTMLInputElement).value = asset.자산코드;
    (document.getElementById('pc-사용자') as HTMLInputElement).value = asset.사용자 || '';
    (document.getElementById('pc-위치') as HTMLInputElement).value = asset.위치 || '';
    (document.getElementById('pc-CPU') as HTMLInputElement).value = asset.CPU || '';
    (document.getElementById('pc-GPU') as HTMLInputElement).value = asset.GPU || '';
    (document.getElementById('pc-RAM') as HTMLInputElement).value = asset.RAM || '';
    (document.getElementById('pc-SSD1') as HTMLInputElement).value = asset.SSD1 || '';
    (document.getElementById('pc-SSD2') as HTMLInputElement).value = asset.SSD2 || '';
    (document.getElementById('pc-HDD1') as HTMLInputElement).value = asset.HDD1 || '';
    (document.getElementById('pc-HDD2') as HTMLInputElement).value = asset.HDD2 || '';
    (document.getElementById('pc-구매일') as HTMLInputElement).value = asset.구매일 || '';
    (document.getElementById('pc-금액') as HTMLInputElement).value = asset.금액 ? Number(asset.금액.replace(/,/g, '')).toLocaleString() : '';
    (document.getElementById('pc-납품업체') as HTMLInputElement).value = asset.납품업체 || '';
    (document.getElementById('pc-품의서명') as HTMLElement).innerText = asset.품의서명 ? `📎${asset.품의서명}` : '';
  } else {
    document.getElementById('pc-modal-title')!.textContent = '새 개인PC 자산 추가';
    deleteBtn.style.display = 'none';
    (document.getElementById('pc-asset-id') as HTMLInputElement).value = '';
    (document.getElementById('pc-법인') as HTMLSelectElement).value = '한맥';
    (document.getElementById('pc-품의서명') as HTMLElement).innerText = '';
  }
}
