/**
 * Generate Post Modal Component
 *
 * Modal for generating content for a specific planned post
 */

import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useContentPlan } from '../context/ContentPlanContext';
import { ContentPlanItem } from '../types';
import StructureDisplay from './StructureDisplay';
import KeywordDisplay from './KeywordDisplay';
import OptInPrompt from './OptInPrompt';

interface GeneratePostModalProps {
    isOpen: boolean;
    onClose: () => void;
    item: ContentPlanItem | null;
}

const GeneratePostModal: React.FC<GeneratePostModalProps> = ({
    isOpen,
    onClose,
    item,
}) => {
    const {
        getString,
        settings,
        setCurrentTaskId,
        fetchTasks,
        addFailedTask,
        refreshUsage,
        opted,
        optinUrl,
    } = useContentPlan();

    // Dev mode detection - check settings from API first, then fallback to URL/localStorage
    const isDevMode = () => {
        // First check the settings from API
        if (settings.dev_mode === true) {
            return true;
        }

        // Fallback to URL parameter or localStorage
        const urlParams = new URLSearchParams(window.location.search);
        return (
            urlParams.get('dev') === 'true' ||
            localStorage.getItem('cpepai-dev-mode') === 'true'
        );
    };

    const [devModePrompt, setDevModePrompt] = useState<string>('');
    const [showDevPrompt, setShowDevPrompt] = useState<boolean>(false);
    const [isGenerating, setIsGenerating] = useState<boolean>(false);
    const [errorMessage, setErrorMessage] = useState<string>('');
    const [is401Error, setIs401Error] = useState<boolean>(false);
    const [regenerationInstructions, setRegenerationInstructions] =
        useState<string>('');

    const handleGenerate = async () => {
        if (!item) return;

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

        try {
            // Make API call to generate post
            const requestBody: any = {};
            if (regenerationInstructions.trim()) {
                requestBody.regeneration_instructions =
                    regenerationInstructions.trim();
            }

            const result: any = await apiFetch({
                path: `/cpepai/v1/items/${item.id}/generate-post`,
                method: 'POST',
                data: requestBody,
            });

            // Check for error responses - API might return error object even with 200 status
            // Check for error field, status_code indicating error (4xx, 5xx), or success === false
            const hasError =
                result.error ||
                (result.status_code && result.status_code >= 400) ||
                result.success === false;

            if (hasError) {
                // Extract error message from various possible locations
                let errorMsg =
                    result.error ||
                    result.message ||
                    (result.validation_errors &&
                    typeof result.validation_errors === 'object'
                        ? (Object.values(result.validation_errors)[0] as string)
                        : null) ||
                    'Failed to generate post content';

                // Check if this is a 401 error (unauthorized - user not opted in)
                const statusCode = result.status_code;
                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('');
                    setIsGenerating(false);
                    return;
                }

                // Show error in dialog - don't close modal or create task
                setIs401Error(false);
                setErrorMessage(errorMsg);
                setIsGenerating(false);
                return;
            }

            // Extract taskId from response (could be at top level or in data)
            const taskId = result.taskId || result.data?.taskId;

            // Only proceed if we have a taskId (successful task creation)
            if (!taskId) {
                // No taskId means task wasn't created - treat as error
                const errorMsg =
                    result.message || 'Failed to create generation task';
                setErrorMessage(errorMsg);
                setIsGenerating(false);
                return;
            }

            // Success - close modal and proceed with task tracking
            onClose();

            // Smoothly scroll to top of the page
            window.scrollTo({ top: 0, behavior: 'smooth' });

            setCurrentTaskId(taskId);
            // Fetch tasks immediately to show the newly created task
            fetchTasks({ limit: 20 });
            // Also fetch again after a short 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 });
            }, 1000);
            // Refresh usage data after generating post
            refreshUsage().catch(err => {
                console.error(
                    'Error refreshing usage after post generation:',
                    err
                );
            });
        } catch (error: any) {
            console.error('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(
                    'generate_post_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 or create task
            setErrorMessage(errorMsg);
        } finally {
            setIsGenerating(false);
        }
    };

    const handleClose = () => {
        setDevModePrompt('');
        setShowDevPrompt(false);
        setIsGenerating(false);
        setErrorMessage('');
        setIs401Error(false);
        setRegenerationInstructions('');
        onClose();
    };

    if (!isOpen || !item) 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"
                onClick={handleClose}
            ></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-2xl w-full max-h-[90vh] flex flex-col 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-start sm:items-center justify-between gap-2">
                            <div className="flex-1 min-w-0">
                                <h3 className="text-base sm:text-lg font-medium text-gray-900">
                                    {getString(
                                        'generate_post_modal',
                                        'title',
                                        'Generate Post Content'
                                    )}
                                </h3>
                                <p className="text-xs sm:text-sm text-gray-600 mt-1">
                                    {getString(
                                        'generate_post_modal',
                                        'subtitle',
                                        'Generate AI-powered content for this planned post'
                                    )}
                                </p>
                            </div>
                            <div className="flex items-center gap-2 flex-shrink-0">
                                {isDevMode() && (
                                    <div className="flex items-center bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-xs font-medium">
                                        <svg
                                            className="w-3 h-3 mr-1"
                                            fill="currentColor"
                                            viewBox="0 0 20 20"
                                        >
                                            <path
                                                fillRule="evenodd"
                                                d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                                                clipRule="evenodd"
                                            />
                                        </svg>
                                        <span className="hidden sm:inline">
                                            DEV MODE{' '}
                                            {settings.dev_mode
                                                ? '(Settings)'
                                                : '(Fallback)'}
                                        </span>
                                        <span className="sm:hidden">DEV</span>
                                    </div>
                                )}
                                <button
                                    onClick={handleClose}
                                    className="text-gray-400 hover:text-gray-500 focus:outline-none"
                                >
                                    <svg
                                        className="h-5 w-5 sm:h-6 sm:w-6"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M6 18L18 6M6 6l12 12"
                                        />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Content */}
                    <div className="flex-1 overflow-y-auto px-4 sm:px-6 py-4 sm:py-6">
                        <div className="space-y-4 sm:space-y-6">
                            {/* Post Title */}
                            <div>
                                <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">
                                    {getString(
                                        'generate_post_modal',
                                        'post_title',
                                        'Post Title'
                                    )}
                                </label>
                                <div className="text-sm sm:text-base text-gray-900 font-medium break-words">
                                    {item.title ||
                                        getString(
                                            'table_cells',
                                            'untitled',
                                            'Untitled'
                                        )}
                                </div>
                            </div>

                            {/* Post Structure */}
                            <div>
                                <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">
                                    {getString(
                                        'generate_post_modal',
                                        'post_structure',
                                        'Content Structure'
                                    )}
                                </label>
                                <StructureDisplay
                                    structure={item.structure}
                                    getString={getString}
                                    maxWidth="max-w-full"
                                    layout="vertical"
                                />
                            </div>

                            {/* Keywords (optional) */}
                            <div>
                                <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">
                                    {getString(
                                        'generate_post_modal',
                                        'keywords',
                                        'Keywords'
                                    )}
                                </label>
                                <KeywordDisplay
                                    keywords={item.keywords}
                                    getString={getString}
                                    maxWidth="max-w-full"
                                    alwaysShowAll={true}
                                />
                            </div>

                            {/* Scheduled Date (optional) */}
                            {item.scheduled_on && (
                                <div>
                                    <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">
                                        {getString(
                                            'generate_post_modal',
                                            'scheduled_on',
                                            'Scheduled On'
                                        )}
                                    </label>
                                    <div className="text-xs sm:text-sm text-gray-900">
                                        {new Date(
                                            item.scheduled_on
                                        ).toLocaleDateString()}
                                    </div>
                                </div>
                            )}

                            {/* Regeneration Instructions - Only show if item already has a post (regeneration) */}
                            {item.post && (
                                <div>
                                    <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1 sm:mb-2">
                                        {getString(
                                            'generate_post_modal',
                                            'regeneration_instructions',
                                            'What would you like to change? (Optional)'
                                        )}
                                    </label>
                                    <textarea
                                        value={regenerationInstructions}
                                        onChange={e =>
                                            setRegenerationInstructions(
                                                e.target.value
                                            )
                                        }
                                        placeholder={getString(
                                            'generate_post_modal',
                                            'regeneration_instructions_placeholder',
                                            'Describe what you want to change or improve in the generated content...'
                                        )}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm sm:text-base"
                                        rows={4}
                                        disabled={isGenerating}
                                    />
                                    <p className="mt-1 text-xs text-gray-500">
                                        {getString(
                                            'generate_post_modal',
                                            'regeneration_instructions_help',
                                            'Specify what you want to change or improve in the regenerated content'
                                        )}
                                    </p>
                                </div>
                            )}

                            {/* Error Message Display or Opt-In UI for 401 */}
                            {is401Error ? (
                                <OptInPrompt
                                    getString={getString}
                                    optinUrl={optinUrl}
                                />
                            ) : errorMessage ? (
                                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                                    <div className="flex items-start">
                                        <div className="flex-shrink-0">
                                            <svg
                                                className="h-5 w-5 text-red-400"
                                                viewBox="0 0 20 20"
                                                fill="currentColor"
                                            >
                                                <path
                                                    fillRule="evenodd"
                                                    d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                                                    clipRule="evenodd"
                                                />
                                            </svg>
                                        </div>
                                        <div className="ml-3 flex-1">
                                            <h3 className="text-sm font-medium text-red-800">
                                                {getString(
                                                    'generate_post_modal',
                                                    'error_title',
                                                    'Generation Failed'
                                                )}
                                            </h3>
                                            <div className="mt-2 text-sm text-red-700 whitespace-pre-line">
                                                {errorMessage}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ) : null}

                            {/* Dev Mode Prompt Display */}
                            {isDevMode() && showDevPrompt && (
                                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                    <div className="flex items-center mb-3">
                                        <div className="flex-shrink-0">
                                            <svg
                                                className="h-5 w-5 text-yellow-400"
                                                viewBox="0 0 20 20"
                                                fill="currentColor"
                                            >
                                                <path
                                                    fillRule="evenodd"
                                                    d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                                                    clipRule="evenodd"
                                                />
                                            </svg>
                                        </div>
                                        <div className="ml-3">
                                            <h3 className="text-sm font-medium text-yellow-800">
                                                Dev Mode - Generation Info
                                            </h3>
                                        </div>
                                    </div>
                                    <div className="mt-2">
                                        <pre className="text-sm text-yellow-700 whitespace-pre-wrap bg-yellow-100 p-3 rounded border max-h-96 overflow-y-auto font-mono">
                                            {devModePrompt}
                                        </pre>
                                    </div>
                                    <div className="mt-3 flex justify-between">
                                        <button
                                            type="button"
                                            onClick={() => {
                                                navigator.clipboard.writeText(
                                                    devModePrompt
                                                );
                                            }}
                                            className="text-sm bg-blue-200 hover:bg-blue-300 text-blue-800 px-3 py-1 rounded transition-colors"
                                        >
                                            Copy to Clipboard
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setShowDevPrompt(false);
                                                setDevModePrompt('');
                                            }}
                                            className="text-sm bg-yellow-200 hover:bg-yellow-300 text-yellow-800 px-3 py-1 rounded transition-colors"
                                        >
                                            Hide Info
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Footer Actions */}
                    <div className="px-4 sm:px-6 py-3 sm:py-4 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={isGenerating}
                        >
                            {getString(
                                'generate_post_modal',
                                'cancel',
                                'Cancel'
                            )}
                        </button>
                        <button
                            type="button"
                            onClick={handleGenerate}
                            className="cpepai-button cpepai-button--primary flex items-center justify-center gap-2 w-full sm:w-auto"
                            disabled={isGenerating}
                        >
                            <svg
                                className="w-4 h-4"
                                fill="none"
                                stroke="currentColor"
                                viewBox="0 0 24 24"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
                                />
                            </svg>
                            {isGenerating
                                ? getString(
                                      'generate_post_modal',
                                      'generating',
                                      'Generating...'
                                  )
                                : getString(
                                      'generate_post_modal',
                                      'generate',
                                      'Generate'
                                  )}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default GeneratePostModal;
