import React from 'react';
import { Block, ButtonBlock, DividerBlock as DividerBlockType, TextInputBlock as TextInputBlockType, GenerateButtonBlock, StepTitleBlock } from '../../types/blocks';
import ScrollableButtonsBlock from './ScrollableButtonsBlock';
import GridButtonsBlock from './GridButtonsBlock';
import UploadPhotoBlock from './UploadPhotoBlock';
import DividerBlock from './DividerBlock';
import TextInputBlock from './TextInputBlock';
import GenerateButton from './GenerateButton';
import StepTitle from './StepTitle';

interface BlockRendererProps {
  block: Block;
  onAction?: (actionType: string, actionValue: string, blockId?: string) => void;
  extraProps?: Record<string, any>;
}

const BlockRenderer: React.FC<BlockRendererProps> = ({ block, onAction, extraProps }) => {
  switch (block.type) {
    case 'scrollableButtons':
    case 'gridButtons':
      const buttonBlock = block as ButtonBlock;
      if (block.type === 'scrollableButtons') {
        return <ScrollableButtonsBlock block={buttonBlock} onAction={onAction} />;
      }
      return <GridButtonsBlock block={buttonBlock} onAction={onAction} isInputVisible={extraProps?.visible} />;
    case 'uploadPhoto':
      return <UploadPhotoBlock
        previewUrl={window.history.state?.usr?.previewUrl || localStorage.getItem('stickerPreviewUrl')}
        onPhotoSelect={(file) => {
          const tempUrl = URL.createObjectURL(file);
          window.history.replaceState(
            { usr: { previewUrl: tempUrl } },
            '',
            window.location.pathname
          );
          return () => URL.revokeObjectURL(tempUrl);
        }}
      />;
    case 'divider':
      return <DividerBlock block={block as DividerBlockType} />;
    case 'textInput':
      return <TextInputBlock 
        block={block as TextInputBlockType} 
        visible={!!extraProps?.visible} 
        onTextChange={extraProps?.onTextChange}
      />;
    case 'generateButton':
      const generateBlock = block as GenerateButtonBlock;
      return <GenerateButton 
        tokenCount={generateBlock.tokenCount} 
        onGenerate={() => onAction?.('function', 'startGeneration', generateBlock.id)} 
      />;
    case 'stepTitle':
      const stepBlock = block as StepTitleBlock;
      return <StepTitle number={stepBlock.number} text={stepBlock.text} />;
    default:
      console.warn(`Unknown block type: ${block.type}`);
      return null;
  }
};

export default BlockRenderer;
