/**
 * Content Plan Generation Modal Component
 */

import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import Select from 'react-select';
import NumericInput from 'react-numeric-input';
import { useContentPlan } from '../context/ContentPlanContext';
import { ContentPlanGenerationFormData } from '../types';
import ErrorMessage from './ErrorMessage';
import OptInPrompt from './OptInPrompt';
import { LANGUAGE_OPTIONS } from '../utils/languageOptions';

interface ContentPlanGenerationModalProps {
    isOpen: boolean;
    onClose: () => void;
}

const ContentPlanGenerationModal: React.FC<ContentPlanGenerationModalProps> = ({
    isOpen,
    onClose,
}) => {
    const {
        getString,
        saving,
        generateContentPlan,
        createMultipleContentPlanItems,
        contentPlan,
        settings,
        setCurrentTaskId,
        closeGenerationModal,
        fetchTasks,
        opted,
        optinUrl,
    } = useContentPlan();

    const [formData, setFormData] = useState<ContentPlanGenerationFormData>({
        goals: ['traffic'],
        publishInterval: 7, // Default: Publish every 7 days (not shown in UI)
        totalPosts: 10, // Total number of posts to generate
        language: 'English',
        customLanguage: '',
        customRecommendations: '',
    });

    const [errors, setErrors] = useState<{ [key: string]: string }>({});

    const [showAdvanced, setShowAdvanced] = useState<boolean>(false);
    const [latestScheduledDate, setLatestScheduledDate] = useState<
        string | null
    >(null);
    const [isGenerating, setIsGenerating] = useState<boolean>(false);
    const [errorMessage, setErrorMessage] = useState<string>('');
    const [is401Error, setIs401Error] = useState<boolean>(false);

    // Available goals
    const goalOptions = [
        {
            value: 'traffic',
            label: getString('generation_modal', 'goal_traffic', 'Traffic'),
        },
        {
            value: 'leads',
            label: getString('generation_modal', 'goal_leads', 'Leads'),
        },
        {
            value: 'authority',
            label: getString('generation_modal', 'goal_authority', 'Authority'),
        },
    ];

    const handleGoalChange = (goalValue: string, checked: boolean) => {
        setFormData(prev => ({
            ...prev,
            goals: checked
                ? [...prev.goals, goalValue]
                : prev.goals.filter(g => g !== goalValue),
        }));
    };

    const handleInputChange = (
        field: keyof ContentPlanGenerationFormData,
        value: any
    ) => {
        setFormData(prev => ({
            ...prev,
            [field]: value,
        }));

        // Clear error for this field
        if (errors[field]) {
            setErrors(prev => ({
                ...prev,
                [field]: '',
            }));
        }
    };

    const validateForm = (): boolean => {
        const newErrors: { [key: string]: string } = {};

        if (formData.goals.length === 0) {
            newErrors.goals = getString(
                'generation_modal',
                'error_goals_required',
                'Please select at least one goal'
            );
        }

        if (formData.totalPosts < 1 || formData.totalPosts > 100) {
            newErrors.totalPosts = getString(
                'generation_modal',
                'error_total_posts',
                'Total posts must be between 1 and 100'
            );
        }

        if (!formData.language) {
            newErrors.language = getString(
                'generation_modal',
                'error_language_required',
                'Please select a language'
            );
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (validateForm()) {
            setIsGenerating(true);
            setErrorMessage(''); // Clear any previous error

            try {
                // Call the context function which will handle the API call and return generated items
                const result = await generateContentPlan(formData);

                const generatedItems = result.items;
                const latestDateFromBackend = result.latestScheduledDate;
                const taskId = result.taskId;

                setLatestScheduledDate(latestDateFromBackend || null);

                // If taskId is present, set it in context (tasks panel will show in main view)
                if (taskId) {
                    setCurrentTaskId(taskId);
                    // Fetch tasks immediately to get the latest status
                    // Don't await - let it run in background so modal can close quickly
                    fetchTasks({ limit: 20 }).catch(err => {
                        console.error('Error fetching tasks:', err);
                    });
                    // Also fetch again after a delay to catch quick failures (e.g., moderation blocks)
                    // This ensures we get the error message even if the task fails very quickly
                    setTimeout(() => {
                        fetchTasks({ limit: 20 }).catch(err => {
                            console.error(
                                'Error fetching tasks (delayed):',
                                err
                            );
                        });
                    }, 1500);
                } else if (generatedItems && generatedItems.length > 0) {
                    // Automatically add all generated items to the plan
                    await createMultipleContentPlanItems(
                        generatedItems,
                        formData.publishInterval,
                        1, // planId
                        latestDateFromBackend
                    );
                }

                // Success - close the modal after generation
                handleClose();
            } catch (error: any) {
                console.error('Content generation failed:', error);

                // Extract error message from error object first
                // WordPress apiFetch may throw errors with response data nested in error.data
                let errorMsg = 'Unknown error';
                if (error && typeof error === 'object') {
                    // Check if error has response data (WordPress apiFetch structure)
                    const responseData = error.data || error;

                    // Check for error field in response
                    if (responseData.error) {
                        errorMsg = responseData.error;
                    }
                    // Check if error has a message property
                    else if (error.message) {
                        errorMsg = error.message;
                    }

                    // Check if error has validation_errors
                    else if (
                        responseData.validation_errors &&
                        typeof responseData.validation_errors === 'object'
                    ) {
                        const firstError = Object.values(
                            responseData.validation_errors
                        )[0];
                        errorMsg =
                            typeof firstError === 'string'
                                ? firstError
                                : 'Validation error';
                    }
                    // Check for message in response data
                    else if (responseData.message) {
                        errorMsg = responseData.message;
                    }
                } else if (typeof error === 'string') {
                    errorMsg = error;
                }

                // Check if this is a 401 error (unauthorized - user not opted in)
                // Check status code, error message content, or opted status
                const statusCode =
                    error?.data?.status || error?.status || error?.statusCode;
                const is401Status = statusCode === 401 || statusCode === '401';

                // Check for secret key error messages (indicates user not opted in)
                const secretKeyErrorPatterns = [
                    'Secret key not available',
                    'secret key',
                    'not opted in',
                    'not activated',
                ];
                const isSecretKeyError = secretKeyErrorPatterns.some(pattern =>
                    errorMsg.toLowerCase().includes(pattern.toLowerCase())
                );

                // Also check if user is not opted in (from context)
                const isNotOptedIn = opted === false;

                // Show opt-in UI if it's a 401, secret key error, or user is not opted in
                if (is401Status || isSecretKeyError || isNotOptedIn) {
                    setIs401Error(true);
                    setErrorMessage('');
                    return;
                }

                setIs401Error(false);

                // Check if this is a connection error and replace with friendly message
                const connectionErrorPatterns = [
                    'cURL error 7',
                    'Failed to connect',
                    "Couldn't connect to server",
                    'Connection refused',
                    'Connection timeout',
                    'Network error',
                ];
                const isConnectionError = connectionErrorPatterns.some(
                    pattern =>
                        errorMsg.toLowerCase().includes(pattern.toLowerCase())
                );

                if (isConnectionError) {
                    errorMsg = getString(
                        'generation_modal',
                        'connection_error',
                        "🚀 Houston, we have a connection problem.\n\nWe can't reach our backend right now.\n\nPlease try again in a moment or contact support if this keeps happening."
                    );
                }

                // Show error in dialog - don't close modal
                setErrorMessage(errorMsg);
            } finally {
                setIsGenerating(false);
            }
        }
    };

    const handleClose = () => {
        setFormData({
            goals: ['traffic'],
            publishInterval: 7, // Default value (not shown in UI)
            totalPosts: 12,
            language: 'English',
            customLanguage: '',
            customRecommendations: '',
        });
        setErrors({});
        setShowAdvanced(false);
        setLatestScheduledDate(null);
        setIsGenerating(false);
        setErrorMessage('');
        setIs401Error(false);
        closeGenerationModal();
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[60] overflow-y-auto">
            {/* Backdrop */}
            <div className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"></div>

            {/* Modal */}
            <div className="flex min-h-screen items-center justify-center p-3 sm:p-4">
                <div className="relative bg-white rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] flex flex-col cpepai-generation-modal mx-2 sm:mx-0">
                    {/* Header */}
                    <div className="bg-gray-100 px-4 sm:px-6 py-3 sm:py-4 rounded-t-lg flex-shrink-0">
                        <div className="flex items-center justify-between">
                            <div className="flex-1 min-w-0">
                                <h3 className="text-base sm:text-lg font-medium text-gray-900">
                                    {getString(
                                        'generation_modal',
                                        'title',
                                        'Generate Content Plan'
                                    )}
                                </h3>
                                <p className="text-xs sm:text-sm text-gray-600 mt-1">
                                    {getString(
                                        'generation_modal',
                                        'subtitle',
                                        'Configure your content plan generation settings'
                                    )}
                                </p>
                            </div>
                        </div>
                    </div>

                    {/* Content */}
                    <div className="cpepai-form flex flex-col flex-1 min-h-0">
                        {/* Parameters Form */}
                        <div className="flex-1 min-h-0 overflow-y-auto">
                            {/* Top Section - Form Controls */}
                            <div className="px-4 sm:px-6 py-3 sm:py-4">
                                <div className="space-y-4 sm:space-y-6">
                                    {/* Goals */}
                                    <div>
                                        <label className="block text-xs sm:text-sm font-medium text-gray-900 mb-2 sm:mb-3">
                                            {getString(
                                                'generation_modal',
                                                'goals_label',
                                                'Goals'
                                            )}
                                            <span className="text-red-500 ml-1">
                                                *
                                            </span>
                                        </label>
                                        <div className="space-y-2">
                                            {goalOptions.map(goal => (
                                                <label
                                                    key={goal.value}
                                                    className="flex items-center"
                                                >
                                                    <input
                                                        type="checkbox"
                                                        checked={formData.goals.includes(
                                                            goal.value
                                                        )}
                                                        onChange={e =>
                                                            handleGoalChange(
                                                                goal.value,
                                                                e.target.checked
                                                            )
                                                        }
                                                        className="mr-2 sm:mr-3 text-primary focus:ring-primary border-gray-300 rounded"
                                                    />
                                                    <span className="text-xs sm:text-sm text-gray-900">
                                                        {goal.label}
                                                    </span>
                                                </label>
                                            ))}
                                        </div>
                                        {errors.goals && (
                                            <p className="cpepai-form-error text-xs sm:text-sm">
                                                {errors.goals}
                                            </p>
                                        )}
                                    </div>

                                    {/* Total Posts */}
                                    <div className="cpepai-form-group">
                                        <label
                                            htmlFor="totalPosts"
                                            className="cpepai-form-label text-xs sm:text-sm"
                                        >
                                            {getString(
                                                'generation_modal',
                                                'total_posts_label',
                                                'Total number of posts to generate'
                                            )}
                                            <span className="text-red-500 ml-1">
                                                *
                                            </span>
                                        </label>
                                        <div className="w-full md:w-auto">
                                            <NumericInput
                                                id="totalPosts"
                                                value={formData.totalPosts}
                                                onChange={(
                                                    value: number | null
                                                ) =>
                                                    handleInputChange(
                                                        'totalPosts',
                                                        value ?? 1
                                                    )
                                                }
                                                min={1}
                                                max={100}
                                                step={1}
                                                precision={0}
                                                mobile={false}
                                            />
                                        </div>
                                        {errors.totalPosts && (
                                            <p className="cpepai-form-error text-xs sm:text-sm">
                                                {errors.totalPosts}
                                            </p>
                                        )}
                                    </div>

                                    {/* Language */}
                                    <div className="cpepai-form-group">
                                        <label
                                            htmlFor="language"
                                            className="cpepai-form-label text-xs sm:text-sm"
                                        >
                                            {getString(
                                                'generation_modal',
                                                'language_label',
                                                'Language'
                                            )}
                                            <span className="text-red-500 ml-1">
                                                *
                                            </span>
                                        </label>
                                        <Select
                                            id="language"
                                            value={LANGUAGE_OPTIONS.find(
                                                option =>
                                                    option.value ===
                                                    formData.language
                                            )}
                                            onChange={selectedOption => {
                                                const value =
                                                    selectedOption?.value ||
                                                    'English';
                                                handleInputChange(
                                                    'language',
                                                    value
                                                );
                                            }}
                                            options={LANGUAGE_OPTIONS}
                                            isSearchable={false}
                                            placeholder={getString(
                                                'generation_modal',
                                                'language_placeholder',
                                                'Select a language'
                                            )}
                                            className="react-select-container"
                                            classNamePrefix="react-select"
                                        />
                                        {errors.language && (
                                            <p className="cpepai-form-error text-xs sm:text-sm">
                                                {errors.language}
                                            </p>
                                        )}
                                    </div>

                                    {/* Advanced Section */}
                                    <div className="cpepai-form-group">
                                        <button
                                            type="button"
                                            onClick={() =>
                                                setShowAdvanced(!showAdvanced)
                                            }
                                            className="text-xs sm:text-sm text-blue-600 hover:text-blue-800 underline focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded"
                                        >
                                            {getString(
                                                'generation_modal',
                                                'advanced_link',
                                                'Advanced'
                                            )}
                                        </button>

                                        {showAdvanced && (
                                            <div className="mt-2 sm:mt-3">
                                                <label
                                                    htmlFor="customRecommendations"
                                                    className="cpepai-form-label text-xs sm:text-sm"
                                                >
                                                    {getString(
                                                        'generation_modal',
                                                        'custom_recommendations_label',
                                                        'Custom Recommendations'
                                                    )}
                                                </label>
                                                <textarea
                                                    id="customRecommendations"
                                                    value={
                                                        formData.customRecommendations
                                                    }
                                                    onChange={e =>
                                                        handleInputChange(
                                                            'customRecommendations',
                                                            e.target.value
                                                        )
                                                    }
                                                    className="cpepai-form-input w-full px-2 sm:px-3 py-2 sm:py-3 text-sm sm:text-base min-h-[80px] sm:min-h-[100px] resize-y"
                                                    placeholder={getString(
                                                        'generation_modal',
                                                        'custom_recommendations_placeholder',
                                                        'Enter any specific recommendations or requirements for the content plan...'
                                                    )}
                                                    rows={4}
                                                />
                                                <p className="text-xs text-gray-500 mt-1">
                                                    {getString(
                                                        'generation_modal',
                                                        'custom_recommendations_help',
                                                        'Optional: Provide specific guidance, topics to focus on, or requirements for the generated content plan.'
                                                    )}
                                                </p>
                                            </div>
                                        )}
                                    </div>

                                    {/* Error Message Display or Opt-In UI for 401 */}
                                    {is401Error ? (
                                        <OptInPrompt
                                            getString={getString}
                                            optinUrl={optinUrl}
                                        />
                                    ) : errorMessage ? (
                                        <ErrorMessage
                                            message={errorMessage}
                                            title={getString(
                                                'generation_modal',
                                                'error_title',
                                                'Generation Failed'
                                            )}
                                        />
                                    ) : null}
                                </div>
                            </div>
                        </div>

                        {/* Footer Actions */}
                        <div className="px-4 sm:px-6 py-3 border-t border-gray-200 flex flex-col sm:flex-row justify-end items-stretch sm:items-center gap-2 sm:gap-3 sm:space-x-0 flex-shrink-0">
                            <button
                                type="button"
                                onClick={handleClose}
                                className="cpepai-button cpepai-button--secondary w-full sm:w-auto"
                                disabled={saving || isGenerating}
                            >
                                {getString(
                                    'generation_modal',
                                    'cancel',
                                    'Cancel'
                                )}
                            </button>
                            <button
                                type="button"
                                onClick={handleSubmit}
                                className="cpepai-button cpepai-button--primary w-full sm:w-auto"
                                disabled={saving || isGenerating}
                            >
                                {isGenerating
                                    ? getString(
                                          'generation_modal',
                                          'generating',
                                          'Generating...'
                                      )
                                    : getString(
                                          'generation_modal',
                                          'generate',
                                          'Generate'
                                      )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ContentPlanGenerationModal;
