import React, { useState } from 'react';
import { SolutionIcon } from './SolutionIcon';

interface LoginBoxProps {
  access: { url: string; httpsUrl?: string; id: string; pw: string };
  color: string;
  soon?: boolean;
}

const CopyField: React.FC<{ label: string; value: string; color: string }> = ({
  label,
  value,
  color,
}) => {
  const [copied, setCopied] = useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(value);
    } catch {
      // fallback
      const ta = document.createElement('textarea');
      ta.value = value;
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand('copy'); } catch { /* noop */ }
      document.body.removeChild(ta);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <div className="login-field">
      <span className="login-field-label">{label}</span>
      <code className="login-field-value">{value}</code>
      <button className="login-copy-btn" onClick={copy} title="복사" style={{ color }}>
        {copied ? (
          <span className="login-copied">복사됨!</span>
        ) : (
          <SolutionIcon slug="copy" size={16} />
        )}
      </button>
    </div>
  );
};

export const LoginBox: React.FC<LoginBoxProps> = ({ access, color, soon }) => {
  return (
    <div
      className="login-box"
      style={{ borderColor: `${color}40`, boxShadow: `0 0 32px ${color}18` }}
    >
      <div className="login-box-head">
        <span className="login-box-title">접속 정보</span>
        {soon && <span className="badge badge-soon">배포 예정</span>}
      </div>

      {!soon && (
        <>
          <div className="login-field">
            <span className="login-field-label">URL</span>
            <a className="login-url" href={access.url} target="_blank" rel="noreferrer">
              {access.url}
              <SolutionIcon slug="external-link" size={14} />
            </a>
          </div>

          {access.httpsUrl && (
            <div className="login-field">
              <span className="login-field-label">HTTPS</span>
              <a className="login-url" href={access.httpsUrl} target="_blank" rel="noreferrer">
                {access.httpsUrl}
                <SolutionIcon slug="external-link" size={14} />
              </a>
            </div>
          )}

          <CopyField label="ID" value={access.id} color={color} />
          <CopyField label="PW" value={access.pw} color={color} />
        </>
      )}

      {soon && (
        <p className="login-soon-text">
          본 솔루션은 현재 준비 중입니다. 배포 후 접속 정보가 제공됩니다.
        </p>
      )}
    </div>
  );
};

export default LoginBox;
