import React, { useState } from 'react';

/**
 * Renders a visual preview of Audience segments data including
 * affinity, in-market, life events, and detailed demographics.
 * Also handles geo target search results.
 */
export default function AudiencePreview({ data }) {
  const [expandedSections, setExpandedSections] = useState({
    affinity: true,
    inMarket: true,
    lifeEvents: true,
    detailedDemographics: false
  });

  if (!data) return null;

  // Handle nested response structure
  const segments = data?.result?.data || data?.data || data;

  // Check if this is a geo search result
  const geoResults = segments?.results || [];
  const geoQuery = segments?.query;

  if (geoQuery !== undefined || geoResults.length > 0) {
    return (
      <div className="audience-preview">
        <h4 className="preview-title">
          🌍 Location Search Results
          <span className="source-badge">Query: "{geoQuery}"</span>
        </h4>
        
        <div className="geo-results">
          {geoResults.length === 0 ? (
            <p className="no-results">No locations found</p>
          ) : (
            <table className="geo-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Type</th>
                  <th>Full Name</th>
                </tr>
              </thead>
              <tbody>
                {geoResults.map((geo, idx) => (
                  <tr key={geo.id || idx}>
                    <td className="geo-id">{geo.id}</td>
                    <td className="geo-name">{geo.name}</td>
                    <td>
                      <span className={`type-badge type-${(geo.targetType || '').toLowerCase()}`}>
                        {geo.targetType}
                      </span>
                    </td>
                    <td className="geo-canonical">{geo.canonicalName}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    );
  }

  // Audience segments view
  const affinity = segments?.affinity || [];
  const inMarket = segments?.inMarket || [];
  const lifeEvents = segments?.lifeEvents || [];
  const detailedDemographics = segments?.detailedDemographics || [];
  const totalCount = segments?.totalCount || 0;
  const retrievedAt = segments?.retrievedAt;

  if (totalCount === 0 && affinity.length === 0) {
    return null;
  }

  const toggleSection = (section) => {
    setExpandedSections(prev => ({
      ...prev,
      [section]: !prev[section]
    }));
  };

  const renderSegmentList = (segmentList, sectionKey, icon) => {
    const isExpanded = expandedSections[sectionKey];
    const displayCount = isExpanded ? segmentList.length : Math.min(5, segmentList.length);
    
    return (
      <div className="segment-list">
        {segmentList.slice(0, displayCount).map((seg, idx) => (
          <div key={seg.id || idx} className="segment-item">
            <span className="segment-icon">{icon}</span>
            <span className="segment-name">{seg.name}</span>
            <span className="segment-id">ID: {seg.id}</span>
          </div>
        ))}
        {segmentList.length > 5 && (
          <button 
            className="toggle-btn"
            onClick={() => toggleSection(sectionKey)}
          >
            {isExpanded ? '▲ Show less' : `▼ Show all ${segmentList.length}`}
          </button>
        )}
      </div>
    );
  };

  return (
    <div className="audience-preview">
      <h4 className="preview-title">
        👥 Audience Segments
        <span className="source-badge">Total: {totalCount}</span>
      </h4>

      {retrievedAt && (
        <div className="retrieved-at">
          Retrieved: {new Date(retrievedAt).toLocaleString()}
        </div>
      )}

      {/* Affinity Audiences */}
      {affinity.length > 0 && (
        <div className="segment-section">
          <h5 onClick={() => toggleSection('affinity')} className="section-header clickable">
            <span>💫 Affinity ({affinity.length})</span>
            <span className="expand-icon">{expandedSections.affinity ? '▼' : '▶'}</span>
          </h5>
          <p className="section-desc">Reach users based on lifestyle, interests, and habits</p>
          {expandedSections.affinity && renderSegmentList(affinity, 'affinity', '💫')}
        </div>
      )}

      {/* In-Market Audiences */}
      {inMarket.length > 0 && (
        <div className="segment-section">
          <h5 onClick={() => toggleSection('inMarket')} className="section-header clickable">
            <span>🛒 In-Market ({inMarket.length})</span>
            <span className="expand-icon">{expandedSections.inMarket ? '▼' : '▶'}</span>
          </h5>
          <p className="section-desc">Reach users actively researching or planning to purchase</p>
          {expandedSections.inMarket && renderSegmentList(inMarket, 'inMarket', '🛒')}
        </div>
      )}

      {/* Life Events */}
      {lifeEvents.length > 0 && (
        <div className="segment-section">
          <h5 onClick={() => toggleSection('lifeEvents')} className="section-header clickable">
            <span>🎯 Life Events ({lifeEvents.length})</span>
            <span className="expand-icon">{expandedSections.lifeEvents ? '▼' : '▶'}</span>
          </h5>
          <p className="section-desc">Reach users during important life milestones</p>
          {expandedSections.lifeEvents && renderSegmentList(lifeEvents, 'lifeEvents', '🎯')}
        </div>
      )}

      {/* Detailed Demographics */}
      {detailedDemographics.length > 0 && (
        <div className="segment-section">
          <h5 onClick={() => toggleSection('detailedDemographics')} className="section-header clickable">
            <span>📊 Detailed Demographics ({detailedDemographics.length})</span>
            <span className="expand-icon">{expandedSections.detailedDemographics ? '▼' : '▶'}</span>
          </h5>
          <p className="section-desc">Parental status, education, homeownership, employment</p>
          {expandedSections.detailedDemographics && renderSegmentList(detailedDemographics, 'detailedDemographics', '📊')}
        </div>
      )}

      {/* Quick Reference */}
      <div className="quick-reference">
        <h5>📋 Static Demographics (no API needed)</h5>
        <div className="static-options">
          <div className="option-group">
            <strong>Age:</strong> 18-24, 25-34, 35-44, 45-54, 55-64, 65+
          </div>
          <div className="option-group">
            <strong>Gender:</strong> Male, Female, Unknown
          </div>
          <div className="option-group">
            <strong>Income:</strong> Top 10%, 11-20%, 21-30%, 31-40%, 41-50%, Lower 50%
          </div>
          <div className="option-group">
            <strong>Parental:</strong> Parent, Not a parent, Unknown
          </div>
        </div>
      </div>
    </div>
  );
}
