import React, { useState, useEffect } from 'react';

function RequestHistorySection({ history, onLoadHistory }) {
  const [expanded, setExpanded] = useState(true);

  // Debug log to see if history is being passed correctly
  useEffect(() => {
    console.log('Request history:', history);
  }, [history]);

  const formatTimestamp = (timestamp) => {
    try {
      const date = new Date(timestamp);
      return date.toLocaleTimeString();
    } catch (e) {
      return timestamp;
    }
  };

  const formatUrl = (url) => {
    if (!url) return '';

    // Remove the base URL to focus on the resource path and query params
    let displayUrl = url;

    try {
      const urlObj = new URL(url);
      // Extract the path after the domain
      displayUrl = urlObj.pathname + urlObj.search;

      // Look for the JSON:API path in the URL dynamically
      // This will work with both default /jsonapi/ and custom paths
      const pathParts = urlObj.pathname.split('/');
      const entityIndex = pathParts.findIndex((part, index) => {
        if (index > 0 && ['node', 'user', 'taxonomy_term', 'media', 'file'].includes(part)) {
          return true;
        }
        return false;
      });

      if (entityIndex > 0) {
        // Extract only the relevant part of the path (entity type and beyond)
        displayUrl = '/' + pathParts.slice(entityIndex).join('/') + urlObj.search;
      }
    } catch (e) {
      console.log('Error parsing URL:', e);
      // Fallback to old method if URL parsing fails
      const jsonApiIndex = url.indexOf('/jsonapi/');
      if (jsonApiIndex !== -1) {
        displayUrl = url.substring(jsonApiIndex + 8); // +8 to skip "/jsonapi/"
      }
    }

    // If still too long, truncate
    if (displayUrl.length > 60) {
      return displayUrl.substring(0, 57) + '...';
    }

    return displayUrl;
  };

  return (
    <div className="request-history-section form-item" style={{ marginTop: '24px', display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
      <details className={`claro-details${expanded ? ' is-open' : ''}`} open={expanded} style={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
        <summary className="claro-details__summary" onClick={(e) => {
          e.preventDefault();
          setExpanded(!expanded);
        }} data-testid="history-toggle">
          <span className="claro-details__summary-content">Request history ({history.length})</span>
        </summary>

        <div className="claro-details__wrapper" style={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
          {!history || history.length === 0 ? (
            <div className="form-item__description">
              No requests have been made yet
            </div>
          ) : (
            <div style={{ flexGrow: 1, overflow: 'auto', border: '1px solid #ddd', borderRadius: '4px', display: 'flex', flexDirection: 'column' }}>
              <ul className="item-list" style={{ margin: 0, padding: 0, listStyle: 'none', fontSize: '0.8rem', flexGrow: 1 }} data-testid="history-list">
                {history.map((item, index) => (
                  <li key={item.id} style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    borderBottom: index === history.length - 1 ? 'none' : '1px solid #ddd',
                    padding: '2px 4px',
                    margin: 0,
                  }}>
                    <div style={{ overflow: 'hidden', flex: 1 }}>
                      <div style={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        fontWeight: 500
                      }}>
                        {formatUrl(item.url)}
                      </div>
                      <div style={{ fontSize: '0.75em', color: '#666' }}>
                        {formatTimestamp(item.timestamp)}
                      </div>
                    </div>
                    <div>
                      <button
                        className="button button--small"
                        onClick={() => onLoadHistory(item)}
                        title="Load this request"
                        style={{ padding: '1px 4px', fontSize: '0.7rem' }}
                      >
                        ▶
                      </button>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </details>
    </div>
  );
}

export default RequestHistorySection;
