/*
 * SCR-29 낙찰 비교·선정(Award) [M15]. 실 API 전환.
 * 정본: GET /api/auctions/{id}/award-view (마감 후 발주자 전용, 봉인 해제) · POST /{id}/award.
 * 대상: 발주자(주최자·참가업체). 마감 후 견적서 비교 → 낙찰 → 계약·발주 전환.
 * 보안: 마감 전 또는 비발주자는 서버가 403 → 화면은 접근 불가 안내. 낙찰 사유 필수(서버 검증).
 */
import { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Button } from '../../components/ui/Button';
import { AiLabel } from '../../components/ui/Badge';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconAiBot, IconCheckCircle, IconDownload, IconList, IconWarning } from '../../components/ui/icons';
import { auctionApi, formatWon, type Quote } from './auctionApi';
import { errMessage, useToast } from './aucShared';
import './auction.css';

/** 인라인 별점 아이콘(★ 텍스트 글리프 대체 — stroke SVG). */
function IconStar({ size = 14 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
      focusable="false"
    >
      <path d="M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.9 6.1 20.5l1.2-6.5L2.5 9.4l6.6-.9L12 2.5z" />
    </svg>
  );
}

export function AwardComparePage() {
  const { auctionId = '' } = useParams();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [reason, setReason] = useState('');
  const [selectedBidId, setSelectedBidId] = useState<string | null>(null);

  const q = useQuery({
    queryKey: ['award-view', auctionId],
    queryFn: () => auctionApi.awardView(auctionId),
    enabled: !!auctionId,
    retry: false,
  });

  const view = q.data;
  const quotes = view?.quotes ?? [];
  const recommended = useMemo(() => quotes.find((x) => x.recommended) ?? quotes[0], [quotes]);
  const alreadyAwarded = !!view?.awarded;
  const selected = quotes.find((x) => x.bidId === selectedBidId) ?? recommended;

  const awardM = useMutation({
    mutationFn: () =>
      auctionApi.award(auctionId, { bidId: selected!.bidId, reason: reason.trim() }),
    onSuccess: (r) => {
      show(`${r.companyName ?? '선정 업체'} 낙찰 승인 완료 — 계약·발주 전환 대상입니다.`);
      qc.invalidateQueries({ queryKey: ['award-view', auctionId] });
    },
    onError: (e) => show(errMessage(e)),
  });

  function onAward() {
    if (!selected) return show('선정할 견적을 선택해 주세요.');
    if (!reason.trim()) return show('선정 사유를 입력해 주세요.');
    awardM.mutate();
  }

  if (q.isLoading) {
    return (
      <div className="kx-page kx-auc">
        <Skeleton height={64} radius={12} />
        <div style={{ height: 16 }} />
        <Skeleton height={360} radius={16} />
      </div>
    );
  }
  if (q.isError) {
    const msg =
      (q.error as { code?: string })?.code === 'FORBIDDEN'
        ? '마감 후 발주자만 견적 비교·낙찰을 열람할 수 있습니다.'
        : '견적 비교 정보를 불러오지 못했습니다.';
    return (
      <div className="kx-page kx-auc">
        <ErrorState message={msg} onRetry={() => q.refetch()} />
      </div>
    );
  }

  return (
    <div className="kx-page kx-auc">
      <header className="kx-auc__head">
        <div>
          <h1 className="kx-auc__title">역경매 응찰 비교 및 낙찰</h1>
          <p className="kx-auc__subtitle">
            {view?.auctionTitle ?? ''} · 마감 후 발주자 뷰(봉인 해제)
          </p>
        </div>
        <Button
          variant="secondary"
          leadingIcon={<IconDownload size={16} />}
          onClick={() => show('응찰서 원본 다운로드는 견적서 PDF 산출 연동 후 제공됩니다.')}
        >
          응찰서 원본 다운로드
        </Button>
      </header>

      <div className="kx-award__summary">
        <div className="kx-award__chip">
          <span className="kx-award__chip-label">공고명</span>
          <span className="kx-award__chip-value">{view?.auctionTitle ?? '—'}</span>
        </div>
        <div className="kx-award__chip">
          <span className="kx-award__chip-label">응찰 현황</span>
          <span className="kx-award__chip-value">총 {view?.bidderCount ?? 0}개사 참여</span>
        </div>
        <div className="kx-award__chip">
          <span className="kx-award__chip-label">낙찰 기준</span>
          <span className="kx-award__chip-value">
            {view?.awardCriteria === 'lowest'
              ? '최저가'
              : `종합평가 (가격 ${view?.weights.price ?? 0}% · 평판 ${view?.weights.reputation ?? 0}% · 납기 ${view?.weights.delivery ?? 0}%)`}
          </span>
        </div>
      </div>

      {quotes.length === 0 ? (
        <EmptyState title="응찰이 없습니다" description="마감된 옥션에 제출된 견적서가 없습니다." />
      ) : (
        <div className="kx-award__grid">
          <div className="kx-award__main">
            {/* 비교 매트릭스 */}
            <section className="kx-card" aria-label="견적 비교표">
              <div className="kx-card__head">
                <h2><IconList className="kx-title-ic" size={18} />견적서 비교표</h2>
                <AiLabel>AI 가중 스코어</AiLabel>
              </div>
              <div className="kx-table-scroll">
                <table className="kx-compare">
                  <thead>
                    <tr>
                      <th className="kx-compare__metric-col">비교 항목</th>
                      {quotes.map((qc2) => (
                        <th
                          key={qc2.bidId}
                          className={`kx-compare__co ${qc2.bidId === selected?.bidId ? 'kx-compare__co--rec' : ''}`}
                        >
                          {qc2.recommended && <span className="kx-compare__rec-tag">최적 추천</span>}
                          <button
                            type="button"
                            className="kx-compare__co-select"
                            aria-pressed={qc2.bidId === selected?.bidId}
                            onClick={() => setSelectedBidId(qc2.bidId)}
                          >
                            <span className="kx-compare__co-name">{qc2.alias}</span>
                            <span className="kx-compare__co-sub">{qc2.subtitle}</span>
                          </button>
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td className="kx-compare__metric-col">총액 (VAT 별도)</td>
                      {quotes.map((qc2) => (
                        <td key={qc2.bidId} className={qc2.isLowestPrice ? 'kx-compare__best' : ''}>
                          <span className="kx-compare__val-strong tnum">
                            {formatWon(qc2.totalPrice)}
                          </span>
                          <span
                            className={`kx-compare__note ${qc2.isLowestPrice ? 'kx-compare__note--best' : ''}`}
                          >
                            {qc2.isLowestPrice ? '최저가' : `+${qc2.priceDeltaPct}% 차이`}
                          </span>
                        </td>
                      ))}
                    </tr>
                    <tr>
                      <td className="kx-compare__metric-col">납기 (시공 완료)</td>
                      {quotes.map((qc2) => (
                        <td key={qc2.bidId} className={qc2.isShortestLead ? 'kx-compare__best' : ''}>
                          <span className="tnum">{qc2.leadDays}일</span>
                          {qc2.isShortestLead && (
                            <span className="kx-compare__note kx-compare__note--best">최단 납기</span>
                          )}
                        </td>
                      ))}
                    </tr>
                    <tr>
                      <td className="kx-compare__metric-col">업체 평판 (최근 1년)</td>
                      {quotes.map((qc2) => {
                        const best =
                          qc2.reputation === Math.max(...quotes.map((x) => x.reputation));
                        return (
                          <td key={qc2.bidId} className={best ? 'kx-compare__best' : ''}>
                            <span className="kx-compare__star">
                              <IconStar size={14} />
                            </span>{' '}
                            <span className="tnum">{qc2.reputation.toFixed(1)}</span>
                          </td>
                        );
                      })}
                    </tr>
                    <tr>
                      <td className="kx-compare__metric-col">종합 점수</td>
                      {quotes.map((qc2) => (
                        <td key={qc2.bidId} className={qc2.recommended ? 'kx-compare__score' : ''}>
                          {qc2.recommended ? (
                            <span className="kx-compare__score-val tnum">
                              {qc2.score.toFixed(1)}
                            </span>
                          ) : (
                            <span
                              className="kx-compare__val-strong tnum"
                              style={{ color: 'var(--color-neutral-500)' }}
                            >
                              {qc2.score.toFixed(1)}
                            </span>
                          )}
                        </td>
                      ))}
                    </tr>
                  </tbody>
                </table>
              </div>
            </section>

            {/* AI 리스크 분석 */}
            <section className="kx-card" aria-label="AI 리스크 분석">
              <div className="kx-card__head">
                <h2><IconAiBot className="kx-title-ic" size={18} />AI 시뮬레이션 · 리스크 분석</h2>
                <AiLabel>AI 분석</AiLabel>
              </div>
              <div className="kx-risk">
                <ul className="kx-barlist">
                  {(view?.riskBars ?? []).map((b) => (
                    <li key={b.label}>
                      <div className="kx-barlist__top">
                        <span>{b.label}</span>
                        <span
                          className="tnum"
                          style={{
                            color:
                              b.tone === 'success'
                                ? 'var(--color-success)'
                                : 'var(--color-neutral-700)',
                            fontWeight: 700,
                          }}
                        >
                          {b.pct}%
                        </span>
                      </div>
                      <div className="kx-barlist__track">
                        <span
                          className={`kx-barlist__fill ${b.tone === 'success' ? 'kx-barlist__fill--success' : 'kx-barlist__fill--ai'}`}
                          style={{ width: `${Math.min(b.pct, 100)}%` }}
                        />
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            </section>
          </div>

          {/* 우 — 낙찰 선정 패널 */}
          <aside className="kx-award__panel" aria-label="낙찰 선정">
            <h2>낙찰 선정</h2>
            {selected && <RecommendCard quote={selected} />}

            <div className="kx-field">
              <label className="kx-field__label" htmlFor="award-reason">
                선정 사유 입력 (필수)
              </label>
              <textarea
                id="award-reason"
                className="kx-award__textarea"
                placeholder="종합 평가 결과 및 업체 강점을 입력하세요. 예: 최저가 응찰 + 과거 동일 규모 행사 수행 실적 우수"
                value={alreadyAwarded ? (view?.awarded?.awardedAt ? '낙찰 완료' : reason) : reason}
                onChange={(e) => setReason(e.target.value)}
                disabled={alreadyAwarded}
              />
            </div>

            <Button
              variant={alreadyAwarded ? 'secondary' : 'primary'}
              block
              leadingIcon={<IconCheckCircle size={16} />}
              onClick={onAward}
              disabled={alreadyAwarded || awardM.isPending}
            >
              {alreadyAwarded
                ? '낙찰 승인 완료'
                : awardM.isPending
                  ? '승인 중…'
                  : '낙찰(Award) 최종 승인'}
            </Button>

            <div className="kx-award__warn">
              <IconWarning size={16} />
              <p>
                낙찰 선정 후에는 취소가 불가하며, 해당 견적서는 즉시 계약·발주 문서로 전환되어 법적
                효력을 갖습니다.
              </p>
            </div>

            <div className="kx-award__steps">
              <p className="kx-award__steps-title">낙찰 이후 프로세스</p>
              <ol>
                <li>
                  <span>1</span> 전자 서명 및 계약 체결
                </li>
                <li>
                  <span>2</span> 시공 착수 회의 예약
                </li>
                <li>
                  <span>3</span> 정기 공정 보고서 발송
                </li>
              </ol>
            </div>
          </aside>
        </div>
      )}
      {toast}
    </div>
  );
}

function RecommendCard({ quote }: { quote: Quote }) {
  return (
    <div className="kx-award__rec">
      <div className="kx-award__rec-top">
        <span className="kx-award__rec-avatar">{quote.alias.slice(0, 2)}</span>
        <div>
          <p className="kx-award__rec-name">
            {quote.alias} ({quote.subtitle})
          </p>
          <span className="kx-award__rec-ai">
            <IconAiBot size={16} /> 종합 점수 {quote.score.toFixed(1)}
          </span>
        </div>
      </div>
      <div className="kx-award__rec-grid">
        <div className="kx-award__rec-cell">
          <span className="kx-award__rec-cell-label">제안 가격</span>
          <span className="kx-award__rec-cell-value tnum">{formatWon(quote.totalPrice)}</span>
        </div>
        <div className="kx-award__rec-cell">
          <span className="kx-award__rec-cell-label">예상 기한</span>
          <span className="kx-award__rec-cell-value tnum">{quote.leadDays}일</span>
        </div>
      </div>
    </div>
  );
}
