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

/**
 * 소프트웨어 모달 초기화 및 로직 제어
 */
export function initSWModal(renderContent: () => void, closeModals: () => void) {
  const swForm = document.getElementById('sw-asset-form') as HTMLFormElement;
  const btnSaveSw = document.getElementById('btn-save-sw-asset') as HTMLButtonElement;
  const btnDeleteSw = document.getElementById('btn-delete-sw-asset') as HTMLButtonElement;

  // 저장 버튼 이벤트
  btnSaveSw?.addEventListener('click', (e) => {
    e.preventDefault();
    if (!swForm.checkValidity()) { swForm.reportValidity(); return; }
    
    const id = (document.getElementById('sw-asset-id') as HTMLInputElement).value;
    const newAsset: SoftwareAsset = {
      id: id || Math.random().toString(36).substring(2, 9),
      type: (document.getElementById('sw-asset-type') as HTMLInputElement).value,
      분야: (document.getElementById('sw-분야') as HTMLSelectElement).value,
      법인: (document.getElementById('sw-법인') as HTMLSelectElement).value,
      부서: (document.getElementById('sw-부서') as HTMLInputElement).value,
      제품명: (document.getElementById('sw-제품명') as HTMLInputElement).value,
      구매일: (document.getElementById('sw-구매일') as HTMLInputElement).value,
      구독일: (document.getElementById('sw-구독일') as HTMLInputElement).value,
      유지보수여부: (document.getElementById('sw-유지보수여부') as HTMLInputElement).checked,
      금액: (document.getElementById('sw-금액') as HTMLInputElement).value,
      수량: parseInt((document.getElementById('sw-수량') as HTMLInputElement).value || '1', 10),
      계정명: (document.getElementById('sw-계정명') as HTMLInputElement).value,
      납품업체: (document.getElementById('sw-납품업체') as HTMLInputElement).value,
      비고: (document.getElementById('sw-비고') as HTMLInputElement).value,
    };

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

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

/**
 * 소프트웨어 상세 모달 열기
 * @param asset 수정 시 자산 데이터, 신규 시 undefined
 */
export function openSwModal(asset?: SoftwareAsset) {
  const swModal = document.getElementById('sw-asset-modal') as HTMLDivElement;
  const swForm = document.getElementById('sw-asset-form') as HTMLFormElement;
  const deleteBtn = document.getElementById('btn-delete-sw-asset')!;
  
  openModal('sw-asset-modal');
  swForm.reset();
  
  const subGroup = document.getElementById('sw-구독일-group')!;
  const permGroup = document.getElementById('sw-유지보수-group')!;
  if (state.activeSubTab === '구독SW') {
    subGroup.style.display = 'block';
    permGroup.style.display = 'none';
  } else {
    subGroup.style.display = 'none';
    permGroup.style.display = 'block';
  }

  if (asset) {
    document.getElementById('sw-modal-title')!.textContent = `${state.activeSubTab} 상세 정보 수정`;
    deleteBtn.style.display = 'block';
    
    (document.getElementById('sw-asset-id') as HTMLInputElement).value = asset.id;
    (document.getElementById('sw-asset-type') as HTMLInputElement).value = asset.type;
    (document.getElementById('sw-분야') as HTMLSelectElement).value = asset.분야 || '업무공통';
    (document.getElementById('sw-법인') as HTMLSelectElement).value = asset.법인;
    (document.getElementById('sw-부서') as HTMLInputElement).value = asset.부서 || '';
    (document.getElementById('sw-제품명') as HTMLInputElement).value = asset.제품명;
    (document.getElementById('sw-구매일') as HTMLInputElement).value = asset.구매일 || '';
    (document.getElementById('sw-구독일') as HTMLInputElement).value = asset.구독일 || '';
    (document.getElementById('sw-유지보수여부') as HTMLInputElement).checked = !!asset.유지보수여부;
    (document.getElementById('sw-금액') as HTMLInputElement).value = asset.금액 ? Number(asset.금액.replace(/,/g, '')).toLocaleString() : '';
    (document.getElementById('sw-수량') as HTMLInputElement).value = String(asset.수량);
    (document.getElementById('sw-계정명') as HTMLInputElement).value = asset.계정명 || '';
    (document.getElementById('sw-납품업체') as HTMLInputElement).value = asset.납품업체 || '';
    (document.getElementById('sw-비고') as HTMLInputElement).value = asset.비고 || '';
  } else {
    document.getElementById('sw-modal-title')!.textContent = `새 ${state.activeSubTab} 자산 추가`;
    deleteBtn.style.display = 'none';
    (document.getElementById('sw-asset-id') as HTMLInputElement).value = '';
    (document.getElementById('sw-asset-type') as HTMLInputElement).value = state.activeSubTab;
    (document.getElementById('sw-분야') as HTMLSelectElement).value = '업무공통';
    (document.getElementById('sw-법인') as HTMLSelectElement).value = '한맥';
    (document.getElementById('sw-부서') as HTMLInputElement).value = '';
  }
}
