import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getPublicPass, publicPassQrUrl } from '../api';
import { PublicPass } from '../types';
import { formatVisitRange } from '../status';

/**
 * Public visitor pass opened from the SMS link (no login). Shows the QR the
 * visitor presents to the access console's webcam.
 */
export const PublicPassPage: React.FC = () => {
  const { token } = useParams<{ token: string }>();
  const [pass, setPass] = useState<PublicPass | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!token) return;
    getPublicPass(token)
      .then(setPass)
      .catch((e) => setError(e instanceof Error ? e.message : '조회 실패'));
  }, [token]);

  if (error) {
    return (
      <div className="badge-sheet">
        <div className="badge-card">
          <div className="badge-head">IT센터 출입증</div>
          <div className="alert alert-error" style={{ marginTop: 16 }}>{error}</div>
        </div>
      </div>
    );
  }

  if (!pass || !token) {
    return <div className="center-screen">불러오는 중…</div>;
  }

  return (
    <div className="badge-sheet">
      <div className="badge-card">
        <div className="badge-head">IT센터 출입증</div>
        <div className="badge-name">{pass.visitorName}</div>
        <div className="badge-company">{pass.company || '-'}</div>
        <img className="badge-qr" src={publicPassQrUrl(token)} alt="출입 QR" />
        <div className="badge-meta">
          <div><b>{pass.zoneName || '-'}</b></div>
          <div><b>{formatVisitRange(pass.visitFrom, pass.visitTo)}</b></div>
        </div>
        <div className="badge-foot">전산실 입장 시 QR을 출입관리시스템에 입력하세요</div>
      </div>
    </div>
  );
};
