// SolaceNet (IRU) agreement preview / e-signature

import React, { useState, useEffect } from 'react';
import { apiClient } from '@/services/api/client';
import { SOLACENET_PRODUCT_NAME, SOLACENET_VENDOR_NAME } from '@/constants/marketplace';

interface AgreementViewerProps {
  agreementId?: string;
  subscriptionId?: string;
  onSign?: () => void;
  onCancel?: () => void;
}

export const AgreementViewer: React.FC<AgreementViewerProps> = ({
  agreementId,
  subscriptionId,
  onSign,
  onCancel,
}) => {
  const [agreement, setAgreement] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [signing, setSigning] = useState(false);

  useEffect(() => {
    // TODO: Fetch agreement content
    // For now, use placeholder
    setLoading(false);
    setAgreement({
      content: `${SOLACENET_PRODUCT_NAME} participation agreement content will be loaded here...`,
      status: 'draft',
    });
  }, [agreementId, subscriptionId]);

  const handleSign = async () => {
    setSigning(true);
    try {
      // TODO: Integrate with e-signature provider (DocuSign/HelloSign)
      await new Promise((resolve) => setTimeout(resolve, 2000));
      
      if (onSign) {
        onSign();
      }
    } catch (err: any) {
      setError(err.message || 'Failed to sign agreement');
    } finally {
      setSigning(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading agreement...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="text-red-600 text-xl mb-4">Error</div>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4 max-w-4xl">
        <div className="bg-white rounded-lg shadow-lg p-8">
          <p className="text-sm text-gray-500 mb-2">{SOLACENET_VENDOR_NAME}</p>
          <h2 className="text-3xl font-bold mb-6 text-gray-800">
            {SOLACENET_PRODUCT_NAME} participation agreement
          </h2>

          {agreement?.status && (
            <div className="mb-4">
              <span className={`px-3 py-1 rounded-full text-sm font-semibold ${
                agreement.status === 'signed' ? 'bg-green-100 text-green-800' :
                agreement.status === 'pending_signature' ? 'bg-yellow-100 text-yellow-800' :
                'bg-gray-100 text-gray-800'
              }`}>
                {agreement.status.replace('_', ' ').toUpperCase()}
              </span>
            </div>
          )}

          <div className="border border-gray-200 rounded-lg p-6 mb-6 max-h-96 overflow-y-auto">
            <pre className="text-sm text-gray-700 whitespace-pre-wrap font-sans">
              {agreement?.content || 'Agreement content not available'}
            </pre>
          </div>

          <div className="flex gap-4">
            {agreement?.status !== 'signed' && (
              <button
                onClick={handleSign}
                disabled={signing}
                className="flex-1 bg-blue-600 text-white py-3 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {signing ? 'Signing...' : 'Sign Agreement'}
              </button>
            )}
            {onCancel && (
              <button
                onClick={onCancel}
                className="flex-1 bg-gray-200 text-gray-800 py-3 px-4 rounded-md hover:bg-gray-300 transition-colors"
              >
                Cancel
              </button>
            )}
          </div>

          {agreement?.status === 'signed' && (
            <div className="mt-4 p-4 bg-green-50 border border-green-200 rounded">
              <p className="text-green-800">
                ✓ Agreement has been signed and executed.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default AgreementViewer;
