import { useState, useEffect, lazy, Suspense } from 'react';
import { ErrorBoundary } from './components/ErrorBoundary';

const Dashboard = lazy(() => import('./components/Dashboard'));
const WorkflowList = lazy(() => import('./components/WorkflowList'));
const FlowBuilder = lazy(() => import('./components/FlowBuilder'));
const ActivityLog = lazy(() => import('./components/Activity'));
const Integrations = lazy(() => import('./components/Integrations'));
const SettingsPage = lazy(() => import('./components/Settings'));
import { LayoutDashboard, GitBranch, Activity, Plug, Settings } from 'lucide-react';
import { SequensyLogo } from './components/icons/SequensyLogo';
import { workflowService } from './services/workflows';
import { Workflow } from './types/workflow';
import { DataProvider } from './context/DataContext';
import { cn } from './lib/utils';
import { __ } from './lib/i18n';

type Screen = 'dashboard' | 'workflows' | 'builder' | 'logs' | 'integrations' | 'settings';

// Map screen names to WordPress page slugs
const screenToSlug: Record<string, string> = {
  dashboard: 'sequensy-workflows',
  workflows: 'sequensy-workflows-workflows',
  integrations: 'sequensy-workflows-integrations',
  logs: 'sequensy-workflows-activity',
  settings: 'sequensy-workflows-settings',
};

const getInitialScreen = (): Screen => {
  const wpScreen = window.sequensyAPI?.activeScreen;
  if (
    wpScreen &&
    ['dashboard', 'workflows', 'integrations', 'logs', 'settings'].includes(wpScreen)
  ) {
    return wpScreen as Screen;
  }
  return 'dashboard';
};

// Navigate to WordPress admin page to keep sidebar in sync
const navigateToScreen = (screen: Screen) => {
  const slug = screenToSlug[screen];
  if (slug) {
    window.location.href = `/wp-admin/admin.php?page=${slug}`;
  }
};

export default function App() {
  const [activeScreen, setActiveScreen] = useState<Screen>(getInitialScreen);
  const [editingWorkflowId, setEditingWorkflowId] = useState<string | null>(null);
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const fetchWorkflows = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await workflowService.getWorkflows();
      setWorkflows(data);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : __('Failed to load workflows');
      setError(errorMessage);
      console.error('Error fetching workflows:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWorkflows();
  }, []);

  const handleEditWorkflow = (workflowId: string) => {
    setEditingWorkflowId(workflowId);
    setActiveScreen('builder');
  };

  const handleCreateWorkflow = () => {
    setEditingWorkflowId(null);
    setActiveScreen('builder');
  };

  const handleBackToWorkflows = () => {
    setEditingWorkflowId(null);
    setActiveScreen('workflows');
    fetchWorkflows(); // Refresh workflows when returning from builder
  };

  const handleWorkflowCreated = (id: number) => {
    setEditingWorkflowId(id.toString());
  };

  return (
    <ErrorBoundary>
      <DataProvider>
        <div className="min-h-screen bg-slate-100">
          <div className="bg-slate-900 text-white px-4 md:px-6 py-3 flex items-center gap-4 md:gap-6">
            <div className="flex items-center gap-2 hidden md:flex">
              <SequensyLogo size={28} />
              <h1 className="text-white font-semibold tracking-tight font-display">{window.sequensyAPI?.plugin_name ?? 'Sequensy'}</h1>
            </div>
            <div className="flex items-center gap-2 flex md:hidden">
              <SequensyLogo size={24} />
              <h1 className="text-white font-semibold tracking-tight font-display">{window.sequensyAPI?.plugin_name ?? 'Sequensy'}</h1>
            </div>

            <nav className="flex gap-0.5 ml-auto md:ml-4 flex-1 md:flex-initial overflow-x-auto">
              <button
                onClick={() => navigateToScreen('dashboard')}
                className={cn(
                  'flex items-center gap-2 px-3 md:px-4 py-2.5 transition-all duration-200 whitespace-nowrap text-sm border-b-2',
                  activeScreen === 'dashboard'
                    ? 'border-white text-white bg-white/10'
                    : 'border-transparent text-slate-400 hover:text-white hover:bg-white/5',
                )}
              >
                <LayoutDashboard className="w-4 h-4" />
                <span className="hidden sm:inline">{__('Dashboard')}</span>
              </button>
              <button
                onClick={() => navigateToScreen('workflows')}
                className={cn(
                  'flex items-center gap-2 px-3 md:px-4 py-2.5 transition-all duration-200 whitespace-nowrap text-sm border-b-2',
                  activeScreen === 'workflows' || activeScreen === 'builder'
                    ? 'border-white text-white bg-white/10'
                    : 'border-transparent text-slate-400 hover:text-white hover:bg-white/5',
                )}
              >
                <GitBranch className="w-4 h-4" />
                <span className="hidden sm:inline">{__('Workflows')}</span>
              </button>
              <button
                onClick={() => navigateToScreen('integrations')}
                className={cn(
                  'flex items-center gap-2 px-3 md:px-4 py-2.5 transition-all duration-200 whitespace-nowrap text-sm border-b-2',
                  activeScreen === 'integrations'
                    ? 'border-white text-white bg-white/10'
                    : 'border-transparent text-slate-400 hover:text-white hover:bg-white/5',
                )}
              >
                <Plug className="w-4 h-4" />
                <span className="hidden sm:inline">{__('Integrations')}</span>
              </button>
              <button
                onClick={() => navigateToScreen('logs')}
                className={cn(
                  'flex items-center gap-2 px-3 md:px-4 py-2.5 transition-all duration-200 whitespace-nowrap text-sm border-b-2',
                  activeScreen === 'logs'
                    ? 'border-white text-white bg-white/10'
                    : 'border-transparent text-slate-400 hover:text-white hover:bg-white/5',
                )}
              >
                <Activity className="w-4 h-4" />
                <span className="hidden sm:inline">{__('Activity')}</span>
              </button>
              <button
                onClick={() => navigateToScreen('settings')}
                className={cn(
                  'flex items-center gap-2 px-3 md:px-4 py-2.5 transition-all duration-200 whitespace-nowrap text-sm border-b-2',
                  activeScreen === 'settings'
                    ? 'border-white text-white bg-white/10'
                    : 'border-transparent text-slate-400 hover:text-white hover:bg-white/5',
                )}
              >
                <Settings className="w-4 h-4" />
                <span className="hidden sm:inline">{__('Settings')}</span>
              </button>
            </nav>
          </div>

          <div className="p-4 md:p-6">
            <Suspense
              fallback={
                <div className="flex items-center justify-center h-64">
                  <div className="text-center">
                    <div className="inline-block animate-spin rounded-full h-10 w-10 border-2 border-slate-200 border-t-cyan-600" />
                    <p className="mt-4 text-slate-500 text-sm">Loading...</p>
                  </div>
                </div>
              }
            >
              {activeScreen === 'dashboard' && (
                <Dashboard
                  workflows={workflows}
                  onNavigate={(screen) => navigateToScreen(screen as Screen)}
                />
              )}
              {activeScreen === 'workflows' && (
                <WorkflowList
                  workflows={workflows}
                  loading={loading}
                  error={error}
                  onEditWorkflow={handleEditWorkflow}
                  onCreateNew={handleCreateWorkflow}
                  onRefresh={fetchWorkflows}
                />
              )}
              {activeScreen === 'builder' && (
                <FlowBuilder
                  workflowId={editingWorkflowId || undefined}
                  onBack={handleBackToWorkflows}
                  onWorkflowCreated={handleWorkflowCreated}
                />
              )}
              {activeScreen === 'logs' && <ActivityLog />}
              {activeScreen === 'integrations' && <Integrations />}
              {activeScreen === 'settings' && <SettingsPage />}
            </Suspense>
          </div>
        </div>
      </DataProvider>
    </ErrorBoundary>
  );
}
