import { state, saveHardwareAsset, deleteHardwareAsset } from '../../core/state';
import { HardwareAsset } from '../../core/excelHandler';
import { openModal, closeModals } from './BaseModal';
import { createIcons, History, X, Paperclip } from 'lucide';
import { CORP_LIST, ORG_LIST, HW_TYPE_LIST, LOCATION_DATA } from './SharedData';
import { 
  generateOptionsHTML, 
  setFieldValue, 
  getFieldValue, 
  parseAndSetLocation, 
  bindLocationEvents, 
  getCombinedLocation 
} from './ModalUtils';

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

const PC_MODAL_HTML = `
  <div id="pc-asset-modal" class="modal-overlay hidden">
    <div class="modal-content wide">
      <div class="modal-header">
        <h2 id="pc-modal-title">개인PC 상세 정보</h2>
        <button id="btn-close-pc-modal" class="btn-icon" aria-label="닫기"><i data-lucide="x"></i></button>
      </div>
      <div class="modal-body">
        <div class="modal-body-split">
          <div class="modal-form-area">
            <form id="pc-asset-form" class="grid-form">
              <input type="hidden" id="pc-asset-id" />
              <input type="hidden" id="pc-asset-type" value="개인PC" />

              <div class="form-section-title">기본 정보 (Identity)</div>
              <div class="form-group">
                <label for="pc-법인">구매법인</label>
                <select id="pc-법인" required>${generateOptionsHTML(CORP_LIST)}</select>
              </div>
              <div class="form-group">
                <label for="pc-자산코드">자산번호/코드</label>
                <input type="text" id="pc-자산코드" readonly placeholder="자동 생성됩니다" required />
              </div>
              <div class="form-group">
                <label for="pc-유형">유형</label>
                <select id="pc-유형">${generateOptionsHTML(HW_TYPE_LIST)}</select>
              </div>
              <div class="form-group">
                <label for="pc-상세용도">상세용도</label>
                <select id="pc-상세용도">
                  <option value="개인PC">개인PC</option>
                  <option value="서버">서버</option>
                </select>
              </div>
              <div class="form-group">
                <label for="pc-사용자">사용자</label>
                <input type="text" id="pc-사용자" required />
              </div>
              <div class="form-group">
                <label for="pc-현사용조직">현 사용조직</label>
                <select id="pc-현사용조직">${generateOptionsHTML(ORG_LIST)}</select>
              </div>
              <div class="form-group" id="pc-이전사용조직-group">
                <label for="pc-이전사용조직">이전 사용조직</label>
                <input type="text" id="pc-이전사용조직" readonly />
              </div>

              <div class="form-section-title">시스템 사양 (Specifications)</div>
              <div class="form-group">
                <label for="pc-모델명">모델명</label>
                <input type="text" id="pc-모델명" />
              </div>
              <div class="form-group">
                <label for="pc-OS">운영체제 (OS)</label>
                <input type="text" id="pc-OS" />
              </div>
              <div class="form-group">
                <label for="pc-CPU">CPU 사양</label>
                <input type="text" id="pc-CPU" />
              </div>
              <div class="form-group">
                <label for="pc-RAM">RAM 용량</label>
                <input type="text" id="pc-RAM" />
              </div>
              <div class="form-group">
                <label for="pc-SSD1">Storage 1 (SSD/HDD)</label>
                <input type="text" id="pc-SSD1" />
              </div>
              <div class="form-group">
                <label for="pc-SSD2">Storage 2 (SSD/HDD)</label>
                <input type="text" id="pc-SSD2" />
              </div>

              <div class="form-section-title" id="pc-location-title">관리 및 운영 (Operation)</div>
              <div class="form-group pc-location-field">
                <label for="pc-위치-빌딩">설치위치 (건물)</label>
                <select id="pc-위치-빌딩">${generateOptionsHTML(Object.keys(LOCATION_DATA))}</select>
              </div>
              <div class="form-group pc-location-field">
                <label for="pc-위치-상세">상세 위치</label>
                <select id="pc-위치-상세">
                  <option value="">건물을 먼저 선택하세요</option>
                </select>
              </div>
              <div class="form-group" id="pc-위치-기타-group" style="display:none;">
                <label for="pc-위치-기타">직접 입력 (기타)</label>
                <input type="text" id="pc-위치-기타" />
              </div>
              <div class="form-group">
                <label for="pc-구매일">구매일</label>
                <input type="text" id="pc-구매일" />
              </div>
              <div class="form-group">
                <label for="pc-금액">금액</label>
                <input type="text" id="pc-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\\\B(?=(\\\\d{3})+(?!\d))/g, ',')" />
              </div>
              <div class="form-group">
                <label for="pc-납품업체">납품업체</label>
                <input type="text" id="pc-납품업체" />
              </div>
              <div class="form-group full-width">
                <label>품의서 (파일)</label>
                <div style="display:flex; align-items:center; gap:0.5rem;">
                  <input type="file" id="pc-품의서" />
                  <span id="pc-품의서명" style="font-size:0.75rem; color:var(--text-light)"></span>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-history-area">
            <div class="history-header">
              <h3><i data-lucide="history" style="width:16px; height:16px;"></i> 수정 이력</h3>
            </div>
            <div id="pc-history-list" class="history-timeline">
              <div class="empty-history">이력이 없습니다.</div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button id="btn-delete-pc-asset" class="btn btn-outline btn-danger">삭제</button>
        <div class="footer-actions">
          <button id="btn-revert-pc-edit" class="btn btn-outline hidden">수정 취소</button>
          <button id="btn-cancel-pc-modal" class="btn btn-outline">닫기</button>
          <button id="btn-save-pc-asset" class="btn btn-primary">수정</button>
        </div>
      </div>
    </div>
  </div>
`;

export function openPcModal(asset: HardwareAsset, mode: 'view' | 'add' = 'view') {
  currentAsset = asset;
  const modal = document.getElementById('pc-asset-modal');
  if (!modal) return;
  
  const form = document.getElementById('pc-asset-form') as HTMLFormElement;
  const saveBtn = document.getElementById('btn-save-pc-asset')!;
  const revertBtn = document.getElementById('btn-revert-pc-edit')!;
  
  if (form) form.reset();
  
  if (mode === 'add') {
    isEditMode = true;
    if (form) {
      form.classList.remove('is-view-mode');
      form.classList.add('is-edit-mode');
    }
    saveBtn.textContent = '저장';
    revertBtn.classList.add('hidden'); 
    const prevOrgGroup = document.getElementById('pc-이전사용조직-group');
    if (prevOrgGroup) prevOrgGroup.style.display = 'none';
  } else {
    isEditMode = false; 
    if (form) {
      form.classList.remove('is-edit-mode');
      form.classList.add('is-view-mode');
    }
    saveBtn.textContent = '수정'; 
    revertBtn.classList.add('hidden'); 
    const prevOrgGroup = document.getElementById('pc-이전사용조직-group');
    if (prevOrgGroup) prevOrgGroup.style.display = 'flex';
  }
  
  fillFormData(asset);
  renderHistory(asset.id);
  
  modal.classList.remove('hidden');
  applyPcTypeSpecificUI();
  createIcons({ icons: { X, History, Paperclip } });
}

function applyPcTypeSpecificUI() {
  const type = getFieldValue('pc-유형');
  const detailPurpose = getFieldValue('pc-상세용도');

  const modelGroup = document.getElementById('pc-모델명')?.closest('.form-group') as HTMLElement;
  const osGroup = document.getElementById('pc-OS')?.closest('.form-group') as HTMLElement;
  const cpuGroup = document.getElementById('pc-CPU')?.closest('.form-group') as HTMLElement;
  const ramGroup = document.getElementById('pc-RAM')?.closest('.form-group') as HTMLElement;
  const ssd1Group = document.getElementById('pc-SSD1')?.closest('.form-group') as HTMLElement;
  const ssd2Group = document.getElementById('pc-SSD2')?.closest('.form-group') as HTMLElement;
  const locationFields = document.querySelectorAll('.pc-location-field');
  const etcGroup = document.getElementById('pc-위치-기타-group');

  // 초기화 (숨김)
  [modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'none'; });
  locationFields.forEach(el => (el as HTMLElement).style.display = 'none');
  if (etcGroup) etcGroup.style.display = 'none';

  if (type === '서버') {
    [modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
    locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
  } 
  else if (['스토리지', 'NAS', 'DAS'].includes(type)) {
    [modelGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
    locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
  }
  else if (type === 'PC' || type === '노트북') {
    [modelGroup, osGroup, cpuGroup, ramGroup, ssd1Group, ssd2Group].forEach(g => { if(g) g.style.display = 'flex'; });
    if (detailPurpose === '서버') {
      locationFields.forEach(el => (el as HTMLElement).style.display = 'flex');
    }
  }
  else if (['CPU', 'GPU', '모바일'].includes(type)) {
    if (modelGroup) modelGroup.style.display = 'flex';
  }
  else if (type === 'RAM') {
    if (ramGroup) ramGroup.style.display = 'flex';
  }
  else if (type === 'HDD') {
    if (ssd1Group) ssd1Group.style.display = 'flex';
  }
  else if (type === '태블릿') {
    if (modelGroup) modelGroup.style.display = 'flex';
    if (ssd1Group) ssd1Group.style.display = 'flex';
  }
}

function fillFormData(asset: HardwareAsset) {
  setFieldValue('pc-asset-id', asset.id);
  setFieldValue('pc-법인', asset.법인);
  setFieldValue('pc-자산코드', asset.자산코드);
  setFieldValue('pc-유형', asset.type);
  setFieldValue('pc-사용자', asset.사용자);
  setFieldValue('pc-현사용조직', asset.현사용조직);
  setFieldValue('pc-이전사용조직', asset.이전사용조직);
  setFieldValue('pc-상세용도', (asset as any).상세용도);

  parseAndSetLocation(asset.위치, 'pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타-group', 'pc-위치-기타');

  setFieldValue('pc-모델명', asset.모델명);
  setFieldValue('pc-OS', asset.OS);
  setFieldValue('pc-CPU', asset.CPU);
  setFieldValue('pc-RAM', asset.RAM);
  setFieldValue('pc-SSD1', asset.SSD1);
  setFieldValue('pc-SSD2', asset.SSD2);
  setFieldValue('pc-구매일', asset.구매일);
  setFieldValue('pc-금액', asset.금액);
  setFieldValue('pc-납품업체', asset.납품업체);
  setFieldValue('pc-품의서명', asset.품의서명);
}

export function initPcModal(onSave: () => void, closeModalsCb: () => void) {
  if (!document.getElementById('pc-asset-modal')) {
    document.body.insertAdjacentHTML('beforeend', PC_MODAL_HTML);
  }

  const pcForm = document.getElementById('pc-asset-form') as HTMLFormElement;
  const saveBtn = document.getElementById('btn-save-pc-asset');
  const revertBtn = document.getElementById('btn-revert-pc-edit');
  const deleteBtn = document.getElementById('btn-delete-pc-asset');

  // 유형 및 상세용도 리스너
  const typeSelect = document.getElementById('pc-유형') as HTMLSelectElement;
  const detailPurposeSelect = document.getElementById('pc-상세용도') as HTMLSelectElement;
  
  [typeSelect, detailPurposeSelect].forEach(el => {
    el?.addEventListener('change', () => applyPcTypeSpecificUI());
  });

  bindLocationEvents('pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타-group', 'pc-위치-기타');

  const handleClose = () => { closeModalsCb(); isEditMode = false; };
  document.getElementById('btn-close-pc-modal')?.addEventListener('click', handleClose);
  document.getElementById('btn-cancel-pc-modal')?.addEventListener('click', handleClose);
  revertBtn?.addEventListener('click', () => {
    isEditMode = false;
    pcForm.classList.replace('is-edit-mode', 'is-view-mode');
    if (saveBtn) saveBtn.textContent = '수정';
    revertBtn.classList.add('hidden');
    if (currentAsset) fillFormData(currentAsset);
  });

  saveBtn?.addEventListener('click', () => {
    if (!currentAsset) return;
    if (!isEditMode) {
      isEditMode = true;
      pcForm.classList.replace('is-view-mode', 'is-edit-mode');
      saveBtn.textContent = '저장';
      revertBtn?.classList.remove('hidden');
      return;
    }

    const type = getFieldValue('pc-유형');
    const detailPurpose = getFieldValue('pc-상세용도');

    const updated: any = {
      ...currentAsset,
      법인: getFieldValue('pc-법인'),
      자산코드: getFieldValue('pc-자산코드'),
      현사용조직: getFieldValue('pc-현사용조직'),
      이전사용조직: getFieldValue('pc-이전사용조직'),
      사용자: getFieldValue('pc-사용자'),
      상세용도: detailPurpose,
      위치: getCombinedLocation('pc-위치-빌딩', 'pc-위치-상세', 'pc-위치-기타'),
      모델명: getFieldValue('pc-모델명'),
      OS: getFieldValue('pc-OS'),
      CPU: getFieldValue('pc-CPU'),
      RAM: getFieldValue('pc-RAM'),
      SSD1: getFieldValue('pc-SSD1'),
      SSD2: getFieldValue('pc-SSD2'),
      구매일: getFieldValue('pc-구매일'),
      금액: getFieldValue('pc-금액'),
      납품업체: getFieldValue('pc-납품업체'),
      type: type || 'PC'
    };

    saveHardwareAsset(updated);
    onSave();
    isEditMode = false;
    pcForm.classList.replace('is-edit-mode', 'is-view-mode');
    saveBtn.textContent = '수정';
    revertBtn?.classList.add('hidden');
  });

  deleteBtn?.addEventListener('click', () => {
    if (!currentAsset) return;
    if (confirm('삭제하시겠습니까?')) {
      deleteHardwareAsset(currentAsset.id);
      onSave();
      handleClose();
    }
  });
}

function renderHistory(assetId: string) {
  const historyList = document.getElementById('pc-history-list');
  if (!historyList) return;
  const logs = state.masterData.logs
    .filter(l => l.assetId === assetId)
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  
  if (logs.length === 0) {
    historyList.innerHTML = '<div class="empty-history">이력이 없습니다.</div>';
    return;
  }
  historyList.innerHTML = logs.map(log => `
    <div class="history-item">
      <div class="history-date">${log.date}</div>
      <div class="history-user">수정자: ${log.user}</div>
      <div class="history-details">${log.details.replace(/\n/g, '<br>')}</div>
    </div>
  `).join('');
}
