/**
 * @file ResultStep.jsx
 * @description Result step showing credentials after successful onboarding.
 */

window.ResultStep = function ResultStep({ result }) {
  const [copied, setCopied] = React.useState({});

  const copyToClipboard = async (text, field) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied({ ...copied, [field]: true });
      setTimeout(() => setCopied(c => ({ ...c, [field]: false })), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  const downloadCredentials = () => {
    const data = {
      clientId: result.clientId,
      clientSecret: result.clientSecret,
      clientShortId: result.clientShortId,
      dashboardCredentials: result.dashboardCredentials,
      downloadedAt: new Date().toISOString(),
      warning: 'Store these credentials securely. The client secret will not be shown again.'
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `v0uch-credentials-${result.clientShortId}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const downloadCertificatePackage = () => {
    if (!result.certificatePackage || !result.certificatePackage.zipBase64) {
      console.error('No certificate package available');
      return;
    }

    // Decode base64 to binary
    const binaryString = atob(result.certificatePackage.zipBase64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

    const blob = new Blob([bytes], { type: 'application/zip' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = result.certificatePackage.filename || `${result.clientShortId}-certificates.zip`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const CopyButton = ({ text, field }) => (
    <button
      onClick={() => copyToClipboard(text, field)}
      className="ml-2 text-gray-400 hover:text-gray-600"
      title="Copy to clipboard"
    >
      {copied[field] ? (
        <svg className="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
        </svg>
      ) : (
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
        </svg>
      )}
    </button>
  );

  return (
    <div className="fade-in">
      <div className="text-center mb-8">
        <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h2 className="text-2xl font-bold text-gray-900">Registration Complete</h2>
        <p className="text-gray-600 mt-2">Your partner account has been created successfully.</p>
      </div>

      <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
        <div className="flex items-start">
          <svg className="w-5 h-5 text-red-600 mt-0.5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
          <div>
            <p className="font-medium text-red-800">Important: Save these credentials now</p>
            <p className="text-red-700 text-sm mt-1">
              The client secret will NOT be shown again. Download or copy these credentials immediately.
            </p>
          </div>
        </div>
      </div>

      <div className="space-y-6">
        <div className="bg-gray-50 rounded-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-medium text-gray-900">OAuth Client Credentials</h3>
            <button
              onClick={downloadCredentials}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm flex items-center"
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              Download JSON
            </button>
          </div>

          <div className="space-y-4">
            <div>
              <label className="text-sm text-gray-500">Client ID</label>
              <div className="flex items-center mt-1">
                <code className="flex-1 p-3 bg-white rounded border font-mono text-sm break-all">
                  {result.clientId}
                </code>
                <CopyButton text={result.clientId} field="clientId" />
              </div>
            </div>

            <div>
              <label className="text-sm text-gray-500">Client Secret</label>
              <div className="flex items-center mt-1">
                <code className="flex-1 p-3 bg-white rounded border font-mono text-sm break-all text-red-600">
                  {result.clientSecret}
                </code>
                <CopyButton text={result.clientSecret} field="clientSecret" />
              </div>
            </div>

            <div>
              <label className="text-sm text-gray-500">Client Short ID</label>
              <div className="flex items-center mt-1">
                <code className="flex-1 p-3 bg-white rounded border font-mono text-sm">
                  {result.clientShortId}
                </code>
                <CopyButton text={result.clientShortId} field="clientShortId" />
              </div>
            </div>
          </div>
        </div>

        <div className="bg-blue-50 rounded-lg p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Dashboard Access</h3>
          <div className="space-y-4">
            <div>
              <label className="text-sm text-gray-500">Username</label>
              <div className="flex items-center mt-1">
                <code className="flex-1 p-3 bg-white rounded border font-mono text-sm">
                  {result.dashboardCredentials.username}
                </code>
                <CopyButton text={result.dashboardCredentials.username} field="username" />
              </div>
            </div>

            <div>
              <label className="text-sm text-gray-500">Temporary Password</label>
              <div className="flex items-center mt-1">
                <code className="flex-1 p-3 bg-white rounded border font-mono text-sm">
                  {result.dashboardCredentials.temporaryPassword}
                </code>
                <CopyButton text={result.dashboardCredentials.temporaryPassword} field="password" />
              </div>
            </div>

            <a
              href="https://dashboard.partner.v0uch.me"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center text-blue-600 hover:underline"
            >
              Open Dashboard
              <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
            </a>
          </div>
        </div>

        {result.webhookCredentials && (
          <div className="bg-purple-50 rounded-lg p-6">
            <h3 className="text-lg font-medium text-gray-900 mb-4">Webhook Configuration</h3>
            <div className="space-y-4">
              <div>
                <label className="text-sm text-gray-500">Webhook URL</label>
                <div className="flex items-center mt-1">
                  <code className="flex-1 p-3 bg-white rounded border font-mono text-sm break-all">
                    {result.webhookCredentials.webhookUrl}
                  </code>
                  <CopyButton text={result.webhookCredentials.webhookUrl} field="webhookUrl" />
                </div>
              </div>

              <div>
                <label className="text-sm text-gray-500">Webhook Signing Secret</label>
                <div className="flex items-center mt-1">
                  <code className="flex-1 p-3 bg-white rounded border font-mono text-sm break-all text-purple-600">
                    {result.webhookCredentials.webhookSecret}
                  </code>
                  <CopyButton text={result.webhookCredentials.webhookSecret} field="webhookSecret" />
                </div>
              </div>

              <p className="text-sm text-purple-700">
                Use the signing secret to verify incoming webhook payloads.
                Check the X-Webhook-Signature header against your computed HMAC-SHA256.
              </p>
            </div>
          </div>
        )}

        <div className="bg-amber-50 rounded-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-medium text-gray-900">Certificate Package</h3>
            {result.certificatePackage && result.certificatePackage.zipBase64 && (
              <button
                onClick={downloadCertificatePackage}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                Download Certificates (.zip)
              </button>
            )}
          </div>

          <div className="flex items-center mb-3">
            <span className="text-sm text-gray-600 mr-2">mTLS Status:</span>
            <span className={`px-3 py-1 rounded-full text-sm font-medium ${
              result.certificateInfo.status === 'issued'
                ? 'bg-green-100 text-green-700'
                : result.certificateInfo.status === 'pending'
                  ? 'bg-yellow-100 text-yellow-700'
                  : 'bg-red-100 text-red-700'
            }`}>
              {result.certificateInfo.status.charAt(0).toUpperCase() + result.certificateInfo.status.slice(1)}
            </span>
            {result.certificateInfo.status === 'pending' && (
              <span className="ml-3 text-sm text-gray-600">
                Check your dashboard for certificate download once ready.
              </span>
            )}
          </div>

          {result.certificateInfo.expiresAt && (
            <p className="text-sm text-gray-600 mb-3">
              Expires: {new Date(result.certificateInfo.expiresAt).toLocaleDateString()}
            </p>
          )}

          {result.certificatePackage && result.certificatePackage.zipBase64 && (
            <div className="bg-white rounded-lg p-4 mt-3 border border-amber-200">
              <p className="text-sm font-medium text-gray-900 mb-2">Package Contents:</p>
              <ul className="text-sm text-gray-600 space-y-1">
                <li>- mtls/ - API authentication certificates</li>
                <li>- cockroachdb/ - Database certificates</li>
                <li>- signing/ - Ed25519 signing keys (JWKS)</li>
                <li>- README.txt - Setup instructions</li>
                <li>- env.template - Environment configuration</li>
              </ul>
            </div>
          )}

          {(!result.certificatePackage || !result.certificatePackage.zipBase64) && (
            <div className="bg-yellow-100 rounded-lg p-3 mt-3">
              <p className="text-sm text-yellow-800">
                Certificate package not available. Please contact support.
              </p>
            </div>
          )}
        </div>

        <div className="bg-gray-50 rounded-lg p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Next Steps</h3>
          <ol className="list-decimal list-inside space-y-2 text-gray-700">
            {result.nextSteps.map((step, i) => (
              <li key={i}>{step}</li>
            ))}
          </ol>
        </div>
      </div>

      <div className="text-center mt-8">
        <a
          href="https://docs.v0uch.me/partners"
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center px-6 py-3 bg-gray-900 text-white rounded-lg hover:bg-gray-800"
        >
          View Integration Guide
          <svg className="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
          </svg>
        </a>
      </div>
    </div>
  );
};
