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

function UrlDisplay({ url, onCopy, showNotification }) {
  const [showCodeDrawer, setShowCodeDrawer] = useState(false);
  const [codeLanguage, setCodeLanguage] = useState('curl');

  // Make URL selectable for copying
  const handleUrlClick = (e) => {
    // Select the text in the element
    const range = document.createRange();
    range.selectNodeContents(e.currentTarget);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  };

  // Format URL for display with syntax highlighting
  const formatUrl = (url) => {
    if (!url) return null;

    // For syntax highlighting, split the URL into base and params
    try {
      const urlObj = new URL(url);
      const baseUrl = urlObj.origin + urlObj.pathname;
      const searchParams = new URLSearchParams(urlObj.search);

      // Display parameters with ampersands in a single line with minimal spacing
      let parts = [];
      let isFirst = true;

      // Define parameter type colors and their value color families
      // Using higher contrast between values and more distinct parameter names
      const paramTypes = {
        fields: {
          keyColor: '#00796B',  // Teal for parameter names
          valueColors: ['#004D40', '#00695C', '#00897B', '#26A69A', '#4DB6AC', '#80CBC4']  // Teal family with more contrast
        },
        filter: {
          keyColor: '#F57F17',  // Deep Orange for parameter names
          valueColors: ['#BF360C', '#D84315', '#E64A19', '#F4511E', '#FF7043', '#FF8A65']  // Orange family with more contrast
        },
        sort: {
          keyColor: '#6A1B9A',  // Deep Purple for parameter names
          valueColors: ['#311B92', '#4527A0', '#512DA8', '#673AB7', '#7E57C2', '#9575CD']  // Purple family with more contrast
        },
        page: {
          keyColor: '#0D47A1',  // Dark Blue for parameter names
          valueColors: ['#01579B', '#0277BD', '#0288D1', '#039BE5', '#29B6F6', '#4FC3F7']  // Blue family with more contrast
        },
        include: {
          keyColor: '#880E4F',  // Dark Pink for parameter names
          valueColors: ['#AD1457', '#C2185B', '#D81B60', '#E91E63', '#EC407A', '#F06292']  // Pink family with more contrast
        },
        other: {
          keyColor: '#37474F',  // Dark Blue-grey for parameter names
          valueColors: ['#263238', '#37474F', '#455A64', '#546E7A', '#78909C', '#90A4AE']  // Blue-grey family
        }
      };

      const getParamTypeStyle = (key) => {
        if (key.startsWith('fields')) return { color: paramTypes.fields.keyColor };
        if (key.startsWith('filter')) return { color: paramTypes.filter.keyColor };
        if (key.startsWith('sort')) return { color: paramTypes.sort.keyColor };
        if (key.startsWith('page')) return { color: paramTypes.page.keyColor };
        if (key.startsWith('include')) return { color: paramTypes.include.keyColor };
        return { color: paramTypes.other.keyColor };
      };

      const getValueColorFamily = (key) => {
        if (key.startsWith('fields')) return paramTypes.fields.valueColors;
        if (key.startsWith('filter')) return paramTypes.filter.valueColors;
        if (key.startsWith('sort')) return paramTypes.sort.valueColors;
        if (key.startsWith('page')) return paramTypes.page.valueColors;
        if (key.startsWith('include')) return paramTypes.include.valueColors;
        return paramTypes.other.valueColors;
      };

      searchParams.forEach((value, key) => {
        const paramStyle = getParamTypeStyle(key);

        // Get the appropriate color family for this parameter type
        const colorFamily = getValueColorFamily(key);

        // Check if this is a multivalue parameter (has commas)
        if (value.includes(',')) {
          const values = value.split(',');
          const valueElements = values.map((val, index) => (
            <span
              key={index}
              style={{ color: colorFamily[index % colorFamily.length] }}
            >
              {index > 0 && <span className="gin-url-display__separator">,</span>}
              {val}
            </span>
          ));

          parts.push(
            <React.Fragment key={key}>
              {!isFirst && <span className="gin-url-display__separator">&amp;</span>}
              <span className="gin-url-display__param-name" style={paramStyle}>{key}</span>
              <span className="gin-url-display__separator" style={{ margin: '0 2px' }}>=</span>
              {valueElements}
            </React.Fragment>
          );
        } else {
          // For single values, use the first color in the family
          parts.push(
            <React.Fragment key={key}>
              {!isFirst && <span className="gin-url-display__separator">&amp;</span>}
              <span className="gin-url-display__param-name" style={paramStyle}>{key}</span>
              <span className="gin-url-display__separator" style={{ margin: '0 2px' }}>=</span>
              <span className="gin-url-display__param-value" style={{ color: colorFamily[0] }}>{value}</span>
            </React.Fragment>
          );
        }

        isFirst = false;
      });

      return (
        <div className="gin-url-display" onClick={handleUrlClick}>
          <div className="gin-url-display__content">
            <span className="gin-url-display__base">{baseUrl}</span>
            {parts.length > 0 && (
              <>
                <span className="gin-url-display__separator">?</span>
                {parts}
              </>
            )}
          </div>
        </div>
      );
    } catch (e) {
      // Fallback to simple display if URL parsing fails
      console.warn('Error parsing URL for display:', e);
      return (
        <div className="gin-url-display" onClick={handleUrlClick}>
          {url}
        </div>
      );
    }
  };

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

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

      case 'js':
        return `// JavaScript fetch example
fetch("${url}", {
  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 => "${url}",
  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('${url}', 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' }
  ];

  return (
    <div className="url-display" data-testid="url-display">
      <div className="form-item__label form-item__label--multiple-value-form" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h4 className="form-item__label" style={{ margin: 0 }}>Request URL</h4>
        <div>
          <button
            className="button button--small"
            onClick={onCopy}
            disabled={!url}
            aria-label="Copy URL to clipboard"
          >
            Copy URL
          </button>
        </div>
      </div>

      <div className="form-element gin-url-display-wrapper" style={{ padding: 0 }}>
        {url ? (
          formatUrl(url)
        ) : (
          <div className="form-item__description url-display-empty">
            Select an entity type and bundle to build a URL
          </div>
        )}
      </div>

      {/* Code Drawer */}
      <div className={`code-drawer ${showCodeDrawer ? 'code-drawer--visible' : ''}`} style={{
        position: 'fixed',
        top: 0,
        right: 0,
        bottom: 0,
        width: '550px',
        maxWidth: '90vw',
        backgroundColor: 'var(--gin-bg-layer)',
        boxShadow: '-5px 0 15px rgba(0, 0, 0, 0.2)',
        zIndex: 1000,
        transform: showCodeDrawer ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform 0.3s ease-in-out',
        display: 'flex',
        flexDirection: 'column',
        borderLeft: '1px solid var(--gin-border-color)',
      }}>
        <div style={{
          padding: '16px',
          borderBottom: '1px solid var(--gin-border-color)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          backgroundColor: 'var(--gin-bg-header)'
        }}>
          <h3 style={{ margin: 0, fontWeight: 500 }}>API code examples</h3>
          <button
            onClick={() => setShowCodeDrawer(false)}
            className="button button--small"
            aria-label="Close code drawer"
          >
            ✕
          </button>
        </div>

        <div style={{
          padding: '12px 16px',
          borderBottom: '1px solid var(--gin-border-color)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '12px'
        }}>
          <div style={{ 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>

          <button
            className="button button--small code-copy-button"
            onClick={() => {
              const code = generateCode(codeLanguage);
              navigator.clipboard.writeText(code)
                .then(() => {
                  if (showNotification) {
                    showNotification('Code copied to clipboard!', 'success');
                  } else {
                    console.log('Code copied to clipboard');
                  }
                })
                .catch(err => {
                  if (showNotification) {
                    showNotification(`Failed to copy: ${err}`, 'error');
                  } else {
                    console.error('Failed to copy code: ', err);
                  }
                });
            }}
            disabled={!url}
            aria-label="Copy code to clipboard"
            title="Copy code"
          >
            Copy code
          </button>
        </div>

        <div style={{ flex: 1, position: 'relative', display: 'flex', flexDirection: 'column' }}>
          <div style={{
            flex: '1 1 auto',
            background: 'var(--gin-bg-app)',
            border: '1px solid var(--gin-border-color)',
            borderRadius: '4px',
            margin: '0 16px 16px',
            position: 'relative',
            height: 'calc(100% - 48px)', // Increased for bottom margin
            overflow: 'hidden',
            display: 'flex',
            marginBottom: '24px' // Added margin at the bottom
          }}>
            <SyntaxHighlighter
              language={codeLanguage === 'js' ? 'javascript' : codeLanguage === 'php' ? 'php' : codeLanguage === 'python' ? 'python' : 'bash'}
              style={materialLight}
              wrapLines={true}
              customStyle={{
                margin: 0,
                padding: '16px',
                borderRadius: '4px',
                fontSize: '0.9rem',
                width: '100%',
                height: '100%',
                overflow: 'auto',
                background: 'var(--gin-bg-app)'
              }}
            >
              {generateCode(codeLanguage)}
            </SyntaxHighlighter>
          </div>
        </div>
      </div>

      {/* Overlay when drawer is open */}
      {showCodeDrawer && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            zIndex: 999,
          }}
          onClick={() => setShowCodeDrawer(false)}
        />
      )}
    </div>
  );
}

export default UrlDisplay;
