/**
 * Preview Only App
 * 
 * A minimal React app that renders only the preview component for visual audit.
 * Used when accessing admin.php?page=boostbot-preview-only&widget=xxx
 * 
 * @since 1.6.0
 */

import { useState, useEffect } from 'react'
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
import { ChatSimulator } from './components/appearance/ChatSimulator'
import { LeadFormPreview } from './components/appearance/PreviewElements/LeadFormPreview'
import { CalendarPreview } from './components/appearance/PreviewElements/CalendarPreview'
import { GalleryPreview } from './components/appearance/PreviewElements/GalleryPreview'
import { YouTubePreview } from './components/appearance/PreviewElements/YouTubePreview'
import { ProductCardPreview } from './components/appearance/PreviewElements/ProductCardPreview'
import { SurveyPreview } from './components/appearance/PreviewElements/SurveyPreview'
import { ContactCardPreview } from './components/appearance/PreviewElements/ContactCardPreview'
import { WhatsAppPreview } from './components/appearance/PreviewElements/WhatsAppPreview'
import { 
  PresetGlobalValues, 
  ElementSettings, 
  WidgetSettings,
  DEFAULT_GLOBAL_VALUES, 
  DEFAULT_ELEMENT_SETTINGS,
  DEFAULT_WIDGET_SETTINGS
} from './types/appearance'
import { apiClient } from './api/client'

// Create a query client for this standalone app
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30000,
      retry: 1,
    },
  },
})

interface PreviewOnlyAppProps {
  widget: string
}

// Inner component that uses React Query
function PreviewContent({ widget }: PreviewOnlyAppProps) {
  const [globalValues, setGlobalValues] = useState<PresetGlobalValues>(DEFAULT_GLOBAL_VALUES)
  const [elementSettings, setElementSettings] = useState<ElementSettings>(DEFAULT_ELEMENT_SETTINGS)
  const [widgetSettings, setWidgetSettings] = useState<WidgetSettings>(DEFAULT_WIDGET_SETTINGS)

  // Fetch the active preset data
  const { data: presetData, isLoading } = useQuery({
    queryKey: ['active-preset-for-preview'],
    queryFn: async () => {
      try {
        const response = await apiClient.get<{ 
          data: { 
            preset: {
              global_values?: PresetGlobalValues
              element_settings?: ElementSettings
              widget_settings?: WidgetSettings
            }
          } 
        }>('appearance-presets/active')
        return response.data?.preset
      } catch (e) {
        console.error('Failed to fetch active preset:', e)
        return null
      }
    },
  })

  // Update state when preset data is fetched
  useEffect(() => {
    if (presetData) {
      if (presetData.global_values) {
        setGlobalValues({ ...DEFAULT_GLOBAL_VALUES, ...presetData.global_values })
      }
      if (presetData.element_settings) {
        setElementSettings({ ...DEFAULT_ELEMENT_SETTINGS, ...presetData.element_settings })
      }
      if (presetData.widget_settings) {
        setWidgetSettings({ ...DEFAULT_WIDGET_SETTINGS, ...presetData.widget_settings })
      }
    }
  }, [presetData])

  if (isLoading) {
    return (
      <div style={{ textAlign: 'center', padding: '40px', color: '#666' }}>
        Loading preset data...
      </div>
    )
  }

  // Render the appropriate widget preview
  const renderWidgetPreview = () => {
    switch (widget) {
      case 'leadform':
        return (
          <LeadFormPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.leadForm}
          />
        )
      
      case 'calendar':
        return (
          <CalendarPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.calendar}
          />
        )
      
      case 'gallery':
        return (
          <GalleryPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.gallery}
          />
        )
      
      case 'youtube':
        return (
          <YouTubePreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.youtube}
          />
        )
      
      case 'productcard':
        return (
          <ProductCardPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.productCard}
          />
        )
      
      case 'survey':
        return (
          <SurveyPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.survey}
          />
        )
      
      case 'contactcard':
        return (
          <ContactCardPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.contactCard}
          />
        )
      
      case 'whatsapp':
        return (
          <WhatsAppPreview
            globalValues={globalValues}
            widgetSettings={widgetSettings.whatsapp}
          />
        )
      
      case 'chat':
      default:
        // Full chat window preview
        return (
          <ChatSimulator
            globalValues={globalValues}
            elementSettings={elementSettings}
            scale={1}
          />
        )
    }
  }

  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'flex-start',
      minHeight: '100vh',
      padding: '20px',
      background: '#f5f5f5',
    }}>
      <div style={{
        background: '#fff',
        borderRadius: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        padding: '24px',
        maxWidth: '500px',
        width: '100%',
      }}>
        <div style={{
          marginBottom: '16px',
          paddingBottom: '12px',
          borderBottom: '1px solid #eee',
          fontSize: '12px',
          color: '#666',
          textAlign: 'center',
        }}>
          מצב תצוגה מקדימה: {widget.toUpperCase()}
        </div>
        {renderWidgetPreview()}
      </div>
    </div>
  )
}

// Main exported component wraps with QueryClientProvider
export function PreviewOnlyApp({ widget }: PreviewOnlyAppProps) {
  return (
    <QueryClientProvider client={queryClient}>
      <PreviewContent widget={widget} />
    </QueryClientProvider>
  )
}
