import { state } from '../../core/state';
import { closeModals, openModal } from './BaseModal';
import { CORP_LIST } from './SharedData';
import { generateOptionsHTML } from './ModalUtils';
import { createIcons, X, Save, Database, CalendarClock, Edit2 } from 'lucide';

let currentItem: any = null;

const DOMAIN_MODAL_HTML = `
  <div id="domain-asset-modal" class="modal-overlay hidden">
    <div class="modal-content wide">
      <div class="modal-header">
        <h2 id="domain-modal-title">도메인 정보</h2>
        <div style="display:flex; gap:0.5rem; align-items:center;">
          <button id="btn-close-domain-modal" class="btn-icon"><i data-lucide="x"></i></button>
        </div>
      </div>
      <div class="modal-body">
        <div class="modal-form-area">
          <form id="domain-asset-form" class="grid-form">
            
            <!-- Group 1: 기본 정보 (Service Identity) -->
            <div class="form-section-title" style="display:flex; align-items:center; gap:0.5rem;">
              <i data-lucide="database" style="width:16px; height:16px; color:var(--primary-color);"></i>
              기본 정보 (Identity)
            </div>
            
            <div class="form-group">
              <label class="required">유형</label>
              <select id="domain-type" required>
                <option value="호스팅">호스팅</option>
                <option value="SSL">SSL</option>
                <option value="도메인">도메인</option>
                <option value="네임서버">네임서버</option>
              </select>
            </div>
            
            <div class="form-group">
              <label class="required">법인</label>
              <select id="domain-corp" required>
                ${generateOptionsHTML(CORP_LIST)}
              </select>
            </div>

            <div class="form-group">
              <label class="required">서비스명</label>
              <input type="text" id="domain-service-name" placeholder="예: 그룹웨어, 홈페이지" required>
            </div>
            
            <div class="form-group">
              <label class="required">관리도메인</label>
              <input type="text" id="domain-name" placeholder="예: hmac.kr" required>
            </div>

            <!-- Group 2: 계약 및 담당 정보 (Contract & Manager) -->
            <div class="form-section-title" style="display:flex; align-items:center; gap:0.5rem; margin-top:1.5rem;">
              <i data-lucide="calendar-clock" style="width:16px; height:16px; color:var(--primary-color);"></i>
              계약 및 담당 정보
            </div>

            <div class="form-group">
              <label>계약 시작일</label>
              <input type="date" id="domain-start-date">
            </div>
            
            <div class="form-group">
              <label>계약 만료일</label>
              <input type="date" id="domain-expiry-date">
            </div>

            <div class="form-group">
              <label>도입 금액</label>
              <input type="text" id="domain-price" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')" placeholder="0">
            </div>
            
            <div class="form-group">
              <label>담당자</label>
              <input type="text" id="domain-manager-main">
            </div>
            
            <div class="form-group">
              <label>담당자(부)</label>
              <input type="text" id="domain-manager-sub">
            </div>

            <!-- Group 3: 기타 (Additional) -->
            <div class="form-section-title" style="display:flex; align-items:center; gap:0.5rem; margin-top:1.5rem;">
              <i data-lucide="edit-2" style="width:16px; height:16px; color:var(--primary-color);"></i>
              기타 사항
            </div>
            
            <div class="form-group full-width">
              <label>비고</label>
              <textarea id="domain-remarks" rows="3" style="width:100%; border:1px solid var(--border-color); border-radius:4px; padding:0.625rem;"></textarea>
            </div>
          </form>
        </div>
      </div>
      <div class="modal-footer">
        <button id="btn-cancel-domain" class="btn btn-outline">취소</button>
        <button id="btn-save-domain" class="btn btn-primary"><i data-lucide="save"></i> 저장하기</button>
      </div>
    </div>
  </div>
`;

export function initDomainModal() {
  if (!document.getElementById('domain-asset-modal')) {
    document.body.insertAdjacentHTML('beforeend', DOMAIN_MODAL_HTML);
  }

  const modal = document.getElementById('domain-asset-modal')!;
  document.getElementById('btn-close-domain-modal')?.addEventListener('click', () => closeModals());
  document.getElementById('btn-cancel-domain')?.addEventListener('click', () => closeModals());
  document.getElementById('btn-save-domain')?.addEventListener('click', () => saveDomain());
}

export function openDomainModal(item: any = null) {
  currentItem = item;
  const isEdit = !!item;
  
  const titleEl = document.getElementById('domain-modal-title');
  if (titleEl) titleEl.textContent = isEdit ? '도메인 정보 수정' : '신규 도메인 등록';

  const setVal = (id: string, val: any) => {
    const el = document.getElementById(id) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
    if (el) el.value = val || '';
  };

  setVal('domain-type', item?.type || '호스팅');
  setVal('domain-corp', item?.corp || '');
  setVal('domain-service-name', item?.service_name || '');
  setVal('domain-name', item?.domain_name || '');
  setVal('domain-start-date', item?.start_date || '');
  setVal('domain-expiry-date', item?.expiry_date || '');
  setVal('domain-price', item?.price || '');
  setVal('domain-manager-main', item?.manager_main || '');
  setVal('domain-manager-sub', item?.manager_sub || '');
  setVal('domain-remarks', item?.remarks || '');

  openModal('domain-asset-modal');
  createIcons({ icons: { X, Save, Database, CalendarClock, Edit2 } });
}

async function saveDomain() {
  const getVal = (id: string) => (document.getElementById(id) as HTMLInputElement)?.value || '';

  const newDomain = {
    id: currentItem ? currentItem.id : `DOM-${Date.now()}`,
    type: getVal('domain-type'),
    corp: getVal('domain-corp'),
    service_name: getVal('domain-service-name'),
    domain_name: getVal('domain-name'),
    start_date: getVal('domain-start-date'),
    expiry_date: getVal('domain-expiry-date'),
    price: getVal('domain-price'),
    manager_main: getVal('domain-manager-main'),
    manager_sub: getVal('domain-manager-sub'),
    remarks: getVal('domain-remarks')
  };

  if (!newDomain.service_name || !newDomain.domain_name) {
    alert('서비스명과 관리도메인은 필수 입력 사항입니다.');
    return;
  }

  if (currentItem) {
    const idx = state.masterData.domain.findIndex(d => d.id === currentItem.id);
    if (idx > -1) state.masterData.domain[idx] = newDomain;
  } else {
    state.masterData.domain.push(newDomain);
  }

  try {
    const response = await fetch(`http://${location.hostname}:3000/api/ops/domain/batch`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(state.masterData.domain)
    });
    
    if (response.ok) {
      // alert('성공적으로 저장되었습니다.');
      closeModals();
      window.dispatchEvent(new CustomEvent('refresh-view'));
    } else {
      throw new Error('DB 저장 실패');
    }
  } catch (err) {
    console.error(err);
    alert('저장 중 오류가 발생했습니다.');
  }
}
