import { state, saveSoftwareAsset, deleteSoftwareAsset } from '../../core/state';
import { SoftwareAsset } from '../../core/excelHandler';
import { openModal, closeModals } from './BaseModal';
import { createIcons, History, Plus, X, Save, Edit2, RotateCcw, UserPlus } from 'lucide';
import { CORP_LIST, ORG_LIST } from './SharedData';
import { 
  generateOptionsHTML, 
  setFieldValue, 
  getFieldValue, 
  setEditLock,
  createModalFrameHTML,
  autoFillForm,
  autoExtractForm
} from './ModalUtils';
import { openSwUserModal } from './SWUserModal';

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

const SW_FIELD_MAP: Record<string, string> = {
  '유형': 'type',
  '법인': '법인',
  '부서': '부서',
  '제품명': '소프트웨어명',
  '구매일': '구매일',
  '만료일': '만료일',
  '수량': '수량',
  '금액': '금액',
  '비고': '비고',
  '자산번호': '자산번호'
};

const SW_FORM_HTML = `
  <div class="form-section-title">소프트웨어 기본 정보</div>
  <div class="form-group">
    <label for="sw-유형">라이선스 유형</label>
    <select id="sw-유형">
      <option value="구독SW">구독 라이선스</option>
      <option value="영구SW">영구 라이선스</option>
    </select>
  </div>
  <div class="form-group">
    <label for="sw-법인">구매법인</label>
    <select id="sw-법인">${generateOptionsHTML(CORP_LIST)}</select>
  </div>
  <div class="form-group">
    <label for="sw-부서">관리부서</label>
    <select id="sw-부서">${generateOptionsHTML(ORG_LIST)}</select>
  </div>
  <div class="form-group">
    <label for="sw-제품명">제품명 (S/W명)</label>
    <input type="text" id="sw-제품명" required />
  </div>
  <div class="form-group">
    <label for="sw-자산번호">자산번호</label>
    <input type="text" id="sw-자산번호" placeholder="관리번호 입력" />
  </div>
  <div class="form-group">
    <label for="sw-수량">총 라이선스 수량</label>
    <input type="number" id="sw-수량" value="1" />
  </div>
  
  <div class="form-section-title">계약 및 금액</div>
  <div class="form-group">
    <label for="sw-구매일">구매일 (계약시작)</label>
    <input type="date" id="sw-구매일" />
  </div>
  <div class="form-group sw-sub-only">
    <label for="sw-만료일">만료일 (계약종료)</label>
    <input type="date" id="sw-만료일" />
  </div>
  <div class="form-group">
    <label for="sw-금액">금액 (단가/총액)</label>
    <input type="text" id="sw-금액" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\d))/g, ',')" />
  </div>
  <div class="form-group full-width">
    <label for="sw-비고">비고 (특이사항)</label>
    <textarea id="sw-비고" rows="2"></textarea>
  </div>

  <div class="form-section-title">
    사용자 할당 현황 
    <button type="button" id="btn-add-sw-user" class="btn btn-outline btn-xs" style="margin-left: 0.5rem;">
      <i data-lucide="user-plus" style="width:12px; height:12px;"></i> 할당 추가
    </button>
  </div>
  <div class="full-width">
    <div id="sw-user-list-container" class="mini-table-container">
      <table class="itam-table mini">
        <thead>
          <tr>
            <th>부서</th>
            <th>이름</th>
            <th>사번</th>
            <th>사용기간</th>
            <th>삭제</th>
          </tr>
        </thead>
        <tbody id="sw-user-list-body"></tbody>
      </table>
    </div>
  </div>
`;

function renderSwUsers(swId: string) {
  const body = document.getElementById('sw-user-list-body');
  if (!body) return;
  const users = (state.masterData.swUsers || []).filter(u => u.swId === swId || u.sw_id === swId);
  
  if (users.length === 0) {
    body.innerHTML = '<tr><td colspan="5" class="empty-row">할당된 사용자가 없습니다.</td></tr>';
    return;
  }

  body.innerHTML = users.map(u => `
    <tr>
      <td>${u.부서 || '-'}</td>
      <td>${u.이름 || '-'}</td>
      <td>${u.사번 || '-'}</td>
      <td><small>${u.사용기간 || '-'}</small></td>
      <td><button class="btn-icon text-danger btn-delete-user" data-id="${u.id}"><i data-lucide="x" style="width:14px; height:14px;"></i></button></td>
    </tr>
  `).join('');
  
  createIcons({ icons: { X } });

  body.querySelectorAll('.btn-delete-user').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.getAttribute('data-id');
      state.masterData.swUsers = state.masterData.swUsers.filter(u => u.id !== id);
      renderSwUsers(swId);
    });
  });
}

export function openSwModal(asset: SoftwareAsset) {
  currentAsset = asset;
  const modal = document.getElementById('sw-asset-modal')!;
  
  setEditLock('sw-asset-form', 'view', {
    saveBtnId: 'btn-save-sw-asset',
    revertBtnId: 'btn-revert-sw-edit'
  });

  isEditMode = false;
  autoFillForm('sw', asset, SW_FIELD_MAP);
  
  const subOnly = document.querySelectorAll('.sw-sub-only');
  subOnly.forEach(el => (el as HTMLElement).style.display = asset.type === '구독SW' ? 'block' : 'none');
  
  renderSwUsers(asset.id);
  
  modal.classList.remove('hidden');
  createIcons({ icons: { X, Save, Edit2, RotateCcw, UserPlus } });
}

export function initSwModal(onSave: () => void, closeModalsCb: () => void) {
  if (!document.getElementById('sw-asset-modal')) {
    const html = createModalFrameHTML('sw', '소프트웨어 상세 정보', SW_FORM_HTML, {
      historyTitle: '라이선스 변경 이력',
      addLogBtnId: 'btn-add-sw-log'
    });
    document.body.insertAdjacentHTML('beforeend', html);
  }

  const saveBtn = document.getElementById('btn-save-sw-asset')!;
  const revertBtn = document.getElementById('btn-revert-sw-edit')!;
  const deleteBtn = document.getElementById('btn-delete-sw-asset')!;
  const typeSelect = document.getElementById('sw-유형') as HTMLSelectElement;

  typeSelect?.addEventListener('change', () => {
    const subOnly = document.querySelectorAll('.sw-sub-only');
    subOnly.forEach(el => (el as HTMLElement).style.display = typeSelect.value === '구독SW' ? 'block' : 'none');
  });

  const handleClose = () => { closeModalsCb(); isEditMode = false; };
  document.getElementById('btn-close-sw-modal')?.addEventListener('click', handleClose);
  document.getElementById('btn-cancel-sw-modal')?.addEventListener('click', handleClose);

  saveBtn.addEventListener('click', () => {
    if (!currentAsset) return;
    if (!isEditMode) {
      setEditLock('sw-asset-form', 'edit', { saveBtnId: 'btn-save-sw-asset', revertBtnId: 'btn-revert-sw-edit' });
      isEditMode = true;
      return;
    }

    const extracted = autoExtractForm('sw', SW_FIELD_MAP);
    const updated = { ...currentAsset, ...extracted };

    saveSoftwareAsset(updated);
    onSave();
    isEditMode = false;
    setEditLock('sw-asset-form', 'view', { saveBtnId: 'btn-save-sw-asset', revertBtnId: 'btn-revert-sw-edit' });
  });

  deleteBtn.addEventListener('click', () => {
    if (currentAsset && confirm('이 소프트웨어 자산을 삭제하시겠습니까?')) {
      deleteSoftwareAsset(currentAsset.id, currentAsset.type);
      onSave();
      handleClose();
    }
  });

  document.getElementById('btn-add-sw-user')?.addEventListener('click', () => {
    if (!currentAsset) return;
    openSwUserModal(currentAsset.id, () => renderSwUsers(currentAsset!.id));
  });
}
