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

const STORAGE_MODAL_HTML = `
  <div id="storage-asset-modal" class="modal-overlay hidden">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="storage-modal-title">스토리지 상세 정보</h2>
        <button id="btn-close-storage-modal" class="btn-icon" aria-label="닫기"><i data-lucide="x"></i></button>
      </div>
      <div class="modal-body">
        <form id="storage-asset-form" class="grid-form">
          <input type="hidden" id="storage-asset-id" />
          <input type="hidden" id="storage-asset-type" value="스토리지" />
          <div class="form-group"><label for="storage-법인">법인</label><input type="text" id="storage-법인" required /></div>
          <div class="form-group"><label for="storage-유형">유형</label><input type="text" id="storage-유형" required /></div>
          <div class="form-group"><label for="storage-자산코드">자산코드</label><input type="text" id="storage-자산코드" required /></div>
          <div class="form-group"><label for="storage-명칭">명칭</label><input type="text" id="storage-명칭" required /></div>
          <div class="form-group"><label for="storage-위치">위치</label><input type="text" id="storage-위치" /></div>
          <div class="form-group"><label for="storage-모델명">모델명</label><input type="text" id="storage-모델명" /></div>
          <div class="form-group"><label for="storage-용량">용량</label><input type="text" id="storage-용량" /></div>
          <div class="form-group"><label for="storage-담당자_정">담당자(정)</label><input type="text" id="storage-담당자_정" /></div>
          <div class="form-group"><label for="storage-IP주소">IP주소</label><input type="text" id="storage-IP주소" /></div>
          <div class="form-group"><label for="storage-구매일">구매일</label><input type="text" id="storage-구매일" /></div>
          <div class="form-group"><label for="storage-금액">금액</label><input type="text" id="storage-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\d))/g, ',')" /></div>
        </form>
      </div>
      <div class="modal-footer">
        <button id="btn-delete-storage-asset" class="btn btn-outline btn-danger">삭제</button>
        <div class="footer-actions">
          <button id="btn-revert-storage-edit" class="btn btn-outline hidden">수정 취소</button>
          <button id="btn-close-storage-footer" class="btn btn-outline">닫기</button>
          <button id="btn-save-storage-asset" class="btn btn-primary">수정</button>
        </div>
      </div>
    </div>
  </div>
`;

export function initStorageModal(renderContent: () => void, closeModals: () => void) {
  if (!document.getElementById('storage-asset-modal')) {
    document.body.insertAdjacentHTML('beforeend', STORAGE_MODAL_HTML);
  }

  const storageForm = document.getElementById('storage-asset-form') as HTMLFormElement;
  const btnRevertEdit = document.getElementById('btn-revert-storage-edit') as HTMLButtonElement;
  const btnSaveStorage = document.getElementById('btn-save-storage-asset') as HTMLButtonElement;
  const btnDeleteStorage = document.getElementById('btn-delete-storage-asset') as HTMLButtonElement;
  const btnCloseHeader = document.getElementById('btn-close-storage-modal') as HTMLButtonElement;
  const btnCloseFooter = document.getElementById('btn-close-storage-footer') as HTMLButtonElement;

  let isEditMode = false;
  let currentAsset: HardwareAsset | null = null;

  const setEditMode = (edit: boolean) => {
    isEditMode = edit;
    if (edit) {
      storageForm.classList.add('is-edit-mode');
      storageForm.classList.remove('is-view-mode');
      btnSaveStorage.textContent = '저장';
      btnRevertEdit.classList.remove('hidden');
      btnCloseFooter.classList.add('hidden');
    } else {
      storageForm.classList.add('is-view-mode');
      storageForm.classList.remove('is-edit-mode');
      btnSaveStorage.textContent = '수정';
      btnRevertEdit.classList.add('hidden');
      btnCloseFooter.classList.remove('hidden');
      if (currentAsset) fillFormData(currentAsset);
    }
  };

  function fillFormData(asset: HardwareAsset) {
    (document.getElementById('storage-asset-id') as HTMLInputElement).value = asset.id;
    (document.getElementById('storage-법인') as HTMLInputElement).value = asset.법인;
    (document.getElementById('storage-유형') as HTMLInputElement).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-IP주소') as HTMLInputElement).value = asset.IP주소 || '';
    (document.getElementById('storage-구매일') as HTMLInputElement).value = asset.구매일 || '';
    (document.getElementById('storage-금액') as HTMLInputElement).value = asset.금액 || '';
  }

  btnRevertEdit?.addEventListener('click', () => setEditMode(false));
  btnCloseHeader?.addEventListener('click', closeModals);
  btnCloseFooter?.addEventListener('click', closeModals);

  btnSaveStorage?.addEventListener('click', (e) => {
    e.preventDefault();
    if (!isEditMode) {
      setEditMode(true);
      return;
    }
    
    if (!storageForm.checkValidity()) { storageForm.reportValidity(); return; }
    
    const id = (document.getElementById('storage-asset-id') as HTMLInputElement).value;
    const newAsset: HardwareAsset = {
      id: id || Math.random().toString(36).substring(2, 9),
      type: '스토리지',
      법인: (document.getElementById('storage-법인') as HTMLInputElement).value,
      storage유형: (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,
      IP주소: (document.getElementById('storage-IP주소') as HTMLInputElement).value,
      구매일: (document.getElementById('storage-구매일') as HTMLInputElement).value,
      금액: (document.getElementById('storage-금액') as HTMLInputElement).value,
      관리자: '', MACaddress: '', HW사양: '', OS: '', 납품업체: '', 품의서명: ''
    };

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

export function openStorageModal(asset?: HardwareAsset) {
  currentAsset = asset || null;
  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';
    fillFormData(asset);
    setEditMode(false);
  } else {
    document.getElementById('storage-modal-title')!.textContent = '신규 스토리지 자산 추가';
    deleteBtn.style.display = 'none';
    (document.getElementById('storage-asset-id') as HTMLInputElement).value = '';
    setEditMode(true);
  }
}
