import React, { useState, useEffect } from 'react';
import { Editor, Frame, Element, useEditor } from '@craftjs/core';
import { 
  HeroSection, 
  EventDetails, 
  TicketSection, 
  TextBlock, 
  ImageBlock, 
  ButtonBlock,
  SpacerBlock,
  TwoColumnLayout
} from './craft/components';

class ErrorBoundary extends React.Component<
  { children: React.ReactNode; fallback: React.ReactNode },
  { hasError: boolean }
> {
  constructor(props: { children: React.ReactNode; fallback: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(_error: Error) {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('PageBuilder Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback;
    }

    return this.props.children;
  }
}

interface EditorWrapperProps {
  pageData: Record<string, unknown> | null;
  enabled: boolean;
  eventId: string;
}

// Component Panel with proper Craft.js integration
const ComponentPanel = () => {
  const { connectors } = useEditor();

  const components = [
    { name: 'Hero Section', component: HeroSection, icon: '🎭' },
    { name: 'Event Details', component: EventDetails, icon: '📅' },
    { name: 'Ticket Section', component: TicketSection, icon: '🎫' },
    { name: 'Text Block', component: TextBlock, icon: '📝' },
    { name: 'Image Block', component: ImageBlock, icon: '🖼️' },
    { name: 'Button Block', component: ButtonBlock, icon: '🔘' },
    { name: 'Spacer Block', component: SpacerBlock, icon: '↕️' },
    { name: 'Two Column Layout', component: TwoColumnLayout, icon: '📱' }
  ];

  return (
    <div className="space-y-2">
      {components.map((comp) => (
        <div
          key={comp.name}
          ref={(ref) => connectors.create(ref, comp.component)}
          className="flex items-center p-3 bg-gray-50 rounded-lg border border-gray-200 cursor-move hover:bg-gray-100 transition-colors"
        >
          <span className="text-lg mr-3">{comp.icon}</span>
          <span className="text-sm font-medium text-gray-700">{comp.name}</span>
        </div>
      ))}
    </div>
  );
};

const EditorWrapper: React.FC<EditorWrapperProps> = ({ pageData, enabled, eventId }) => {
  return (
    <ErrorBoundary
      fallback={
        <div className="bg-white rounded-lg shadow-lg min-h-96 border border-gray-200 flex items-center justify-center">
          <div className="text-center text-gray-500 py-12">
            <div className="text-4xl mb-4">⚠️</div>
            <h3 className="text-lg font-medium mb-2">Editor Error</h3>
            <p className="text-sm mb-4">There was an issue loading the page editor.</p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 text-sm"
            >
              Reload Editor
            </button>
          </div>
        </div>
      }
    >
      <Editor
        resolver={{
          HeroSection,
          EventDetails,
          TicketSection,
          TextBlock,
          ImageBlock,
          ButtonBlock,
          SpacerBlock,
          TwoColumnLayout
        }}
        enabled={enabled}
        onRender={(_render) => {
          // Custom render logic if needed
        }}
      >
        <div className="flex h-full">
          {/* Component Panel */}
          <div className="w-64 bg-white shadow-lg border-r border-gray-200 flex flex-col">
            <div className="p-4 border-b border-gray-200">
              <h3 className="font-semibold text-gray-900">Components</h3>
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
              <ComponentPanel />
            </div>
          </div>

          {/* Main Editor */}
          <div className="flex-1 p-4">
            <div className="bg-white rounded-lg shadow-lg min-h-96 border border-gray-200">
              <Frame data={pageData && Object.keys(pageData).length > 0 ? pageData : undefined}>
                <Element 
                  is="div" 
                  canvas
                  className="w-full min-h-96 p-4"
                  custom={{ 
                    eventId,
                    // Event data will be passed from parent component
                  }}
                >
                  {/* Default content - always show for empty canvas */}
                  <div className="text-center text-gray-500 py-12">
                    <div className="text-4xl mb-4">🎨</div>
                    <h3 className="text-lg font-medium mb-2">Start Building Your Page</h3>
                    <p className="text-sm">Drag components from the left panel to get started</p>
                  </div>
                </Element>
              </Frame>
            </div>
          </div>
        </div>
      </Editor>
    </ErrorBoundary>
  );
};

interface PageBuilderProps {
  eventId: string;
  templateId?: string;
  pageId?: string;
  onSave?: (pageData: Record<string, unknown>) => void;
  onPreview?: (pageData: Record<string, unknown>) => void;
}

const PageBuilder: React.FC<PageBuilderProps> = ({
  eventId,
  templateId,
  pageId,
  onSave,
  onPreview
}) => {
  const [enabled, setEnabled] = useState(true);
  const [pageData, setPageData] = useState<Record<string, unknown> | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (templateId || pageId) {
      loadPageData();
    }
  }, [templateId, pageId]);

  const loadPageData = async () => {
    setLoading(true);
    try {
      const endpoint = templateId 
        ? `/api/templates/${templateId}`
        : `/api/custom-pages/${pageId}`;
      
      // Get auth token for API calls
      const { supabase } = await import('../lib/supabase');
      const { data: { session } } = await supabase.auth.getSession();
      
      const headers: Record<string, string> = {};
      if (session?.access_token) {
        headers['Authorization'] = `Bearer ${session.access_token}`;
      }
      
      const response = await fetch(endpoint, { headers });
      const data = await response.json();
      
      if (data.success) {
        // Safely handle page data that might have invalid component references
        const pageData = data.pageData;
        if (pageData && typeof pageData === 'object' && Object.keys(pageData).length > 0) {
          console.log('Loading existing page data:', pageData);
          setPageData(pageData);
        } else {
          console.log('No page data found, starting with empty canvas');
          setPageData(null);
        }
      } else {
        console.error('Failed to load page data:', data);
        setPageData(null);
      }
    } catch (error) {
      console.error('Error loading page data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!onSave) return;
    
    const editorState = (document.querySelector('[data-craftjs="editor"]') as HTMLElement & { __craft?: { actions?: { serialize(): Record<string, unknown> } } })?.__craft?.actions?.serialize();
    if (editorState) {
      await onSave(editorState);
    }
  };

  const handlePreview = () => {
    if (!onPreview) return;
    
    const editorState = (document.querySelector('[data-craftjs="editor"]') as HTMLElement & { __craft?: { actions?: { serialize(): Record<string, unknown> } } })?.__craft?.actions?.serialize();
    if (editorState) {
      onPreview(editorState);
    }
  };

  const _components = [
    { name: 'Hero Section', component: HeroSection, icon: '🎭' },
    { name: 'Event Details', component: EventDetails, icon: '📅' },
    { name: 'Ticket Section', component: TicketSection, icon: '🎫' },
    { name: 'Text Block', component: TextBlock, icon: '📝' },
    { name: 'Image Block', component: ImageBlock, icon: '🖼️' },
    { name: 'Button Block', component: ButtonBlock, icon: '🔘' },
    { name: 'Spacer Block', component: SpacerBlock, icon: '↕️' },
    { name: 'Two Column Layout', component: TwoColumnLayout, icon: '📱' }
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  return (
    <div className="h-screen bg-gray-100 flex flex-col">
      {/* Toolbar */}
      <div className="bg-white border-b border-gray-200 p-4 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-600">Edit Mode:</span>
            <button
              onClick={() => setEnabled(!enabled)}
              className={`px-3 py-1 text-xs rounded-full ${
                enabled 
                  ? 'bg-green-100 text-green-800' 
                  : 'bg-gray-100 text-gray-600'
              }`}
            >
              {enabled ? 'ON' : 'OFF'}
            </button>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <button
            onClick={handlePreview}
            className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-md hover:bg-gray-50"
          >
            Preview
          </button>
          <button
            onClick={handleSave}
            className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-md"
          >
            Save
          </button>
        </div>
      </div>

      {/* Editor */}
      <div className="flex-1 overflow-hidden">
        <EditorWrapper
          pageData={pageData}
          enabled={enabled}
          eventId={eventId}
        />
      </div>
    </div>
  );
};

export default PageBuilder;