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

function CodeExamplesTab({ requestUrl, onCopy, showNotification }) {
  const [codeLanguage, setCodeLanguage] = useState('curl');

  // Generate code examples in different languages
  const generateCode = (language) => {
    if (!requestUrl) return 'No request URL available';

    switch (language) {
      case 'curl':
        let curlCommand = `curl -X GET "${requestUrl}"`;
        curlCommand += ` \\\n  -H "Accept: application/vnd.api+json"`;
        return curlCommand;

      case 'js':
        return `// JavaScript fetch example
fetch("${requestUrl}", {
  headers: {
    "Accept": "application/vnd.api+json"
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));`;

      case 'php':
        return `<?php
// PHP cURL example
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "${requestUrl}",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Accept: application/vnd.api+json"
  ]
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
  echo "cURL Error: " . $err;
} else {
  $data = json_decode($response, true);
  print_r($data);
}`;

      case 'python':
        return `# Python requests example
import requests

headers = {
    'Accept': 'application/vnd.api+json'
}

response = requests.get('${requestUrl}', headers=headers)
data = response.json()
print(data)`;

      default:
        return 'Language not supported';
    }
  };

  // Language options for the dropdown
  const languageOptions = [
    { value: 'curl', label: 'cURL' },
    { value: 'js', label: 'JavaScript' },
    { value: 'php', label: 'PHP' },
    { value: 'python', label: 'Python' }
  ];

  const handleCopyCode = () => {
    const code = generateCode(codeLanguage);
    navigator.clipboard.writeText(code)
      .then(() => {
        if (showNotification) {
          showNotification('Code copied to clipboard!', 'success');
        }
      })
      .catch(err => {
        if (showNotification) {
          showNotification(`Failed to copy: ${err}`, 'error');
        }
      });
  };

  return (
    <div className="explorer-panel" style={{ display: 'flex', flexDirection: 'column', height: '100%', backgroundColor: 'var(--explorer-background)', border: '1px solid var(--explorer-border)', borderRadius: 'var(--explorer-panel-radius)', overflow: 'hidden' }}>
      <div className="explorer-panel-header">
        <span>API code examples</span>
        <button
          className="button button--small"
          onClick={handleCopyCode}
          disabled={!requestUrl}
          aria-label="Copy code to clipboard"
        >
          Copy code
        </button>
      </div>

      <div className="explorer-panel-content" style={{ padding: '16px', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{
          marginBottom: '16px',
          display: 'flex',
          alignItems: 'center',
          gap: '12px'
        }}>
          <label htmlFor="code-language" className="form-item__label" style={{ margin: 0, whiteSpace: 'nowrap' }}>Language:</label>
          <div>
            <select
              id="code-language"
              className="form-element"
              value={codeLanguage}
              onChange={(e) => setCodeLanguage(e.target.value)}
              style={{ minWidth: '150px' }}
            >
              {languageOptions.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
          </div>
        </div>

        <div style={{
          borderRadius: '4px',
          overflow: 'hidden',
          flexGrow: 1,
          display: 'flex',
          flexDirection: 'column',
          backgroundColor: 'var(--explorer-background-tertiary)',
          border: '1px solid var(--explorer-border)'
        }}>
          {!requestUrl ? (
            <div className="form-item__description" style={{ padding: '16px', textAlign: 'center' }}>
              Select an entity type and bundle to generate code examples
            </div>
          ) : (
            <SyntaxHighlighter
              language={codeLanguage === 'js' ? 'javascript' : codeLanguage === 'curl' ? 'bash' : codeLanguage}
              style={materialLight}
              wrapLines={true}
              customStyle={{
                margin: 0,
                padding: '16px',
                height: '100%',
                overflow: 'auto',
                backgroundColor: 'var(--explorer-background-tertiary)',
                fontSize: '0.875rem'
              }}
            >
              {generateCode(codeLanguage)}
            </SyntaxHighlighter>
          )}
        </div>
      </div>
    </div>
  );
}

export default CodeExamplesTab;
