import { useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconPlus, IconSearch } from '../../components/ui/icons';
import { approvalApi, type ApprovalBox, type ApprovalListItem, type ApprovalStatus } from './approvalApi';
import { ApprovalComposePanel } from './ApprovalComposePanel';
import './approval-queue.css';

/*
 * SCR-10 결재함(홀매니저·기안자·결재자). §5B 공통 전자결재(F028) 실배선 — WISE 결재함 구조.
 * - 탭: 결재할 문서(PENDING) · 상신한 문서(DRAFTED) · 반려(REJECTED, 내 기안) · 완료(DONE).
 * - 기안: 기안 작성 + 결재선 지정 패널(ApprovalComposePanel mode=create).
 * - 반려건 재상신: 반려/상신 탭의 REJECTED 문서 → 재상신 패널(mode=resubmit, version+1).
 * - 결재할 문서 열기 → ReviewDetailsPage(승인/반려). 라우트 미변경: approvalId 쿼리 전달.
 * ★ App.tsx 불변 — 기안/재상신은 인-페이지 패널(?compose=1 / ?resubmit=<id> 쿼리로 딥링크 가능).
 */
type TabKey = 'PENDING' | 'DRAFTED' | 'REJECTED' | 'DONE';

const TABS: TabKey[] = ['PENDING', 'DRAFTED', 'REJECTED', 'DONE'];

function statusTone(s: ApprovalStatus): string {
  switch (s) {
    case 'APPROVED':
      return 'kx-aq__st--ok';
    case 'REJECTED':
      return 'kx-aq__st--bad';
    case 'IN_PROGRESS':
    case 'SUBMITTED':
      return 'kx-aq__st--wip';
    default:
      return '';
  }
}

export function ManagerApprovalQueuePage() {
  const { eventId = '', hallId = 'H7', booth = 'A-101' } = useParams();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { t } = useTranslation();
  const [sp, setSp] = useSearchParams();

  const [tab, setTab] = useState<TabKey>('PENDING');
  const [keyword, setKeyword] = useState('');
  const [term, setTerm] = useState('');
  const [notice, setNotice] = useState<string | null>(null);

  // 인-페이지 뷰: ?compose=1(기안) / ?resubmit=<id>(재상신) / 그 외 목록.
  const composing = sp.get('compose') === '1';
  const resubmitId = sp.get('resubmit');

  const box: ApprovalBox = tab === 'REJECTED' ? 'DRAFTED' : (tab as ApprovalBox);
  const listQ = useQuery({
    queryKey: ['approvals', box, term],
    queryFn: () => approvalApi.list({ box, keyword: term || undefined, page: 0, size: 100 }),
    enabled: !composing && !resubmitId,
  });

  const allRows = listQ.data?.items ?? [];
  const rows = tab === 'REJECTED' ? allRows.filter((r) => r.status === 'REJECTED') : allRows;

  const statusLabel = (s: ApprovalStatus) => t(`approval.status.${s}`);

  const openCompose = () => {
    setNotice(null);
    setSp({ compose: '1' });
  };
  const openResubmit = (id: string) => {
    setNotice(null);
    setSp({ resubmit: id });
  };
  const backToList = () => setSp({});

  const onDone = (_id: string, msg: string) => {
    setNotice(msg);
    setSp({});
    qc.invalidateQueries({ queryKey: ['approvals'] });
  };

  // 행 클릭: 반려 문서(내 기안)는 재상신, 그 외는 검수/조회 화면으로.
  const onRowOpen = (r: ApprovalListItem) => {
    if (r.status === 'REJECTED') {
      openResubmit(r.id);
      return;
    }
    navigate(
      `/events/${eventId}/halls/${hallId}/booths/${r.refId ?? booth}/review?approvalId=${encodeURIComponent(r.id)}`,
    );
  };

  if (composing) {
    return (
      <ApprovalComposePanel
        mode="create"
        eventId={eventId || undefined}
        onDone={onDone}
        onCancel={backToList}
      />
    );
  }
  if (resubmitId) {
    return (
      <ApprovalComposePanel
        mode="resubmit"
        approvalId={resubmitId}
        eventId={eventId || undefined}
        onDone={onDone}
        onCancel={backToList}
      />
    );
  }

  return (
    <div className="kx-aq">
      <header className="kx-aq__head">
        <div className="kx-aq__head-top">
          <div className="kx-aq__title-row">
            <h1>{t('approval.boxTitle')}</h1>
          </div>
          <div className="kx-aq__head-actions">
            <form
              className="kx-aq__search"
              onSubmit={(e) => {
                e.preventDefault();
                setTerm(keyword.trim());
              }}
            >
              <span aria-hidden="true">
                <IconSearch size={16} />
              </span>
              <input
                placeholder={t('approval.searchPlaceholder')}
                aria-label={t('approval.search')}
                value={keyword}
                onChange={(e) => setKeyword(e.target.value)}
              />
            </form>
            <Button leadingIcon={<IconPlus size={16} />} onClick={openCompose}>
              {t('approval.compose')}
            </Button>
          </div>
        </div>

        <div className="kx-aq__tabs" role="tablist" aria-label={t('approval.boxTitle')}>
          {TABS.map((tk) => (
            <button
              key={tk}
              type="button"
              role="tab"
              aria-selected={tab === tk}
              className={`kx-aq__tab ${tab === tk ? 'is-active' : ''}`}
              onClick={() => {
                setTab(tk);
                setNotice(null);
              }}
            >
              {t(`approval.tab.${tk}`)}
            </button>
          ))}
        </div>
      </header>

      <div className="kx-aq__body">
        <section className="kx-aq__main" aria-label={t('approval.boxTitle')}>
          {notice && (
            <div className="kx-aq__notice" role="status">
              {notice}
            </div>
          )}
          <div className="kx-aq__main-head">
            <h2>{t(`approval.tab.${tab}`)}</h2>
            <span className="kx-aq__count tnum">{rows.length}</span>
          </div>
          <div className="kx-aq__table-wrap">
            {listQ.isLoading ? (
              <div className="kx-aq__skel">
                <Skeleton height={20} />
                <Skeleton height={20} />
                <Skeleton height={20} />
              </div>
            ) : listQ.isError ? (
              <ErrorState onRetry={() => listQ.refetch()} />
            ) : rows.length === 0 ? (
              <EmptyState title={t(`approval.empty.${tab}`)} />
            ) : (
              <table className="kx-table">
                <thead>
                  <tr>
                    <th>{t('approval.colTitle')}</th>
                    <th>{t('approval.colDocType')}</th>
                    <th>{t('approval.colDrafter')}</th>
                    <th>{t('approval.colSubmitted')}</th>
                    <th>{t('approval.colStep')}</th>
                    <th>{t('approval.colStatus')}</th>
                    <th className="kx-aq__col-act">{t('approval.colAction')}</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r) => (
                    <tr key={r.id}>
                      <td>
                        <div className="kx-aq__event">{r.title}</div>
                        {r.refId ? <div className="kx-aq__booth tnum">{r.refId}</div> : null}
                      </td>
                      <td>{t(`approval.docTypes.${r.docType}`, { defaultValue: r.docType })}</td>
                      <td className="kx-aq__muted">{r.drafterName ?? r.drafterId}</td>
                      <td className="kx-aq__muted tnum">{(r.submittedAt ?? '').slice(0, 10) || '-'}</td>
                      <td className="tnum">
                        {r.totalSteps > 0 ? `${r.curStep}/${r.totalSteps}` : '-'}
                      </td>
                      <td>
                        <span className={`kx-aq__st ${statusTone(r.status)}`}>{statusLabel(r.status)}</span>
                      </td>
                      <td className="kx-aq__col-act">
                        <button className="kx-aq__review" onClick={() => onRowOpen(r)}>
                          {r.status === 'REJECTED' ? t('approval.resubmitBtn') : t('approval.open')}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
