import React, { useState, useEffect } from 'react';
import { Toaster } from 'react-hot-toast';
import { useTranslation } from 'react-i18next';
import VariationsTable from './components/table/VariationsTable';
import BulkPanel from './components/bulk/BulkPanel';
import AttributeManager from './components/attributes/AttributeManager';
import SettingsTab from './components/settings/SettingsTab';
import ExportButton from './components/export/ExportButton';
import ImportModal from './components/export/ImportModal';
import CacheWaitOverlay from './components/ui/CacheWaitOverlay';
import { api } from './services/api';
import type { PreviewData } from './types/preview';

type ViewType = 'variations' | 'bulk' | 'attributes' | 'settings';

interface CacheStats {
  health: {
    cache_count: number;
    actual_count: number;
  };
}

function App() {
  const { t } = useTranslation();
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [currentView, setCurrentView] = useState<ViewType>('variations');
  const [isDesktop, setIsDesktop] = useState(window.innerWidth >= 1024);
  const [previewData, setPreviewData] = useState<PreviewData>({});
  const [showImportModal, setShowImportModal] = useState(false);
  const [cachePercentage, setCachePercentage] = useState(100); // Default 100%

  // Auto-check cache on mount
  useEffect(() => {
    const checkAndStartCache = async () => {
      try {
        const response = await api.post('/cache/check-and-start');
        if (response.data.started) {
          console.log('[App] Cache sync auto-started:', response.data.message);
        }
      } catch (error) {
        console.error('[App] Cache check failed:', error);
      }
    };

    checkAndStartCache();
  }, []); // Only on mount

  // Poll cache percentage for overlay
  useEffect(() => {
    const loadCachePercentage = async () => {
      try {
        const response = await api.get('/cache/stats');
        const stats: CacheStats = response.data.data;
        
        if (stats.health.actual_count > 0) {
          const percentage = Math.floor((stats.health.cache_count / stats.health.actual_count) * 100);
          setCachePercentage(percentage);
        }
      } catch (error) {
        console.error('[App] Failed to load cache percentage:', error);
      }
    };

    // Initial load
    loadCachePercentage();

    // Poll every 2 seconds (faster than CacheStatus for overlay responsiveness)
    const interval = setInterval(loadCachePercentage, 2000);

    return () => clearInterval(interval);
  }, []);

  // Responsive check
  useEffect(() => {
    const handleResize = () => {
      setIsDesktop(window.innerWidth >= 1024);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Slide-in panel megjelenítési logika (csak desktop ÉS táblázat nézetben ÉS van kijelölés)
  const showSlideInPanel = isDesktop && currentView === 'variations' && selectedIds.length > 0;

  // Preview handler (BulkPanel-től jön a callback)
  const handlePreviewReceived = (preview: PreviewData) => {
    console.log('[App] Preview received:', preview);
    console.log('[App] Current view:', currentView);
    setPreviewData(preview);
    // Ha full-screen mode-ban vagyunk, váltson vissza táblázat nézetre
    if (currentView === 'bulk') {
      console.log('[App] Switching to variations view');
      setCurrentView('variations');
    }
  };

  // Preview törlése
  const handleClearPreview = () => {
    setPreviewData({});
  };

  return (
    <div className="bg-gradient-to-br from-gray-50 to-gray-100">
      {/* Compact Header with Title, Subtitle, Tabs, and Actions */}
      <header className="bg-white border-b border-gray-200 shadow-sm">
        <div className="px-4 py-2">
          <div className="flex items-center justify-between gap-6">
            {/* Left: Icon + Title/Subtitle + Tabs */}
            <div className="flex items-center gap-6">
              {/* Icon + Title/Subtitle */}
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-lg flex items-center justify-center shadow-md">
                  {/* Grid icon (matching WordPress menu dashicons-grid-view) */}
                  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
                  </svg>
                </div>
                <div>
                  <h1 className="text-xl font-bold text-gray-900 leading-tight">
                    {t('app_title')}
                  </h1>
                  <p className="text-xs text-gray-500 font-medium">{t('app_subtitle')}</p>
                </div>
              </div>
              
              {/* Tabs (same row as title) */}
              <div className="flex gap-2">
                <button
                  onClick={() => setCurrentView('variations')}
                  className={`px-5 py-2 rounded-lg font-semibold text-sm transition flex items-center gap-2 ${
                    currentView === 'variations'
                      ? 'bg-blue-600 text-white shadow-md'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                  </svg>
                  {t('tabs.variations')}
                </button>
                
                <button
                  onClick={() => {
                    if (selectedIds.length === 0) {
                      return;
                    }
                    setCurrentView('bulk');
                    handleClearPreview();
                  }}
                  disabled={selectedIds.length === 0}
                  className={`px-5 py-2 rounded-lg font-semibold text-sm transition flex items-center gap-2 ${
                    currentView === 'bulk'
                      ? 'bg-purple-600 text-white shadow-md'
                      : selectedIds.length === 0
                      ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                  title={selectedIds.length === 0 ? t('tabs.bulk_disabled') : ''}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                  {t('tabs.bulk')}
                  {selectedIds.length > 0 && (
                    <span className="ml-1 px-1.5 py-0.5 bg-white/20 rounded text-xs">
                      {selectedIds.length}
                    </span>
                  )}
                </button>

                <button
                  onClick={() => setCurrentView('attributes')}
                  className={`px-5 py-2 rounded-lg font-semibold text-sm transition flex items-center gap-2 ${
                    currentView === 'attributes'
                      ? 'bg-green-600 text-white shadow-md'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                  </svg>
                  {t('tabs.attributes')}
                </button>
              </div>
            </div>
            
            {/* Right: Export/Import/Settings + Selected counter */}
            <div className="flex items-center gap-3">
              {/* Export Button */}
              <ExportButton selectedIds={selectedIds} />
              
              {/* Import Button */}
              <button
                onClick={() => setShowImportModal(true)}
                className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
                <span className="font-medium text-sm">{t('import.button')}</span>
              </button>
              
              {/* Settings Button */}
              <button
                onClick={() => setCurrentView('settings')}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition ${
                  currentView === 'settings'
                    ? 'bg-gray-900 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                <span className="font-medium text-sm">{t('tabs.settings')}</span>
              </button>
              
              {/* Selected counter */}
              {selectedIds.length > 0 && (
                <div className="flex items-center gap-2 px-4 py-2 bg-blue-50 border border-blue-200 rounded-lg">
                  <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                  </svg>
                  <span className="text-sm font-semibold text-blue-700">
                    {selectedIds.length} {t('selected').toLowerCase()}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* Main content */}
      <main className="relative">
        {/* Full-screen view (tab-based) */}
        {currentView === 'bulk' ? (
          <BulkPanel 
            variationIds={selectedIds} 
            mode="full-screen"
            onPreview={handlePreviewReceived}
            onClearPreview={handleClearPreview}
          />
        ) : currentView === 'attributes' ? (
          <AttributeManager />
        ) : currentView === 'settings' ? (
          <SettingsTab />
        ) : (
          <>
            {/* Táblázat nézet */}
            <VariationsTable 
              onSelectionChange={setSelectedIds}
              previewData={previewData}
            />
            
            {/* Slide-in panel (automatikus segédablak - csak desktop) */}
            {showSlideInPanel && (
              <BulkPanel 
                variationIds={selectedIds} 
                mode="slide-in"
                onPreview={handlePreviewReceived}
                onClearPreview={handleClearPreview}
              />
            )}
          </>
        )}
      </main>

      {/* Toast notifications */}
      <Toaster 
        position="bottom-right"
        toastOptions={{
          duration: 3000,
          style: {
            background: '#fff',
            color: '#333',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            borderRadius: '0.75rem',
            padding: '1rem',
            fontSize: '0.875rem',
            fontWeight: '500',
          },
          success: {
            iconTheme: {
              primary: '#10b981',
              secondary: '#fff',
            },
          },
          error: {
            iconTheme: {
              primary: '#ef4444',
              secondary: '#fff',
            },
          },
        }}
      />

      {/* Import Modal */}
      <ImportModal 
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
      />

      {/* Cache Wait Overlay (5 sec, only if cache < 100%) */}
      <CacheWaitOverlay cachePercentage={cachePercentage} />
    </div>
  );
}

export default App;
