/*
 * SCR-38 업체 수주 부스 대시보드(업체 포털 홈) [M15]. 실 API 전환.
 * 정본: GET /api/contractor/dashboard (ContractorDashboard).
 * 대상: 장치·공사업체. 상단 KPI + 좌 수주 부스 리스트 + 우 옥션 참여·알림 피드.
 * 보안: 옥션 참여 위젯은 자사 응찰 금액만 표기(타사 금액 비노출 — 서버가 자사 데이터만 반환).
 */
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Button } from '../../components/ui/Button';
import { DdayChip } from '../../components/ui/Badge';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import {
  IconBell,
  IconCheckCircle,
  IconDocument,
  IconGrid,
  IconList,
  IconTag,
  IconUsers,
  IconWarning,
} from '../../components/ui/icons';
import { useToast } from '../auction/aucShared';
import {
  contractorApi,
  formatWon,
  type AwardedBooth,
  type MyBid,
} from '../auction/auctionApi';
import './contractor.css';

export function ContractorBoothDashboardPage() {
  const navigate = useNavigate();
  const { node: toast } = useToast();

  const q = useQuery({
    queryKey: ['contractor-dashboard'],
    queryFn: () => contractorApi.dashboard(),
    retry: false,
    refetchInterval: 15000,
  });
  const data = q.data;

  return (
    <div className="kx-page">
      <header className="kx-cbd__head">
        <div>
          <h1 className="kx-cbd__title">수주 부스</h1>
          <p className="kx-cbd__subtitle">{data?.companyName ?? '업체 포털'}</p>
        </div>
        <Button variant="secondary" onClick={() => navigate('/auctions')}>
          옥션 참여하기
        </Button>
      </header>

      {q.isLoading && <Skeleton height={96} radius={12} />}
      {q.isError && !q.isLoading && (
        <ErrorState message="대시보드를 불러오지 못했습니다." onRetry={() => q.refetch()} />
      )}

      {!q.isLoading && !q.isError && data && (
        <>
          {/* KPI 밴드 */}
          <section className="kx-cbd__kpis" aria-label="핵심 지표">
            {data.kpis.map((k) => (
              <div key={k.label} className={`kx-kpi ${k.tone === 'error' ? 'kx-kpi--error' : ''}`}>
                <span className="kx-kpi__label">
                  {k.tone === 'error' && <IconWarning size={14} />}
                  {k.label}
                </span>
                <strong
                  className="kx-kpi__value tnum"
                  style={k.tone === 'success' ? { color: 'var(--color-success)' } : undefined}
                >
                  {k.value}
                </strong>
              </div>
            ))}
          </section>

          <div className="kx-cbd__grid">
            {/* 좌 — 수주 부스 리스트 */}
            <section className="kx-cbd__col" aria-label="수주 부스 리스트">
              <div className="kx-card__head" style={{ marginBottom: 0 }}>
                <h2 style={{ fontSize: 'var(--fs-h2)' }}><IconList className="kx-title-ic" size={18} />수주 부스 리스트</h2>
              </div>

              {data.awardedBooths.length === 0 ? (
                <EmptyState
                  title="수주한 부스가 없습니다"
                  description="진행 중인 옥션에 응찰해 시공을 수주하세요."
                />
              ) : (
                data.awardedBooths.map((b) => (
                  <BoothCard
                    key={b.auctionId}
                    booth={b}
                    onOpen={() => navigate(`/auctions/${b.auctionId}`)}
                  />
                ))
              )}
            </section>

            {/* 우 — 위젯 */}
            <aside className="kx-cbd__col" aria-label="옥션·알림 위젯">
              <div className="kx-cbd-widget">
                <div className="kx-card__head">
                  <h2 style={{ fontSize: 'var(--fs-h3)' }}><IconTag className="kx-title-ic" size={18} />옥션 참여 현황</h2>
                </div>
                <div className="kx-cbd-widget__rows">
                  {data.myAuctionBids.length === 0 ? (
                    <p className="kx-cbd-bid__price" style={{ padding: '8px 0' }}>
                      참여 중인 옥션이 없습니다.
                    </p>
                  ) : (
                    data.myAuctionBids.map((bid) => (
                      <BidItem
                        key={bid.auctionId}
                        bid={bid}
                        onOpen={() => navigate(`/auctions/${bid.auctionId}`)}
                      />
                    ))
                  )}
                </div>
                <Button
                  variant="ghost"
                  block
                  onClick={() => navigate('/auctions')}
                  style={{ marginTop: 16 }}
                >
                  옥션 대시보드로 이동
                </Button>
              </div>

              <div className="kx-cbd-widget">
                <div className="kx-card__head">
                  <h2 style={{ fontSize: 'var(--fs-h3)' }}><IconBell className="kx-title-ic" size={18} />알림 피드</h2>
                </div>
                <div className="kx-feed">
                  {data.feed.length === 0 ? (
                    <p className="kx-feed__meta">새로운 알림이 없습니다.</p>
                  ) : (
                    data.feed.map((f) => (
                      <div key={f.text} className="kx-feed__item">
                        <span className={`kx-feed__dot kx-feed__dot--${f.tone}`}>
                          {f.tone === 'ok' ? (
                            <IconCheckCircle size={14} />
                          ) : f.tone === 'warn' ? (
                            <IconWarning size={14} />
                          ) : (
                            <IconDocument size={14} />
                          )}
                        </span>
                        <p className="kx-feed__text">{f.text}</p>
                        <p className="kx-feed__meta">{f.meta}</p>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </aside>
          </div>
        </>
      )}
      {toast}
    </div>
  );
}

function BoothCard({ booth, onOpen }: { booth: AwardedBooth; onOpen: () => void }) {
  return (
    <article className="kx-booth">
      <div className="kx-booth__top">
        <div>
          <span className="kx-booth__event-tag">{booth.event}</span>
          <h4 className="kx-booth__name">{booth.name}</h4>
          <div className="kx-booth__meta">
            <span>
              <IconGrid size={14} /> Booth {booth.booth || '—'}
            </span>
            {booth.client && (
              <span>
                <IconUsers size={14} /> {booth.client}
              </span>
            )}
          </div>
        </div>
        <div className="kx-booth__right">
          <p className="kx-booth__right-label">상태</p>
          <p
            className="kx-booth__right-value"
            style={{ color: 'var(--color-success)', fontSize: 'var(--fs-body)' }}
          >
            {booth.stage}
          </p>
        </div>
      </div>
      <div className="kx-booth__actions">
        <Button variant="secondary" leadingIcon={<IconDocument size={16} />} onClick={onOpen}>
          옥션 상세
        </Button>
      </div>
    </article>
  );
}

function BidItem({ bid, onOpen }: { bid: MyBid; onOpen: () => void }) {
  const rank = bid.myRank ?? 0;
  const rankCls = rank === 1 ? 'kx-rankpill--1' : rank > 0 && rank <= 3 ? 'kx-rankpill--mid' : 'kx-rankpill--low';
  return (
    <button type="button" className="kx-cbd-bid" onClick={onOpen} style={{ width: '100%', textAlign: 'left', border: 0, background: 'transparent' }}>
      <div>
        <p className="kx-cbd-bid__name">{bid.auctionTitle}</p>
        <p className="kx-cbd-bid__price tnum">내 입찰가: {formatWon(bid.myPrice)}</p>
      </div>
      <div className="kx-cbd-bid__right">
        <span className={`kx-rankpill ${rankCls}`}>{rank > 0 ? `${rank}위` : '-'}</span>
        <DdayChip dday={bid.dday} />
      </div>
    </button>
  );
}
