import React, { useState } from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { materialLight } from 'react-syntax-highlighter/dist/esm/styles/prism';

function AuthSection({ baseUrl = '' }) {
  const [expandedSection, setExpandedSection] = useState('js');

  // Extract the base path without trailing slash
  const jsonapiPath = baseUrl ? baseUrl.replace(/\/$/, '') : '/jsonapi';

  const handleCopyExample = (text) => {
    navigator.clipboard.writeText(text);
  };

  const fetchExample = `
// Get a token using fetch
fetch('/oauth/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET'
})
.then(response => response.json())
.then(data => {
  // Use the access token for authenticated requests
  const token = data.access_token;
  fetch('${jsonapiPath}/node/article', {
    headers: {
      'Authorization': 'Bearer ' + token,
      'Accept': 'application/vnd.api+json'
    }
  });
});`;

  const curlTokenExample = `
# Get a token using cURL
curl -X POST "/oauth/token" \\
  -H "Content-Type: application/x-www-form-urlencoded" \\
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"`;

  const curlJsonapiExample = `
# Make authenticated JSON:API request using cURL
curl -X GET "${jsonapiPath}/node/article" \\
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \\
  -H "Accept: application/vnd.api+json"`;

  const postJsonapiExample = `
# Create content using JSON:API with cURL
curl -X POST "${jsonapiPath}/node/article" \\
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \\
  -H "Accept: application/vnd.api+json" \\
  -H "Content-Type: application/vnd.api+json" \\
  -d '{
    "data": {
      "type": "node--article",
      "attributes": {
        "title": "My New Article",
        "body": {
          "value": "Article content goes here",
          "format": "full_html"
        }
      }
    }
  }'`;

  // Common styling for each accordion section
  const accordionStyles = {
    marginBottom: '12px',
    border: '1px solid var(--explorer-border)',
    borderRadius: '4px',
    overflow: 'hidden'
  };

  const accordionHeaderStyles = {
    padding: '12px 16px',
    backgroundColor: 'var(--explorer-background-secondary)',
    borderBottom: '1px solid var(--explorer-border)',
    cursor: 'pointer',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    fontWeight: '500'
  };

  const accordionContentStyles = {
    display: 'block',
    padding: '0',
    backgroundColor: 'var(--explorer-background-tertiary)'
  };

  return (
    <div className="auth-section explorer-panel" style={{
      marginTop: '24px',
      border: '1px solid var(--explorer-border)',
      borderRadius: 'var(--explorer-panel-radius)',
      overflow: 'hidden'
    }}>
      <div className="explorer-panel-header">
        <span>Examples</span>
      </div>

      <div className="explorer-panel-content" style={{ padding: '16px' }}>
        <div style={{ marginBottom: '16px' }}>
          <p className="form-item__description">
            The JSON:API Explorer automatically uses your current Drupal session for authentication.
            These examples show how to authenticate when accessing the API from external applications.
          </p>
        </div>

        {/* JavaScript Example - Expanded by default */}
        <div style={accordionStyles}>
          <div
            style={accordionHeaderStyles}
            onClick={() => setExpandedSection(expandedSection === 'js' ? '' : 'js')}
          >
            <span>JavaScript authentication example</span>
            {expandedSection === 'js' ? (
              <button
                className="button button--small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleCopyExample(fetchExample);
                }}
                title="Copy example code"
              >
                Copy
              </button>
            ) : (
              <span style={{ fontSize: '0.9em', opacity: 0.6 }}>Click to expand</span>
            )}
          </div>

          {expandedSection === 'js' && (
            <div style={accordionContentStyles}>
              <SyntaxHighlighter
                language="javascript"
                style={materialLight}
                wrapLines={true}
                customStyle={{
                  fontSize: '0.8rem',
                  margin: 0,
                  padding: '16px',
                  backgroundColor: 'var(--explorer-background-tertiary)'
                }}
              >
                {fetchExample}
              </SyntaxHighlighter>
            </div>
          )}
        </div>

        {/* Get Token Example */}
        <div style={accordionStyles}>
          <div
            style={accordionHeaderStyles}
            onClick={() => setExpandedSection(expandedSection === 'curl-token' ? '' : 'curl-token')}
          >
            <span>Get OAuth token with cURL</span>
            {expandedSection === 'curl-token' ? (
              <button
                className="button button--small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleCopyExample(curlTokenExample);
                }}
                title="Copy example code"
              >
                Copy
              </button>
            ) : (
              <span style={{ fontSize: '0.9em', opacity: 0.6 }}>Click to expand</span>
            )}
          </div>

          {expandedSection === 'curl-token' && (
            <div style={accordionContentStyles}>
              <SyntaxHighlighter
                language="bash"
                style={materialLight}
                wrapLines={true}
                customStyle={{
                  fontSize: '0.8rem',
                  margin: 0,
                  padding: '16px',
                  backgroundColor: 'var(--explorer-background-tertiary)'
                }}
              >
                {curlTokenExample}
              </SyntaxHighlighter>
            </div>
          )}
        </div>

        {/* GET Request Example */}
        <div style={accordionStyles}>
          <div
            style={accordionHeaderStyles}
            onClick={() => setExpandedSection(expandedSection === 'curl-get' ? '' : 'curl-get')}
          >
            <span>Authenticated GET request with cURL</span>
            {expandedSection === 'curl-get' ? (
              <button
                className="button button--small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleCopyExample(curlJsonapiExample);
                }}
                title="Copy example code"
              >
                Copy
              </button>
            ) : (
              <span style={{ fontSize: '0.9em', opacity: 0.6 }}>Click to expand</span>
            )}
          </div>

          {expandedSection === 'curl-get' && (
            <div style={accordionContentStyles}>
              <SyntaxHighlighter
                language="bash"
                style={materialLight}
                wrapLines={true}
                customStyle={{
                  fontSize: '0.8rem',
                  margin: 0,
                  padding: '16px',
                  backgroundColor: 'var(--explorer-background-tertiary)'
                }}
              >
                {curlJsonapiExample}
              </SyntaxHighlighter>
            </div>
          )}
        </div>

        {/* POST Request Example */}
        <div style={accordionStyles}>
          <div
            style={accordionHeaderStyles}
            onClick={() => setExpandedSection(expandedSection === 'curl-post' ? '' : 'curl-post')}
          >
            <span>Create content with cURL</span>
            {expandedSection === 'curl-post' ? (
              <button
                className="button button--small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleCopyExample(postJsonapiExample);
                }}
                title="Copy example code"
              >
                Copy
              </button>
            ) : (
              <span style={{ fontSize: '0.9em', opacity: 0.6 }}>Click to expand</span>
            )}
          </div>

          {expandedSection === 'curl-post' && (
            <div style={accordionContentStyles}>
              <SyntaxHighlighter
                language="bash"
                style={materialLight}
                wrapLines={true}
                customStyle={{
                  fontSize: '0.8rem',
                  margin: 0,
                  padding: '16px',
                  backgroundColor: 'var(--explorer-background-tertiary)'
                }}
              >
                {postJsonapiExample}
              </SyntaxHighlighter>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default AuthSection;
