/*
 * SCR-44 통합검색 (search). 참조: UIWS SearchResultsPage.
 * 대형 검색창 + 결과 타입 탭 + 좌측 파셋. 백엔드: /api/work/search (WORKLOG|NOTICE|MEETING|REPORT|OPINION).
 * ★ 갭: AI 자연어 검색 엔드포인트·크로스모듈(행사/부스/업체) 검색 부재 → AI 토글은 UI 표기(비활성 안내). 07_work_api_gaps.md 기록.
 */
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { searchApi } from '../../api/endpoints';
import type { SearchResultItem } from '../../api/types';
import { AiLabel } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import {
  IconCalendar,
  IconDocument,
  IconSearch,
  IconSpark,
  IconTag,
} from '../../components/ui/icons';
import { fmtDateTime, errMessage } from './workShared';
import './work.css';

const TYPE_META: Record<string, { label: string; Icon: typeof IconDocument }> = {
  WORKLOG: { label: '업무일지', Icon: IconDocument },
  NOTICE: { label: '공지', Icon: IconDocument },
  MEETING: { label: '회의록', Icon: IconCalendar },
  REPORT: { label: '업무보고', Icon: IconDocument },
  OPINION: { label: '의견', Icon: IconDocument },
  EVENT: { label: '행사', Icon: IconCalendar },
  COMPANY: { label: '업체', Icon: IconDocument },
  AUCTION: { label: '옥션', Icon: IconDocument },
  BOOTH: { label: '부스', Icon: IconDocument },
  LEAD: { label: '리드', Icon: IconDocument },
  CMS: { label: '콘텐츠', Icon: IconDocument },
};

/** type(+id)별 이동 경로 파생(백엔드 route 와 정합). null=이동 불가. */
function routeFor(type: string, id: string): string | null {
  switch (type) {
    case 'WORKLOG':
      return '/work/worklog';
    case 'NOTICE':
      return '/work/notice';
    case 'MEETING':
      return '/work/meeting';
    case 'REPORT':
      return '/work/report';
    case 'OPINION':
      return '/work/opinion';
    case 'EVENT':
      return '/schedule';
    case 'COMPANY':
      return '/admin/companies';
    case 'AUCTION':
      return id ? `/auctions/${id}` : '/auctions';
    case 'BOOTH':
      return '/booth-sales';
    case 'LEAD':
      return '/leads';
    case 'CMS':
      return '/cms';
    default:
      return null;
  }
}

export function SearchPage() {
  const navigate = useNavigate();
  const [input, setInput] = useState('');
  const [query, setQuery] = useState('');
  const [aiMode, setAiMode] = useState(false);
  const [tab, setTab] = useState<string>('ALL');

  const searchQ = useQuery({
    queryKey: ['search', query],
    queryFn: () => searchApi.search(query, 50),
    enabled: query.trim().length > 0,
  });

  const results = searchQ.data ?? [];
  const counts = useMemo(() => {
    const c: Record<string, number> = { ALL: results.length };
    for (const r of results) c[r.type] = (c[r.type] ?? 0) + 1;
    return c;
  }, [results]);

  const tabs = useMemo(() => {
    const present = Array.from(new Set(results.map((r) => r.type)));
    return ['ALL', ...present];
  }, [results]);

  const filtered = tab === 'ALL' ? results : results.filter((r) => r.type === tab);

  function highlight(text: string): React.ReactNode {
    if (!query.trim()) return text;
    const idx = text.toLowerCase().indexOf(query.toLowerCase());
    if (idx < 0) return text;
    return (
      <>
        {text.slice(0, idx)}
        <mark style={{ background: '#FEF0C7', padding: '0 1px' }}>
          {text.slice(idx, idx + query.length)}
        </mark>
        {text.slice(idx + query.length)}
      </>
    );
  }

  return (
    <div className="kx-page">
      <header className="kx-work__head">
        <div>
          <h1 className="kx-work__title">통합검색</h1>
          <p className="kx-work__subtitle">업무일지·공지·회의록·보고·의견 + 행사·업체·옥션·부스·리드·콘텐츠 크로스 검색</p>
        </div>
      </header>

      <div className="kx-search__hero">
        <div className="kx-search__box">
          <IconSearch size={22} />
          <input
            placeholder="검색어를 입력하세요"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && setQuery(input)}
            aria-label="통합검색"
            autoFocus
          />
          <button
            className={`kx-search__ai-toggle ${aiMode ? '' : 'is-off'}`}
            onClick={() => setAiMode((v) => !v)}
            title="AI 자연어 검색(준비 중)"
          >
            <IconSpark size={14} /> AI 자연어 검색
          </button>
        </div>
        <Button onClick={() => setQuery(input)}>검색</Button>
      </div>

      {aiMode && (
        <div className="kx-meet__ai-card" role="note">
          <AiLabel>AI 자연어 검색</AiLabel>{' '}
          <span className="kx-list-table__muted">
            자연어 검색은 준비 중입니다. 현재는 키워드 검색으로 동작합니다.
          </span>
        </div>
      )}

      {!query.trim() ? (
        <EmptyState
          title="검색어를 입력하세요"
          description="업무 데이터 전반을 한 번에 검색합니다."
          icon={<IconSearch size={28} />}
        />
      ) : (
        <div className="kx-cal" style={{ gridTemplateColumns: '200px minmax(0,1fr)' }}>
          {/* 파셋 */}
          <aside className="kx-card" aria-label="검색 필터">
            <div className="kx-card__head">
              <h2><IconTag className="kx-title-ic" size={18} />유형</h2>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {tabs.map((t) => (
                <button
                  key={t}
                  className={`kx-msg__rail-btn ${tab === t ? 'is-active' : ''}`}
                  onClick={() => setTab(t)}
                >
                  {t === 'ALL' ? '전체' : (TYPE_META[t]?.label ?? t)}
                  <span className="kx-list-table__muted">{counts[t] ?? 0}</span>
                </button>
              ))}
            </div>
          </aside>

          {/* 결과 */}
          <section aria-label="검색 결과" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {searchQ.isLoading &&
              Array.from({ length: 5 }).map((_, i) => (
                <div className="kx-search__result" key={i}>
                  <Skeleton height={36} width={36} radius={6} />
                  <div style={{ flex: 1 }}>
                    <Skeleton height={16} width="50%" />
                    <Skeleton height={14} width="80%" />
                  </div>
                </div>
              ))}
            {searchQ.isError && (
              <ErrorState message={errMessage(searchQ.error)} onRetry={() => searchQ.refetch()} />
            )}
            {!searchQ.isLoading && !searchQ.isError && filtered.length === 0 && (
              <EmptyState title="검색 결과가 없습니다" description={`'${query}'에 대한 결과를 찾지 못했습니다.`} />
            )}
            {filtered.map((r: SearchResultItem) => {
              const meta = TYPE_META[r.type] ?? { label: r.type, Icon: IconDocument };
              const Icon = meta.Icon;
              const route = routeFor(r.type, r.id);
              const go = () => route && navigate(route);
              return (
                <div
                  className="kx-search__result"
                  key={`${r.type}-${r.id}`}
                  onClick={route ? go : undefined}
                  onKeyDown={route ? (e) => (e.key === 'Enter' || e.key === ' ') && go() : undefined}
                  role={route ? 'button' : undefined}
                  tabIndex={route ? 0 : undefined}
                  style={route ? { cursor: 'pointer' } : undefined}
                >
                  <span className="kx-search__result-icon">
                    <Icon size={18} />
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="kx-list-table__title">{highlight(r.title)}</div>
                    <div className="kx-detail__meta">
                      <span className="kx-pill kx-pill--info">{meta.label}</span>
                      <span>{fmtDateTime(r.createdAt)}</span>
                    </div>
                  </div>
                </div>
              );
            })}
          </section>
        </div>
      )}
    </div>
  );
}
