
// Call Trigger Modal Component

const { useState } = React;

function CallModal({ campaign, onClose }) {
  // Hardcoded phone number
  const hardcodedPhone = '919910988218';
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');

  const handleTriggerCall = async () => {
    setLoading(true);
    setError('');

    try {
      // Use hardcoded phone number
      const formattedPhone = hardcodedPhone;
      
      // Call the Nugget API to trigger the voice call
      const response = await fetch('https://api.nugget.com/unified-support/api/v1/ticketing/external/voice/getOrCreateIssue', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Basic ZGVtb251Z2dldEBudWdnZXQuY29tOmQ0NG8yN2IyODg2czczYzZvcGJnLWQ2bnQ0bGNqaW5yYzczOTBjMHBn'
        },
        body: JSON.stringify({
          businessPhoneNumber: '918035341451',
          userPhoneNumber: formattedPhone,
          callDirection: 'outbound',
          journeyId: campaign.journeyId,
          journeyVersion: campaign.journeyVersion
        })
      });

      if (response.ok) {
        const data = await response.json();
        console.log('✅ Call triggered successfully:', data);
        setSuccess(true);
        setTimeout(() => {
          onClose();
        }, 2000);
      } else {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || 'Failed to trigger call');
      }
    } catch (err) {
      console.error('❌ Error triggering call:', err);
      setError(err.message || 'Failed to trigger call. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={{
          padding: '24px',
          borderBottom: '1px solid #ECECEA',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <div>
            <h2 style={{
              margin: 0,
              fontSize: '20px',
              fontWeight: 600,
              color: '#1F2433',
              marginBottom: '4px'
            }}>
              Trigger Call
            </h2>
            <p style={{
              margin: 0,
              fontSize: '14px',
              color: '#5B6B7A'
            }}>
              Campaign: {campaign.name}
            </p>
          </div>
          <button
            onClick={onClose}
            style={{
              background: 'transparent',
              border: 'none',
              cursor: 'pointer',
              padding: '8px',
              borderRadius: '6px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = '#F5F5F5'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
          >
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
              <path d="M15 5L5 15M5 5L15 15" stroke="#5B6B7A" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: '24px' }}>
          {success ? (
            <div style={{
              padding: '32px',
              textAlign: 'center',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '16px'
            }}>
              <div style={{
                width: '64px',
                height: '64px',
                borderRadius: '50%',
                background: '#E8F5E9',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}>
                <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                  <path d="M26.6667 8L12 22.6667L5.33334 16" stroke="#4CAF50" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div>
                <h3 style={{ margin: '0 0 8px 0', fontSize: '18px', fontWeight: 600, color: '#1F2433' }}>
                  Call Triggered Successfully!
                </h3>
                <p style={{ margin: 0, fontSize: '14px', color: '#5B6B7A' }}>
                  The call will be initiated shortly to +91 9910988218
                </p>
              </div>
            </div>
          ) : loading ? (
            <div style={{
              padding: '48px 32px',
              textAlign: 'center',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '16px'
            }}>
              <div style={{ position: 'relative', width: '64px', height: '64px' }}>
                <svg width="64" height="64" viewBox="0 0 64 64" fill="none" style={{ animation: 'spin 1s linear infinite' }}>
                  <circle cx="32" cy="32" r="28" stroke="#E0E0E0" strokeWidth="4"/>
                  <path d="M32 4C45.2548 4 56 14.7452 56 28" stroke="#4CAF50" strokeWidth="4" strokeLinecap="round"/>
                  <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
                </svg>
              </div>
              <div>
                <h3 style={{ margin: '0 0 8px 0', fontSize: '18px', fontWeight: 600, color: '#1F2433' }}>
                  Triggering Call...
                </h3>
                <p style={{ margin: 0, fontSize: '14px', color: '#5B6B7A' }}>
                  Initiating call to +91 9910988218
                </p>
              </div>
              <div style={{
                marginTop: '16px',
                padding: '12px 16px',
                background: '#E8F5E9',
                border: '1px solid #C8E6D4',
                borderRadius: '8px',
                fontSize: '13px',
                color: '#2E7D32'
              }}>
                AI Agent: {campaign.aiAgent}
              </div>
            </div>
          ) : error ? (
            <div style={{
              padding: '32px',
              textAlign: 'center',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '16px'
            }}>
              <div style={{
                width: '64px',
                height: '64px',
                borderRadius: '50%',
                background: '#FFEBEE',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}>
                <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                  <path d="M16 10V16M16 22H16.0133M28 16C28 22.6274 22.6274 28 16 28C9.37258 28 4 22.6274 4 16C4 9.37258 9.37258 4 16 4C22.6274 4 28 9.37258 28 16Z" stroke="#DC2626" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div>
                <h3 style={{ margin: '0 0 8px 0', fontSize: '18px', fontWeight: 600, color: '#1F2433' }}>
                  Call Failed
                </h3>
                <p style={{ margin: 0, fontSize: '14px', color: '#5B6B7A' }}>
                  {error}
                </p>
              </div>
              <Button variant="primary" onClick={handleTriggerCall}>
                Retry
              </Button>
            </div>
          ) : (
            <div style={{
              padding: '32px',
              textAlign: 'center',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '24px'
            }}>
              <div style={{
                width: '64px',
                height: '64px',
                borderRadius: '50%',
                background: '#E3F2FD',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none">
                  <path d="M3 5C3 3.89543 3.89543 3 5 3H8.27924C8.70967 3 9.09181 3.27543 9.22792 3.68377L10.7257 8.17721C10.8831 8.64932 10.6694 9.16531 10.2243 9.38787L7.96701 10.5165C9.06925 12.9612 11.0388 14.9308 13.4835 16.033L14.6121 13.7757C14.8347 13.3306 15.3507 13.1169 15.8228 13.2743L20.3162 14.7721C20.7246 14.9082 21 15.2903 21 15.7208V19C21 20.1046 20.1046 21 19 21H18C9.71573 21 3 14.2843 3 6V5Z" stroke="#2196F3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
              <div>
                <h3 style={{ margin: '0 0 8px 0', fontSize: '18px', fontWeight: 600, color: '#1F2433' }}>
                  Ready to Trigger Call
                </h3>
                <p style={{ margin: '0 0 16px 0', fontSize: '14px', color: '#5B6B7A' }}>
                  Call will be made to +91 9910988218
                </p>
                <div style={{
                  padding: '12px 16px',
                  background: '#E8F5E9',
                  border: '1px solid #C8E6D4',
                  borderRadius: '8px',
                  fontSize: '13px',
                  color: '#2E7D32',
                  marginBottom: '24px'
                }}>
                  <strong>AI Agent:</strong> {campaign.aiAgent}
                </div>
                <Button variant="primary" onClick={handleTriggerCall}>
                  Trigger Call
                </Button>
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
