import { state, saveAsset, deleteAsset } from '../../core/state';
import { closeModals, openModal } from './BaseModal';
import { CORP_LIST } from './SharedData';
import { generateOptionsHTML, setEditLock } from './ModalUtils';
import { createIcons, X, Save, Database, CalendarClock, Edit2 } from 'lucide';
import { formatExcelDate } from '../../core/excelHandler';
import { UI_TEXT } from '../../core/schema';

let currentItem: any = null;

const DOMAIN_MODAL_HTML = `
... (rest of DOMAIN_MODAL_HTML remains same) ...
`;

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());
  
  const saveBtn = document.getElementById('btn-save-domain');
  const revertBtn = document.getElementById('btn-revert-domain');
  const deleteBtn = document.getElementById('btn-delete-domain');
  const headerEditBtn = document.getElementById('btn-edit-domain-header');

  saveBtn?.addEventListener('click', () => {
    if (!currentItem) return;
    if (saveBtn.textContent?.includes('수정')) {
      setEditLock('domain-asset-form', 'edit', { saveBtnId: 'btn-save-domain', revertBtnId: 'btn-revert-domain' });
      return;
    }
    saveDomain();
  });

  headerEditBtn?.addEventListener('click', () => {
    setEditLock('domain-asset-form', 'edit', { saveBtnId: 'btn-save-domain', revertBtnId: 'btn-revert-domain' });
  });

  revertBtn?.addEventListener('click', () => {
    setEditLock('domain-asset-form', 'view', { saveBtnId: 'btn-save-domain', revertBtnId: 'btn-revert-domain' });
    if (currentItem) openDomainModal(currentItem);
  });

  deleteBtn?.addEventListener('click', async () => {
    if (currentItem && confirm(UI_TEXT.MESSAGES.CONFIRM_DELETE)) {
      const success = await deleteAsset('domain', currentItem.id);
      if (success) {
          alert('성공적으로 삭제되었습니다.');
          closeModals();
          window.dispatchEvent(new CustomEvent('refresh-view'));
      }
    }
  });
}

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

  setEditLock('domain-asset-form', mode, { saveBtnId: 'btn-save-domain', revertBtnId: 'btn-revert-domain' });

  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', formatExcelDate(item?.start_date));
  setVal('domain-expiry-date', formatExcelDate(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 || '');

  const deleteBtn = document.getElementById('btn-delete-domain');
  if (deleteBtn) deleteBtn.style.display = isEdit ? 'block' : 'none';

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

  const success = await saveAsset('domain', newDomain);
  if (success) {
      alert(UI_TEXT.MESSAGES.SAVE_SUCCESS);
      closeModals();
      window.dispatchEvent(new CustomEvent('refresh-view'));
  }
}
