import { ASSET_SCHEMA, UI_TEXT } from './schema';
import { getActionButtonsHTML } from './utils';
import { generateOptionsHTML } from '../components/Modal/ModalUtils';
import { CORP_LIST } from '../components/Modal/SharedData';

/**
 * ITAM Unified Filter Bar Component
 * 검색 UI를 표준화하고 한 곳에서 관리합니다.
 */

export interface FilterOptions {
  keywordLabel?: string;
  showCorp?: boolean;
  showDept?: boolean;
  showLoc?: boolean;
  showField?: boolean;
  extraHTML?: string;
  onFilterChange: (filters: any) => void;
}

export function renderFilterBar(container: HTMLElement, options: FilterOptions) {
  const { keywordLabel = '통합 검색', showCorp = false, showDept = false, showLoc = false, showField = false, extraHTML = '', onFilterChange } = options;

  container.innerHTML = `
    <div class="search-item flex-1">
      <label>${keywordLabel}</label>
      <input type="text" id="filter-keyword" placeholder="검색어를 입력하세요..." autocomplete="off">
    </div>
    ${showField ? `
    <div class="search-item">
      <label>${ASSET_SCHEMA.SW_FIELD.ui}</label>
      <select id="filter-field">
        <option value="">전체 분야</option>
        <option value="업무공통">업무공통</option>
        <option value="개발S/W">개발S/W</option>
        <option value="디자인">디자인</option>
        <option value="설계S/W">설계S/W</option>
      </select>
    </div>` : ''}
    ${showCorp ? `
    <div class="search-item">
      <label>${ASSET_SCHEMA.PURCHASE_CORP.ui}</label>
      <select id="filter-corp">${generateOptionsHTML(CORP_LIST, '', true)}</select>
    </div>` : ''}
    ${showLoc ? `
    <div class="search-item">
      <label>${ASSET_SCHEMA.LOCATION.ui}</label>
      <select id="filter-loc"><option value="">전체 위치</option></select>
    </div>` : ''}
    ${showDept ? `
    <div class="search-item">
      <label>${ASSET_SCHEMA.CURRENT_DEPT.ui}</label>
      <select id="filter-dept"><option value="">전체 조직</option></select>
    </div>` : ''}
    ${extraHTML}
    <button id="btn-reset-filters" class="btn btn-outline btn-reset">
      <i data-lucide="refresh-ccw"></i> ${UI_TEXT.ACTION.RESET_FILTER}
    </button>
    ${getActionButtonsHTML()}
  `;

  // Bind Events
  const triggerChange = () => {
    const filters = {
      keyword: (container.querySelector('#filter-keyword') as HTMLInputElement)?.value.toLowerCase().trim() || '',
      corp: (container.querySelector('#filter-corp') as HTMLSelectElement)?.value || '',
      dept: (container.querySelector('#filter-dept') as HTMLSelectElement)?.value || '',
      loc: (container.querySelector('#filter-loc') as HTMLSelectElement)?.value || '',
      field: (container.querySelector('#filter-field') as HTMLSelectElement)?.value || ''
    };
    onFilterChange(filters);
  };

  container.querySelector('#filter-keyword')?.addEventListener('input', triggerChange);
  container.querySelector('#filter-corp')?.addEventListener('change', triggerChange);
  container.querySelector('#filter-dept')?.addEventListener('change', triggerChange);
  container.querySelector('#filter-loc')?.addEventListener('change', triggerChange);
  container.querySelector('#filter-field')?.addEventListener('change', triggerChange);

  container.querySelector('#btn-reset-filters')?.addEventListener('click', () => {
    ['filter-keyword', 'filter-corp', 'filter-dept', 'filter-loc', 'filter-field'].forEach(id => {
      const el = container.querySelector(`#${id}`);
      if (el) (el as any).value = '';
    });
    triggerChange();
  });
}

/**
 * 공통 필터링 로직
 */
export function applyCommonFilters(list: any[], filters: any, searchKeys: (keyof typeof ASSET_SCHEMA)[]) {
  return list.filter(item => {
    const matchKeyword = !filters.keyword || searchKeys.some(key => 
      String(item[ASSET_SCHEMA[key].key] || item[ASSET_SCHEMA[key].db] || '').toLowerCase().includes(filters.keyword)
    );
    const matchCorp = !filters.corp || (item[ASSET_SCHEMA.PURCHASE_CORP.key] || item[ASSET_SCHEMA.PURCHASE_CORP.db]) === filters.corp;
    const matchDept = !filters.dept || (item[ASSET_SCHEMA.CURRENT_DEPT.key] || item[ASSET_SCHEMA.CURRENT_DEPT.db]) === filters.dept;
    const matchLoc = !filters.loc || (item[ASSET_SCHEMA.LOCATION.key] || item[ASSET_SCHEMA.LOCATION.db]) === filters.loc;
    const matchField = !filters.field || (item[ASSET_SCHEMA.SW_FIELD.key] || item[ASSET_SCHEMA.SW_FIELD.db]) === filters.field;

    return matchKeyword && matchCorp && matchDept && matchLoc && matchField;
  });
}
