/**
 * Content Plan Plugin - Main TypeScript Entry Point
 */

import React from 'react';
import { render } from '@wordpress/element';
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
    ContentPlanProvider,
    useContentPlan,
} from './context/ContentPlanContext';
import DynamicSettingsForm from './components/DynamicSettingsForm';
import ContentPlanTable from './components/ContentPlanTable';
import CalendarView from './components/CalendarView';
import ContentPlanGenerationModal from './components/ContentPlanGenerationModal';
import ContentPlanItemSidebar from './components/ContentPlanItemSidebar';
import TasksPanel from './components/TasksPanel';
import LogsTable from './components/LogsTable';
import Toast from './components/Toast';
import RecalculateScheduleModal from './components/RecalculateScheduleModal';
import OnboardingScreen from './components/OnboardingScreen';
import ErrorMessage from './components/ErrorMessage';
import Tooltip from './components/Tooltip';
import OptInPrompt from './components/OptInPrompt';
import { Tab, Settings, ContentPlanGenerationFormData } from './types';
import '../css/app.css';

const App: React.FC = () => {
    const [activeTab, setActiveTab] = useState<string>('content-plan');
    const [contentPlanView, setContentPlanView] = useState<
        'table' | 'calendar'
    >('table');
    const [toast, setToast] = useState<{
        message: string;
        type: 'success' | 'error' | 'info';
        isVisible: boolean;
    }>({
        message: '',
        type: 'success',
        isVisible: false,
    });
    const [recalculateModal, setRecalculateModal] = useState<{
        isOpen: boolean;
        futureItemsCount: number;
        oldInterval: number;
        newInterval: number;
    }>({
        isOpen: false,
        futureItemsCount: 0,
        oldInterval: 7,
        newInterval: 7,
    });
    const {
        loading,
        error,
        data,
        user,
        usage,
        usageError,
        backendConfigured,
        settings,
        fieldConfigs,
        strings,
        clearError,
        refreshData,
        saveSettings,
        recalculateSchedule,
        getString,
        generationModalOpen,
        openGenerationModal,
        closeGenerationModal,
        currentTaskId,
        tasks,
        tasksLoading,
        sidebarOpen,
        opted,
        optinUrl,
    } = useContentPlan();

    // Check if tutorial should be shown
    const showTutorial = settings && settings.tutorial_watched !== true;

    // Define tooltip order
    const tooltipOrder = [
        'content-plan-header',
        'generate-ai',
        'schedule-manual',
        'usage-box',
    ];

    // State to track current tooltip
    const [currentTooltipIndex, setCurrentTooltipIndex] = useState<number>(0);
    const currentTooltipId =
        showTutorial && currentTooltipIndex < tooltipOrder.length
            ? tooltipOrder[currentTooltipIndex]
            : null;

    // Function to advance to next tooltip
    const nextTooltip = () => {
        // Small delay to allow fade-out animation to complete
        setTimeout(() => {
            if (currentTooltipIndex < tooltipOrder.length - 1) {
                setCurrentTooltipIndex(prev => prev + 1);
            } else {
                // All tooltips shown, mark tutorial as watched
                markTutorialWatched();
            }
        }, 200); // Match fade-out animation duration
    };

    // Function to skip tutorial
    const skipTutorial = () => {
        markTutorialWatched();
    };

    // Function to mark tutorial as watched
    const markTutorialWatched = async () => {
        try {
            await saveSettings({
                ...settings,
                tutorial_watched: true,
            });
            setCurrentTooltipIndex(tooltipOrder.length); // Stop showing tooltips
        } catch (error) {
            console.error('Failed to mark tutorial as watched:', error);
        }
    };

    // Reset tooltip index when tutorial becomes available
    useEffect(() => {
        if (showTutorial) {
            setCurrentTooltipIndex(0);
        }
    }, [showTutorial]);

    const tabs: Tab[] = [
        {
            id: 'content-plan',
            label: getString('navigation', 'content_plan', 'Content Plan'),
        },
        {
            id: 'settings',
            label: getString('navigation', 'settings', 'Settings'),
        },
        { id: 'log', label: getString('navigation', 'log', 'Log') },
    ];

    const handleOnboardingComplete = () => {
        // Refresh data to get updated settings
        refreshData();
    };

    const handleOnboardingSkip = () => {
        // Settings are already updated optimistically in OnboardingScreen
        // Refresh other data in the background without blocking the dashboard
        refreshData();
    };

    // Check if onboarding is needed
    // Show onboarding if onboarding_completed is not explicitly true
    // (i.e., it's false or undefined/not set)
    // BUT skip onboarding if opted === false (user has opted out of Freemius)
    const needsOnboarding =
        settings && settings.onboarding_completed !== true && opted !== false;

    // Check if onboarding is completed - if so, show dashboard immediately even while loading
    const onboardingCompleted =
        settings && settings.onboarding_completed === true;

    // Show loader while loading OR while settings haven't been populated yet
    // BUT skip loading spinner if onboarding is already completed (to allow immediate dashboard display after skip)
    if (
        (loading || !settings || Object.keys(settings).length === 0) &&
        !onboardingCompleted
    ) {
        return (
            <div
                className="min-h-screen font-wp flex items-center justify-center"
                style={{ backgroundColor: '#f0f0f1' }}
            >
                <div className="cpepai-loading">
                    <div className="cpepai-spinner"></div>
                    {getString('app', 'loading', 'Loading...')}
                </div>
            </div>
        );
    }

    // Show onboarding screen if needed (after loading is complete)
    if (needsOnboarding) {
        return (
            <OnboardingScreen
                onComplete={handleOnboardingComplete}
                onSkip={handleOnboardingSkip}
            />
        );
    }

    const renderTabContent = (): JSX.Element | null => {
        // Don't show error in main content area if sidebar is open
        // (error will be shown in the sidebar instead)
        if (error && !sidebarOpen) {
            return (
                <div className="mb-4">
                    <ErrorMessage
                        message={error}
                        title={getString('app', 'error', 'Error')}
                    />
                    <div className="mt-2">
                        <button
                            onClick={clearError}
                            className="cpepai-button-secondary text-sm"
                        >
                            {getString('common', 'dismiss', 'Dismiss')}
                        </button>
                    </div>
                </div>
            );
        }

        switch (activeTab) {
            case 'content-plan':
                return (
                    <div>
                        <div className="mb-4">
                            <h2 className="text-xl sm:text-2xl font-semibold text-wp-text mb-2">
                                {getString(
                                    'content_plan_table',
                                    'title',
                                    'Content Plan'
                                )}
                            </h2>
                            <p className="text-sm sm:text-base text-wp-gray mb-4 sm:mb-6">
                                {getString(
                                    'content_plan_table',
                                    'description',
                                    'Manage your content plans with the table below. Create, edit, and delete content plans as needed.'
                                )}
                            </p>
                        </div>

                        {/* Tasks Panel - shown when there are tasks, loading tasks, or a current task */}
                        {(() => {
                            const unwatchedTasks = tasks.filter(
                                task => !task.watched
                            );
                            const hasActiveTasks = unwatchedTasks.some(
                                task =>
                                    task.status === 'queued' ||
                                    task.status === 'processing'
                            );
                            const hasAnyTasks = unwatchedTasks.length > 0;
                            // Show panel if: loading tasks, has active tasks, has any tasks, or currentTaskId is set
                            const shouldShowPanel =
                                tasksLoading ||
                                currentTaskId ||
                                hasActiveTasks ||
                                hasAnyTasks;

                            return shouldShowPanel ? (
                                <div className="mb-6">
                                    <TasksPanel
                                        taskId={currentTaskId || undefined}
                                        onClose={() => {
                                            // onClose will be handled by TasksPanel to clear currentTaskId
                                        }}
                                    />
                                </div>
                            ) : null;
                        })()}

                        {/* Horizontal Tabs for Table/Calendar View */}
                        <div className="mb-4">
                            <div className="border-b border-gray-200">
                                <nav
                                    className="flex -mb-px"
                                    aria-label="Content Plan Views"
                                >
                                    <button
                                        onClick={() =>
                                            setContentPlanView('table')
                                        }
                                        className={`px-4 py-2 text-sm font-medium transition-colors duration-200 ${
                                            contentPlanView === 'table'
                                                ? 'border-b-2 border-[#080081] text-[#080081]'
                                                : 'text-gray-600 hover:text-gray-800 hover:border-gray-300'
                                        }`}
                                    >
                                        {getString(
                                            'content_plan_table',
                                            'table_view',
                                            'Table View'
                                        )}
                                    </button>
                                    <button
                                        onClick={() =>
                                            setContentPlanView('calendar')
                                        }
                                        className={`px-4 py-2 text-sm font-medium transition-colors duration-200 ${
                                            contentPlanView === 'calendar'
                                                ? 'border-b-2 border-[#080081] text-[#080081]'
                                                : 'text-gray-600 hover:text-gray-800 hover:border-gray-300'
                                        }`}
                                    >
                                        {getString(
                                            'content_plan_table',
                                            'calendar_view',
                                            'Calendar View'
                                        )}
                                    </button>
                                </nav>
                            </div>
                        </div>

                        {/* Render selected view */}
                        {contentPlanView === 'table' ? (
                            <ContentPlanTable
                                currentTooltipId={currentTooltipId}
                                onTooltipDismiss={nextTooltip}
                                currentTooltipIndex={currentTooltipIndex}
                                totalTooltipCount={tooltipOrder.length}
                                onSkipTutorial={skipTutorial}
                            />
                        ) : (
                            <CalendarView getString={getString} />
                        )}
                    </div>
                );
            case 'settings':
                return (
                    <div>
                        <h2 className="text-xl sm:text-2xl font-semibold text-wp-text mb-3 sm:mb-4">
                            {getString('settings', 'title', 'Settings')}
                        </h2>
                        <p className="text-sm sm:text-base text-wp-gray mb-4 sm:mb-6">
                            {getString(
                                'settings',
                                'description',
                                'Configure your plugin settings below'
                            )}
                        </p>

                        {fieldConfigs &&
                        Object.keys(fieldConfigs).length > 0 ? (
                            <DynamicSettingsForm
                                settings={settings}
                                fieldConfigs={fieldConfigs}
                                onSave={async (formData: Settings) => {
                                    try {
                                        const result =
                                            await saveSettings(formData);

                                        // Check if recalculation is needed
                                        if (result?.recalculation_needed) {
                                            setRecalculateModal({
                                                isOpen: true,
                                                futureItemsCount:
                                                    result.future_items_count ||
                                                    0,
                                                oldInterval:
                                                    result.old_interval || 7,
                                                newInterval:
                                                    result.new_interval || 7,
                                            });
                                        } else {
                                            // Show success toast notification
                                            setToast({
                                                message: getString(
                                                    'settings',
                                                    'save_success',
                                                    'Settings saved successfully'
                                                ),
                                                type: 'success',
                                                isVisible: true,
                                            });
                                        }
                                    } catch (error) {
                                        console.error(
                                            'Failed to save settings:',
                                            error
                                        );
                                        // Show error toast notification
                                        setToast({
                                            message: getString(
                                                'settings',
                                                'save_error',
                                                'Failed to save settings'
                                            ),
                                            type: 'error',
                                            isVisible: true,
                                        });
                                    }
                                }}
                            />
                        ) : (
                            <div className="bg-gray-50 rounded-lg p-4 sm:p-6">
                                <p className="text-sm sm:text-base text-wp-gray">
                                    {getString(
                                        'settings',
                                        'no_settings_config',
                                        'No settings configuration available.'
                                    )}
                                </p>
                            </div>
                        )}
                    </div>
                );
            case 'log':
                return (
                    <div>
                        <h2 className="text-xl sm:text-2xl font-semibold text-wp-text mb-3 sm:mb-4">
                            {getString('log', 'title', 'Log')}
                        </h2>
                        <p className="text-sm sm:text-base text-wp-gray mb-4 sm:mb-6">
                            {getString(
                                'log',
                                'description',
                                'Activity logs will be available here.'
                            )}
                        </p>
                        <LogsTable />
                    </div>
                );
            default:
                return null;
        }
    };

    // Show onboarding screen if needed (after loading is complete)
    if (needsOnboarding) {
        return (
            <OnboardingScreen
                onComplete={handleOnboardingComplete}
                onSkip={handleOnboardingSkip}
            />
        );
    }

    // Show main dashboard (onboarding completed or not needed)
    return (
        <div
            className="min-h-screen font-wp"
            style={{ backgroundColor: '#f0f0f1' }}
        >
            <div className="w-full p-3 sm:p-4 md:p-6">
                {/* Main Layout - Responsive: Vertical on mobile, Horizontal on desktop */}
                <div className="flex flex-col lg:flex-row gap-4 lg:gap-6">
                    {/* Navigation - Horizontal tabs on mobile, Vertical sidebar on desktop */}
                    <div className="w-full lg:w-64 lg:flex-shrink-0">
                        <div className="p-3 sm:p-4">
                            <nav className="flex flex-row lg:flex-col gap-2 lg:space-y-2 lg:space-x-0 overflow-x-auto lg:overflow-x-visible">
                                {tabs.map(tab => (
                                    <button
                                        key={tab.id}
                                        className={`flex-shrink-0 lg:w-full text-left px-3 sm:px-4 py-2 sm:py-3 transition-colors duration-200 whitespace-nowrap relative ${
                                            activeTab === tab.id
                                                ? 'text-[#080081] border-l-[3px] border-[#080081] font-bold'
                                                : 'text-gray-600 bg-transparent hover:text-gray-800'
                                        }`}
                                        onClick={() => setActiveTab(tab.id)}
                                    >
                                        {tab.label}
                                    </button>
                                ))}
                            </nav>

                            {/* Usage Information - Displayed below navigation menu */}
                            <Tooltip
                                show={showTutorial}
                                tooltipId="usage-box"
                                currentTooltipId={currentTooltipId}
                                content="This shows your account status and remaining AI credits. Credits are used only when generating content with AI."
                                position="right"
                                onDismiss={nextTooltip}
                                currentIndex={currentTooltipIndex + 1}
                                totalCount={tooltipOrder.length}
                                onSkip={skipTutorial}
                            >
                                <div className="mt-4 p-3 bg-white rounded-lg border border-gray-200 shadow-sm">
                                    <h3 className="text-sm font-semibold text-wp-text mb-2">
                                        {getString('common', 'usage', 'Usage')}
                                    </h3>
                                    {loading ? (
                                        <div className="flex items-center justify-center py-4">
                                            <div className="cpepai-spinner"></div>
                                            <span className="ml-2 text-xs text-wp-gray">
                                                {getString(
                                                    'app',
                                                    'loading',
                                                    'Loading...'
                                                )}
                                            </span>
                                        </div>
                                    ) : opted === false ? (
                                        <OptInPrompt
                                            getString={getString}
                                            optinUrl={optinUrl}
                                        />
                                    ) : usageError ? (
                                        <div className="py-4">
                                            <ErrorMessage
                                                message={usageError}
                                                title={getString(
                                                    'common',
                                                    'usage_load_error_title',
                                                    '🚀 Houston, we have a connection problem.'
                                                )}
                                            />
                                        </div>
                                    ) : usage ? (
                                        <div className="space-y-2 text-xs text-wp-gray">
                                            <div className="flex justify-between items-center">
                                                <span>
                                                    {getString(
                                                        'common',
                                                        'account_status',
                                                        'Account Status'
                                                    )}
                                                    :
                                                </span>
                                                <span
                                                    className={`font-medium ${
                                                        usage.blocked
                                                            ? 'text-red-600'
                                                            : 'text-green-600'
                                                    }`}
                                                >
                                                    {usage.blocked
                                                        ? getString(
                                                              'common',
                                                              'blocked',
                                                              'Blocked'
                                                          )
                                                        : getString(
                                                              'common',
                                                              'active',
                                                              'Active'
                                                          )}
                                                </span>
                                            </div>
                                            <div className="flex justify-between items-center">
                                                <span>
                                                    {getString(
                                                        'common',
                                                        'tokens_remaining',
                                                        'Tokens Remaining'
                                                    )}
                                                    :
                                                </span>
                                                <span
                                                    className={`font-medium ${
                                                        usage.tokensRemaining >
                                                        0
                                                            ? 'text-green-600'
                                                            : 'text-red-600'
                                                    }`}
                                                >
                                                    {usage.tokensRemaining}
                                                </span>
                                            </div>
                                            {usage.renewDate && (
                                                <div className="flex justify-between items-center">
                                                    <span>
                                                        {getString(
                                                            'common',
                                                            'renew_date',
                                                            'Renew Date'
                                                        )}
                                                        :
                                                    </span>
                                                    <span className="font-medium">
                                                        {new Date(
                                                            usage.renewDate
                                                        ).toLocaleDateString()}
                                                    </span>
                                                </div>
                                            )}
                                            {usage.blocked && (
                                                <div className="mt-2 p-2 bg-red-50 border border-red-200 rounded text-red-700 text-xs">
                                                    {getString(
                                                        'common',
                                                        'account_blocked',
                                                        'Account is blocked'
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                    ) : backendConfigured ? (
                                        <div className="py-4">
                                            <p className="text-xs text-wp-gray text-center">
                                                {getString(
                                                    'common',
                                                    'usage_not_available',
                                                    'Usage information is not available at this time.'
                                                )}
                                            </p>
                                        </div>
                                    ) : null}
                                </div>
                            </Tooltip>
                        </div>
                    </div>

                    {/* Right Column - Tab Content */}
                    <div className="flex-1 min-w-0">
                        <div className="cpepai-card p-4 sm:p-5 md:p-6 min-h-[400px] sm:min-h-[500px] md:min-h-[600px]">
                            {renderTabContent()}
                        </div>
                    </div>
                </div>
            </div>

            {/* Content Plan Generation Modal */}
            <ContentPlanGenerationModal
                isOpen={generationModalOpen}
                onClose={closeGenerationModal}
            />

            {/* Toast Notification */}
            <Toast
                message={toast.message}
                type={toast.type}
                isVisible={toast.isVisible}
                onClose={() =>
                    setToast(prev => ({ ...prev, isVisible: false }))
                }
                duration={3000}
            />

            {/* Recalculate Schedule Modal */}
            <RecalculateScheduleModal
                isOpen={recalculateModal.isOpen}
                onClose={() =>
                    setRecalculateModal(prev => ({ ...prev, isOpen: false }))
                }
                onConfirm={async () => {
                    try {
                        await recalculateSchedule();
                        setToast({
                            message: getString(
                                'settings',
                                'recalculate_success',
                                'Scheduled dates recalculated successfully'
                            ),
                            type: 'success',
                            isVisible: true,
                        });
                    } catch (error) {
                        console.error('Failed to recalculate schedule:', error);
                        setToast({
                            message: getString(
                                'settings',
                                'recalculate_error',
                                'Failed to recalculate scheduled dates'
                            ),
                            type: 'error',
                            isVisible: true,
                        });
                    }
                }}
                futureItemsCount={recalculateModal.futureItemsCount}
                oldInterval={recalculateModal.oldInterval}
                newInterval={recalculateModal.newInterval}
            />

            {/* Content Plan Item Sidebar - Available for both table and calendar views */}
            <ContentPlanItemSidebar />
        </div>
    );
};

// Initialize the app when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    const appContainer = document.getElementById('cpepai-app');

    if (appContainer) {
        render(
            <ContentPlanProvider>
                <App />
            </ContentPlanProvider>,
            appContainer
        );
    }
});

// Export for potential external use
export { App };
