/**
 * Template Engine
 * Phase 5: Sites Renderer & Publishing
 * 
 * Renders blocks using shared components from the component library.
 * Uses fully styled modern components from @shared.
 */
import React from 'react';
import type { Block } from '../types';
import {
  HeroBlock,
  FeatureGridBlock,
  TestimonialsBlock,
  CTABlock,
  ServicesBlock,
  StatsPanel,
  TextBlock,
  QuoteBlock,
  ContactFormBlock,
  ImageGalleryBlock,
  VideoBlock,
  ProductsBlock,
} from '@shared/blocks';

/**
 * Render a block using the template engine.
 * Imports shared components dynamically.
 */
export function renderTemplate(block: Block | any): React.ReactElement {
  // Handle both formats: { type, data } or { type, ...properties }
  let type: string;
  let data: Record<string, any>;
  
  if (block.type && block.data) {
    // Standard format: { type, data }
    type = block.type;
    data = block.data;
  } else {
    // API format: { type, heading, subheading, content, ... }
    type = block.type;
    data = block;
  }

  try {
    // Try to import shared component
    // This will be replaced with actual component imports once shared components are available
    switch (type) {
      case 'hero':
        return renderHeroBlock(data);
      case 'features':
        return renderFeaturesBlock(data);
      case 'testimonials':
        return renderTestimonialsBlock(data);
      case 'text':
        return renderTextBlock(data);
      case 'image':
        return renderImageBlock(data);
      case 'button':
        return renderButtonBlock(data);
      case 'section':
        return renderSectionBlock(data);
      case 'grid':
        return renderGridBlock(data);
      case 'card':
        return renderCardBlock(data);
      case 'list':
        return renderListBlock(data);
      case 'quote':
        return renderQuoteBlock(data);
      case 'video':
        return renderVideoBlock(data);
      case 'form':
        return renderFormBlock(data);
      case 'accordion':
        return renderAccordionBlock(data);
      case 'faq':
        return renderFAQBlock(data);
      case 'cta':
        return renderCTABlock(data);
      case 'services':
        return renderServicesBlock(data);
      case 'stats':
        return renderStatsBlock(data);
      default:
        return <div className="block-unknown">Unknown block type: {type}</div>;
    }
  } catch (error) {
    console.error(`Error rendering block type ${type}:`, error);
    return <div className="block-error">Error rendering block: {type}</div>;
  }
}

/**
 * Render hero block using shared HeroBlock component.
 */
function renderHeroBlock(data: Record<string, any>): React.ReactElement {
  const title = data.heading || data.title || 'Hero Title';
  const subtitle = data.subheading || data.subtitle;
  const content = Array.isArray(data.content) ? data.content.join(' ') : data.content;
  
  return (
    <HeroBlock
      title={title}
      subtitle={subtitle}
      ctaLabel={data.buttonText || data.ctaLabel}
      onCtaClick={data.buttonLink || data.ctaLink ? () => window.location.href = (data.buttonLink || data.ctaLink) : undefined}
      supportingContent={content ? <p>{content}</p> : undefined}
    />
  );
}

/**
 * Render text block using shared TextBlock component.
 */
function renderTextBlock(data: Record<string, any>): React.ReactElement {
  const content = Array.isArray(data.content) ? data.content.join(' ') : data.content;
  
  return (
    <TextBlock
      title={data.heading || data.title}
      content={content || ''}
      align={data.align || 'left'}
    />
  );
}

/**
 * Render image block.
 */
function renderImageBlock(data: Record<string, any>): React.ReactElement {
  return (
    <div className="block-image" style={{ padding: '1rem' }}>
      {data.src && (
        <img 
          src={data.src} 
          alt={data.alt || ''} 
          style={{ maxWidth: '100%', height: 'auto' }}
        />
      )}
      {data.caption && <p style={{ fontSize: '0.9rem', color: '#666' }}>{data.caption}</p>}
    </div>
  );
}

/**
 * Render button block.
 */
function renderButtonBlock(data: Record<string, any>): React.ReactElement {
  return (
    <div className="block-button" style={{ padding: '1rem', textAlign: data.align || 'center' }}>
      <a 
        href={data.link || '#'} 
        className="button"
        style={{ 
          display: 'inline-block', 
          padding: '0.75rem 1.5rem', 
          background: data.color || '#007bff', 
          color: 'white', 
          textDecoration: 'none',
          borderRadius: '4px'
        }}
      >
        {data.text || 'Button'}
      </a>
    </div>
  );
}

/**
 * Render section block.
 */
function renderSectionBlock(data: Record<string, any>): React.ReactElement {
  return (
    <section className="block-section" style={{ padding: '3rem 2rem', background: data.background || 'transparent' }}>
      {data.title && <h2>{data.title}</h2>}
      {data.content && <div dangerouslySetInnerHTML={{ __html: data.content }} />}
    </section>
  );
}

/**
 * Render grid block.
 */
function renderGridBlock(data: Record<string, any>): React.ReactElement {
  const columns = data.columns || 3;
  return (
    <div className="block-grid" style={{ display: 'grid', gridTemplateColumns: `repeat(${columns}, 1fr)`, gap: '2rem', padding: '2rem' }}>
      {data.items?.map((item: any, index: number) => (
        <div key={index} className="grid-item">
          {item.content && <div dangerouslySetInnerHTML={{ __html: item.content }} />}
        </div>
      ))}
    </div>
  );
}

/**
 * Render card block.
 */
function renderCardBlock(data: Record<string, any>): React.ReactElement {
  return (
    <div className="block-card" style={{ border: '1px solid #ddd', borderRadius: '8px', padding: '1.5rem', margin: '1rem' }}>
      {data.title && <h3>{data.title}</h3>}
      {data.content && <div dangerouslySetInnerHTML={{ __html: data.content }} />}
    </div>
  );
}

/**
 * Render list block.
 */
function renderListBlock(data: Record<string, any>): React.ReactElement {
  const listType = data.ordered ? 'ol' : 'ul';
  return React.createElement(
    listType,
    { className: 'block-list', style: { padding: '1rem 2rem' } },
    data.items?.map((item: string, index: number) => (
      <li key={index}>{item}</li>
    ))
  );
}

/**
 * Render quote block.
 */
function renderQuoteBlock(data: Record<string, any>): React.ReactElement {
  return (
    <blockquote className="block-quote" style={{ padding: '2rem', borderLeft: '4px solid #007bff', margin: '2rem 0', fontStyle: 'italic' }}>
      {data.quote && <p>{data.quote}</p>}
      {data.author && <cite>— {data.author}</cite>}
    </blockquote>
  );
}

/**
 * Render video block.
 */
function renderVideoBlock(data: Record<string, any>): React.ReactElement {
  return (
    <div className="block-video" style={{ padding: '1rem' }}>
      {data.src && (
        <video controls style={{ maxWidth: '100%' }}>
          <source src={data.src} type={data.type || 'video/mp4'} />
        </video>
      )}
      {data.embed && <div dangerouslySetInnerHTML={{ __html: data.embed }} />}
    </div>
  );
}

/**
 * Render form block.
 */
function renderFormBlock(data: Record<string, any>): React.ReactElement {
  return (
    <form className="block-form" style={{ padding: '2rem', maxWidth: '600px', margin: '0 auto' }}>
      {data.fields?.map((field: any, index: number) => (
        <div key={index} style={{ marginBottom: '1rem' }}>
          <label>{field.label}</label>
          <input 
            type={field.type || 'text'} 
            name={field.name}
            placeholder={field.placeholder}
            style={{ width: '100%', padding: '0.5rem' }}
          />
        </div>
      ))}
      <button type="submit" style={{ padding: '0.75rem 1.5rem', background: '#007bff', color: 'white', border: 'none', borderRadius: '4px' }}>
        {data.submitText || 'Submit'}
      </button>
    </form>
  );
}

/**
 * Render accordion block.
 */
function renderAccordionBlock(data: Record<string, any>): React.ReactElement {
  return (
    <div className="block-accordion" style={{ padding: '1rem' }}>
      {data.items?.map((item: any, index: number) => (
        <details key={index} style={{ marginBottom: '1rem', border: '1px solid #ddd', borderRadius: '4px', padding: '1rem' }}>
          <summary style={{ cursor: 'pointer', fontWeight: 'bold' }}>{item.title}</summary>
          <div style={{ marginTop: '1rem' }}>{item.content}</div>
        </details>
      ))}
    </div>
  );
}

/**
 * Render features block using shared FeatureGridBlock component.
 */
function renderFeaturesBlock(data: Record<string, any>): React.ReactElement {
  const heading = data.heading || data.title;
  const content = Array.isArray(data.content) ? data.content : [];
  const layout = data.layout || 'two-column';
  const columns = layout === 'two-column' ? 2 : layout === 'three-column' ? 3 : 3;
  
  // Convert content array to features array
  const features = content.map((item: string) => ({
    title: item.split(':')[0] || item,
    description: item.includes(':') ? item.split(':').slice(1).join(':').trim() : undefined,
  }));
  
  return (
    <FeatureGridBlock
      heading={heading}
      features={features}
      columns={columns as 2 | 3 | 4}
    />
  );
}

/**
 * Render testimonials block using shared TestimonialsBlock component.
 */
function renderTestimonialsBlock(data: Record<string, any>): React.ReactElement {
  const title = data.heading || data.title;
  const subtitle = data.subheading || data.subtitle;
  const content = Array.isArray(data.content) ? data.content : [];
  const layout = data.layout || 'cards';
  
  // Convert content array to testimonials array
  const testimonials = content.map((item: string) => ({
    quote: item,
    author: 'Customer', // Default author if not provided
  }));
  
  return (
    <TestimonialsBlock
      title={title}
      subtitle={subtitle}
      testimonials={testimonials}
      columns={layout === 'cards' ? 3 : 1}
      variant={layout === 'cards' ? 'card' : 'default'}
    />
  );
}

/**
 * Render FAQ block.
 */
function renderFAQBlock(data: Record<string, any>): React.ReactElement {
  const heading = data.heading || data.title || 'FAQ';
  const subheading = data.subheading || data.subtitle;
  const content = Array.isArray(data.content) ? data.content : [];
  
  return (
    <section className="block-faq" style={{ padding: '3rem 2rem' }}>
      {heading && <h2 style={{ marginBottom: '1rem' }}>{heading}</h2>}
      {subheading && <p style={{ color: '#666', marginBottom: '2rem' }}>{subheading}</p>}
      <div>
        {content.map((item: string, index: number) => (
          <div key={index} style={{ marginBottom: '1rem', padding: '1rem', borderBottom: '1px solid #eee' }}>
            <p><strong>Q:</strong> {item}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/**
 * Render CTA (Call to Action) block using shared CTABlock component.
 */
function renderCTABlock(data: Record<string, any>): React.ReactElement {
  const title = data.heading || data.title || 'Call to Action';
  const subtitle = data.subheading || data.subtitle;
  const content = Array.isArray(data.content) ? data.content[0] : data.content;
  
  return (
    <CTABlock
      title={title}
      subtitle={subtitle}
      primaryCtaLabel={data.buttonText || data.ctaLabel}
      primaryCtaLink={data.buttonLink || data.ctaLink}
      backgroundImage={data.backgroundImage}
      variant={data.layout === 'full-width' ? 'centered' : 'default'}
    >
      {content && <p>{content}</p>}
    </CTABlock>
  );
}

/**
 * Render services block using shared ServicesBlock component.
 */
function renderServicesBlock(data: Record<string, any>): React.ReactElement {
  const title = data.heading || data.title;
  const subtitle = data.subheading || data.subtitle;
  const content = Array.isArray(data.content) ? data.content : [];
  
  // Convert content array to services array
  const services = content.map((item: string) => ({
    title: item.split(':')[0] || item,
    description: item.includes(':') ? item.split(':').slice(1).join(':').trim() : undefined,
  }));
  
  return (
    <ServicesBlock
      title={title}
      subtitle={subtitle}
      services={services}
      columns={3}
      variant="card"
    />
  );
}

/**
 * Render stats block using shared StatsPanel component.
 */
function renderStatsBlock(data: Record<string, any>): React.ReactElement {
  const content = Array.isArray(data.content) ? data.content : [];
  
  // Convert content array to stats array
  const stats = content.map((item: string) => {
    // Try to parse "Label: Value" format
    const parts = item.split(':');
    if (parts.length >= 2) {
      return {
        label: parts[0].trim(),
        value: parts.slice(1).join(':').trim(),
      };
    }
    return {
      label: item,
      value: '',
    };
  });
  
  return (
    <StatsPanel
      heading={data.heading || data.title}
      stats={stats}
    />
  );
}

