import { useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '../../components/ui/Button';
import { AiLabel } from '../../components/ui/Badge';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import {
  IconChevronRight,
  IconClose,
  IconDownload,
  IconExpand,
  IconMinus,
  IconPlus,
  IconSpark,
} from '../../components/ui/icons';
import { approvalApi, type ApprovalLine, type ApprovalStatus } from './approvalApi';
import './review-details.css';
import './approval-form.css';

/*
 * SCR-11 검수 상세. §5B 공통 전자결재(F028) 실배선.
 * - 좌: 문서/도면 프리뷰(참고용 샘플 캔버스 유지) / 우: 실 결재선 타임라인·이력 + 승인/반려(실동작).
 * - approvalId 쿼리 존재 시 실 결재 문서 로드·처리(승인/반려는 현재 단계 결재자만 백엔드 403).
 *   반려는 사유 입력 모달(사유 필수). 반려된 내 기안은 재상신 링크(결재함 재상신 패널) 노출.
 *   미존재 시 기존 데모(도면·AI 오버레이) 유지 — 라우트 하위호환.
 */
const MOCK = `${import.meta.env.BASE_URL}mock/review_details`;
const BLUEPRINT = `${MOCK}/img1.jpg`;

const TABS = ['도면', '예상 사진 (참고용)', '버전 비교'];

type ActionKind = 'approve' | 'reject';

// 상태 → Nifty blog contextual 배지 톤(공용 .kx-detailview__badge)
function statusTone(s: ApprovalStatus): string {
  switch (s) {
    case 'APPROVED':
      return 'kx-detailview__badge--ok';
    case 'REJECTED':
      return 'kx-detailview__badge--danger';
    case 'IN_PROGRESS':
    case 'SUBMITTED':
      return 'kx-detailview__badge--info';
    default:
      return '';
  }
}

function lineTone(s: ApprovalLine['lineStatus']): string {
  switch (s) {
    case 'CURRENT':
      return 'kx-rev__step--cur';
    case 'APPROVED':
      return 'kx-rev__step--ok';
    case 'REJECTED':
      return 'kx-rev__step--bad';
    case 'SKIPPED':
      return 'kx-rev__step--skip';
    default:
      return '';
  }
}

export function ReviewDetailsPage() {
  const { booth = 'A-102' } = useParams();
  const [sp] = useSearchParams();
  const approvalId = sp.get('approvalId');
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { t } = useTranslation();
  const [tab, setTab] = useState(0);
  const [overlay, setOverlay] = useState(true);
  const [notice, setNotice] = useState<string | null>(null);
  const [actionKind, setActionKind] = useState<ActionKind | null>(null);

  const detailQ = useQuery({
    queryKey: ['approval', approvalId],
    queryFn: () => approvalApi.get(approvalId as string),
    enabled: !!approvalId,
  });

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ['approval', approvalId] });
    qc.invalidateQueries({ queryKey: ['approvals'] });
  };

  const approveM = useMutation({
    mutationFn: (comment: string) => approvalApi.approve(approvalId as string, comment.trim() || undefined),
    onSuccess: () => {
      setNotice(t('approval.approvedDone'));
      setActionKind(null);
      invalidate();
    },
    onError: (e: Error) => setNotice(e.message),
  });

  const rejectM = useMutation({
    mutationFn: (comment: string) => approvalApi.reject(approvalId as string, comment.trim()),
    onSuccess: () => {
      setNotice(t('approval.rejectedDone'));
      setActionKind(null);
      invalidate();
    },
    onError: (e: Error) => setNotice(e.message),
  });

  const d = detailQ.data;
  const busy = approveM.isPending || rejectM.isPending;
  const statusLabel = d ? t(`approval.status.${d.status}`) : '';

  const doAction = (comment: string) => {
    if (actionKind === 'approve') approveM.mutate(comment);
    else if (actionKind === 'reject') rejectM.mutate(comment);
  };

  return (
    <div className="kx-rev">
      <header className="kx-rev__head">
        <div>
          <nav className="kx-rev__crumb" aria-label="경로">
            <button onClick={() => navigate(-1)}>{t('approval.boxTitle')}</button>
            <span aria-hidden="true">
              <IconChevronRight size={14} />
            </span>
            <span className="kx-rev__crumb-cur">{d ? d.title : `부스 ${booth}`}</span>
          </nav>
          <div className="kx-rev__title-row">
            <h1 className="kx-detailview__title">{d ? d.title : t('approval.reviewTitle')}</h1>
            {d ? (
              <span className={`kx-detailview__badge ${statusTone(d.status)}`}>{statusLabel}</span>
            ) : (
              <span className="kx-detailview__badge kx-detailview__badge--info">
                {t('approval.demoMode')}
              </span>
            )}
          </div>
          {d ? (
            <div className="kx-detailview__meta">
              <span className="kx-detailview__meta-item">
                <span className="kx-detailview__meta-label">{t('approval.version')}</span>
                <span className="kx-detailview__meta-value">v{d.version}</span>
              </span>
              <span className="kx-detailview__meta-item">
                <span className="kx-detailview__meta-label">{t('approval.drafter')}</span>
                <span className="kx-detailview__meta-value">{d.drafterName ?? d.drafterId}</span>
              </span>
              <span className="kx-detailview__meta-item">
                <span className="kx-detailview__meta-label">{t('approval.step')}</span>
                <span className="kx-detailview__meta-value">
                  {d.curStep}/{d.totalSteps}
                </span>
              </span>
            </div>
          ) : null}
        </div>
        <Button variant="ghost" leadingIcon={<IconDownload size={16} />}>
          {t('approval.downloadOriginal')}
        </Button>
      </header>

      <div className="kx-rev__body">
        {/* 좌: 문서/도면 프리뷰(참고용) */}
        <section className="kx-rev__canvas" aria-label={t('approval.previewAria')}>
          <div className="kx-rev__canvas-top">
            <div className="kx-rev__tabs" role="tablist">
              {TABS.map((tabLabel, i) => (
                <button
                  key={tabLabel}
                  role="tab"
                  aria-selected={tab === i}
                  className={tab === i ? 'is-active' : ''}
                  onClick={() => setTab(i)}
                >
                  {tabLabel}
                </button>
              ))}
            </div>
            <button
              className={`kx-rev__overlay-toggle ${overlay ? 'is-on' : ''}`}
              onClick={() => setOverlay((o) => !o)}
              aria-pressed={overlay}
            >
              <span aria-hidden="true">
                <IconSpark size={15} />
              </span>{' '}
              AI 오버레이
              <span className="kx-rev__switch" aria-hidden="true">
                <span className="kx-rev__switch-knob" />
              </span>
            </button>
          </div>
          <div className="kx-rev__viewer">
            <div className="kx-rev__grid-bg" aria-hidden="true" />
            <div className="kx-rev__drawing">
              <img src={BLUEPRINT} alt={t('approval.previewAria')} loading="lazy" />
            </div>
            <div className="kx-rev__zoom">
              <button aria-label="확대">
                <IconPlus size={18} />
              </button>
              <button aria-label="축소">
                <IconMinus size={18} />
              </button>
              <button aria-label="화면맞춤">
                <IconExpand size={18} />
              </button>
            </div>
          </div>
        </section>

        {/* 우: 실 결재선 타임라인·이력·의견 */}
        <aside className="kx-rev__panel" aria-label={t('approval.lineAria')}>
          {!approvalId ? (
            <div className="kx-rev__ai-card">
              <div className="kx-rev__ai-card-head">
                <AiLabel>{t('approval.demoMode')}</AiLabel>
              </div>
              <p className="kx-rev__vdetail">{t('approval.demoHint')}</p>
            </div>
          ) : detailQ.isLoading ? (
            <div className="kx-rev__ai-card">
              <Skeleton height={24} width="70%" />
              <Skeleton height={16} />
              <Skeleton height={120} />
            </div>
          ) : detailQ.isError || !d ? (
            <ErrorState onRetry={() => detailQ.refetch()} />
          ) : (
            <>
              {d.content ? (
                <div className="kx-rev__ai-card">
                  <div className="kx-rev__ai-card-head">
                    <strong>{t('approval.docBody')}</strong>
                  </div>
                  <p className="kx-rev__vdetail">{d.content}</p>
                </div>
              ) : null}

              <div className="kx-rev__ai-card">
                <div className="kx-rev__ai-card-head">
                  <strong>{t('approval.line')}</strong>
                </div>
                <ol className="kx-rev__steps">
                  {d.lines.map((l) => (
                    <li key={l.id} className={`kx-rev__step ${lineTone(l.lineStatus)}`}>
                      <span className="kx-rev__step-no" aria-hidden="true">
                        {l.stepNo}
                      </span>
                      <div>
                        <p className="kx-rev__vtitle">{l.approverName ?? l.approverId}</p>
                        <p className="kx-rev__vdetail">
                          {t(`approval.lineStatus.${l.lineStatus}`)}
                          {l.comment ? ` — ${l.comment}` : ''}
                        </p>
                      </div>
                    </li>
                  ))}
                </ol>
              </div>

              <div className="kx-rev__thread">
                <h3>{t('approval.history')}</h3>
                {d.history.length === 0 ? (
                  <EmptyState title={t('approval.noHistory')} />
                ) : (
                  d.history.map((h) => (
                    <div key={h.id} className="kx-rev__comment">
                      <span className="kx-rev__avatar">{t(`approval.action.${h.action}`)}</span>
                      <div>
                        <div className="kx-rev__comment-top">
                          <strong>{h.actorName ?? h.actorId}</strong>
                          <span>{(h.actedAt ?? '').replace('T', ' ').slice(0, 16)}</span>
                        </div>
                        {h.comment ? <p>{h.comment}</p> : null}
                      </div>
                    </div>
                  ))
                )}
              </div>
            </>
          )}
        </aside>
      </div>

      {/* 하단 액션 — 승인/반려(현재 단계 결재자) · 재상신(반려된 내 기안) */}
      <footer className="kx-rev__footer">
        <div className="kx-rev__foot-left">
          <p className="kx-rev__foot-note">
            {notice
              ? notice
              : approvalId && d
                ? d.canAct
                  ? t('approval.canActHint')
                  : d.canResubmit
                    ? t('approval.canResubmitHint')
                    : t('approval.notApproverHint')
                : t('approval.demoFootNote')}
          </p>
        </div>
        <div className="kx-rev__foot-actions">
          {approvalId && d?.canResubmit ? (
            <Button
              variant="secondary"
              onClick={() => navigate(`/work/approval?resubmit=${encodeURIComponent(d.id)}`)}
            >
              {t('approval.resubmitBtn')}
            </Button>
          ) : null}
          <Button
            variant="danger"
            disabled={!approvalId || !d?.canAct || busy}
            onClick={() => {
              setNotice(null);
              setActionKind('reject');
            }}
          >
            {t('approval.reject')}
          </Button>
          <Button
            disabled={!approvalId || !d?.canAct || busy}
            onClick={() => {
              setNotice(null);
              setActionKind('approve');
            }}
          >
            {t('approval.approve')}
          </Button>
        </div>
      </footer>

      {actionKind && (
        <ActionModal
          kind={actionKind}
          busy={busy}
          onClose={() => setActionKind(null)}
          onConfirm={doAction}
        />
      )}
    </div>
  );
}

function ActionModal({
  kind,
  busy,
  onClose,
  onConfirm,
}: {
  kind: ActionKind;
  busy: boolean;
  onClose: () => void;
  onConfirm: (comment: string) => void;
}) {
  const { t } = useTranslation();
  const [comment, setComment] = useState('');
  const required = kind === 'reject';
  const canConfirm = !busy && (!required || comment.trim().length > 0);

  return (
    <div className="kx-apm__backdrop" role="dialog" aria-modal="true" onClick={onClose}>
      <div className="kx-apm" onClick={(e) => e.stopPropagation()}>
        <div className="kx-apm__head">
          <h2>{kind === 'reject' ? t('approval.rejectModalTitle') : t('approval.approveModalTitle')}</h2>
          <button className="kx-apm__close" aria-label={t('approval.cancel')} onClick={onClose}>
            <IconClose size={18} />
          </button>
        </div>
        <div className="kx-apm__body">
          <label className="kx-apm__label" htmlFor="kx-apm-comment">
            {required ? t('approval.rejectReason') : t('approval.comment')}
            {required ? <em style={{ color: 'var(--color-error)', fontStyle: 'normal' }}> *</em> : null}
          </label>
          <textarea
            id="kx-apm-comment"
            className="kx-apm__textarea"
            rows={4}
            value={comment}
            placeholder={required ? t('approval.rejectReasonPlaceholder') : t('approval.commentOptional')}
            onChange={(e) => setComment(e.target.value)}
          />
          {required ? <span className="kx-apm__hint">{t('approval.rejectReasonHint')}</span> : null}
        </div>
        <div className="kx-apm__foot">
          <Button variant="ghost" onClick={onClose} disabled={busy}>
            {t('approval.cancel')}
          </Button>
          <Button
            variant={kind === 'reject' ? 'danger' : 'primary'}
            disabled={!canConfirm}
            onClick={() => onConfirm(comment)}
          >
            {busy ? t('approval.saving') : kind === 'reject' ? t('approval.reject') : t('approval.approve')}
          </Button>
        </div>
      </div>
    </div>
  );
}
