import { useState, useEffect } from '@wordpress/element';
import api from '../utils/api';

const { __ } = wp.i18n;

const STEPS = [
    { id: 1, label: __('What to Write', 'ai-bulk-post') },
    { id: 2, label: __('AI Provider', 'ai-bulk-post') },
    { id: 3, label: __('Prompts', 'ai-bulk-post') },
    { id: 4, label: __('Schedule', 'ai-bulk-post') },
    { id: 5, label: __('Publish', 'ai-bulk-post') },
];

const CONTENT_LENGTH_OPTIONS = [
    { value: 400, label: __('Short', 'ai-bulk-post'), desc: __('~300 words', 'ai-bulk-post') },
    { value: 800, label: __('Medium', 'ai-bulk-post'), desc: __('~600 words', 'ai-bulk-post') },
    { value: 1500, label: __('Long', 'ai-bulk-post'), desc: __('~1000 words', 'ai-bulk-post') },
    { value: 3000, label: __('Very Long', 'ai-bulk-post'), desc: __('~2000 words', 'ai-bulk-post') },
];

const PROMPT_PRESETS = {
    blog: {
        label: __('Blog Post', 'ai-bulk-post'),
        title: __('Write one engaging blog post title about [subject].', 'ai-bulk-post'),
        content: __('Write a comprehensive blog post about [subject]. Use HTML headings (h2, h3), bullet points, and clear paragraphs. Target length is [length] words. Include an introduction, main content sections, and a conclusion.', 'ai-bulk-post'),
    },
    news: {
        label: __('News Article', 'ai-bulk-post'),
        title: __('Write a news headline about [subject].', 'ai-bulk-post'),
        content: __('Write a factual news article about [subject]. Use journalistic style with inverted pyramid structure. Include who, what, when, where, why. Target length is [length] words.', 'ai-bulk-post'),
    },
    review: {
        label: __('Product Review', 'ai-bulk-post'),
        title: __('Write a product review title for [subject].', 'ai-bulk-post'),
        content: __('Write a detailed product review about [subject]. Include pros, cons, features, and a final verdict. Use HTML formatting with headings. Target length is [length] words.', 'ai-bulk-post'),
    },
    tutorial: {
        label: __('Tutorial', 'ai-bulk-post'),
        title: __('Write a how-to tutorial title about [subject].', 'ai-bulk-post'),
        content: __('Write a step-by-step tutorial about [subject]. Use numbered steps, code examples where relevant, and clear explanations. Target length is [length] words.', 'ai-bulk-post'),
    },
};

const PROVIDER_NAMES = {
    openai: 'OpenAI',
    google: 'Google Gemini',
    grok: 'Grok',
    deepseek: 'DeepSeek',
};

const POST_TYPES = {
    post: __('Posts', 'ai-bulk-post'),
    page: __('Pages', 'ai-bulk-post'),
};

const defaultData = {
    title: '',
    provider: 'openai',
    model: 'gpt-5.6-luna',
    subject: '',
    length: 800,
    prompt_title: 'Write one blog post title about [subject].',
    prompt_content:
        'Write blog post about [subject]. Use html characters and subheadings. And content length should be [length] words.',
    recurrence_type: 'interval',
    recurrence_interval: 1,
    recurrence_days: [],
    recurrence_time: '09:00',
    post_type: 'post',
    post_status: 'publish',
    categories: [],
    temperature: 0.7,
    max_tokens: 800,
};

const dayOptions = [
    { value: 'sun', label: __('Sun', 'ai-bulk-post') },
    { value: 'mon', label: __('Mon', 'ai-bulk-post') },
    { value: 'tue', label: __('Tue', 'ai-bulk-post') },
    { value: 'wed', label: __('Wed', 'ai-bulk-post') },
    { value: 'thu', label: __('Thu', 'ai-bulk-post') },
    { value: 'fri', label: __('Fri', 'ai-bulk-post') },
    { value: 'sat', label: __('Sat', 'ai-bulk-post') },
];

const getCreativityLabel = (value) => {
    if (value <= 0.3) return __('Factual', 'ai-bulk-post');
    if (value <= 0.8) return __('Balanced', 'ai-bulk-post');
    if (value <= 1.3) return __('Creative', 'ai-bulk-post');
    return __('Very Creative', 'ai-bulk-post');
};

const getClosestLengthOption = (value) => {
    return CONTENT_LENGTH_OPTIONS.reduce((prev, curr) =>
        Math.abs(curr.value - value) < Math.abs(prev.value - value) ? curr : prev
    );
};

const getCreativityTip = (value) => {
    if (value <= 0.3) return __('Sticks closely to facts and instructions', 'ai-bulk-post');
    if (value <= 0.8) return __('Balanced between accuracy and creativity', 'ai-bulk-post');
    if (value <= 1.3) return __('More varied and creative output', 'ai-bulk-post');
    return __('Highly creative, may deviate from source', 'ai-bulk-post');
};

export default function AgentForm({ agent, onSave, onClose }) {
    const [data, setData] = useState(defaultData);
    const [models, setModels] = useState({});
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [errors, setErrors] = useState({});
    const [currentStep, setCurrentStep] = useState(1);

    const hasProviders = Object.keys(models).length > 0;

    useEffect(() => {
        loadData();
        if (agent) {
            setData((prev) => ({
                ...prev,
                ...agent,
                categories: agent.categories || [],
                recurrence_days: agent.recurrence_days || [],
            }));
        }
    }, [agent]);

    const loadData = async () => {
        setLoading(true);
        try {
            const [modelsResult, catsResult] = await Promise.allSettled([
                api.getModels(),
                api.getCategories(),
            ]);
            if (modelsResult.status === 'fulfilled') {
                setModels(modelsResult.value);
            } else {
                console.error('Failed to load models:', modelsResult.reason);
            }
            if (catsResult.status === 'fulfilled') {
                setCategories(catsResult.value);
            } else {
                console.error('Failed to load categories:', catsResult.reason);
            }
        } catch (err) {
            console.error('Failed to load form data:', err);
        } finally {
            setLoading(false);
        }
    };

    const update = (field, value) => {
        setData((prev) => ({ ...prev, [field]: value }));
        setErrors((prev) => ({ ...prev, [field]: null }));
    };

    const validateStep = (step) => {
        const newErrors = {};

        if (step === 1) {
            if (!data.title.trim())
                newErrors.title = __('Title is required.', 'ai-bulk-post');
            if (!data.subject.trim())
                newErrors.subject = __('Subject is required.', 'ai-bulk-post');
        }

        if (step === 3) {
            if (!data.prompt_title.trim())
                newErrors.prompt_title = __('Title prompt is required.', 'ai-bulk-post');
            if (!data.prompt_content.trim())
                newErrors.prompt_content = __(
                    'Content prompt is required.',
                    'ai-bulk-post'
                );
        }

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

    const handleNext = () => {
        if (validateStep(currentStep)) {
            setCurrentStep((prev) => Math.min(prev + 1, 5));
        }
    };

    const handleBack = () => {
        setCurrentStep((prev) => Math.max(prev - 1, 1));
    };

    const handleSubmit = async () => {
        if (!validateStep(currentStep)) return;

        setSaving(true);
        try {
            await onSave(data);
        } catch (err) {
            setErrors({ submit: err.message });
        } finally {
            setSaving(false);
        }
    };

    const toggleDay = (day) => {
        const days = data.recurrence_days.includes(day)
            ? data.recurrence_days.filter((d) => d !== day)
            : [...data.recurrence_days, day];
        update('recurrence_days', days);
    };

    const applyPreset = (presetKey) => {
        const preset = PROMPT_PRESETS[presetKey];
        if (preset) {
            update('prompt_title', preset.title);
            update('prompt_content', preset.content);
        }
    };

    const renderStepContent = () => {
        if (loading) {
            return (
                <div className="aibp-loading">
                    <span className="spinner is-active" />
                    {__('Loading...', 'ai-bulk-post')}
                </div>
            );
        }

        switch (currentStep) {
            case 1:
                return (
                    <div className="aibp-step-content">
                        <div className="aibp-form-field">
                            <label htmlFor="aibp-title">
                                {__('Agent Name', 'ai-bulk-post')} *
                            </label>
                            <input
                                id="aibp-title"
                                type="text"
                                value={data.title}
                                onChange={(e) => update('title', e.target.value)}
                                placeholder={__(
                                    'e.g., Daily Tech News Bot',
                                    'ai-bulk-post'
                                )}
                                className={errors.title ? 'aibp-input-error' : ''}
                            />
                            {errors.title && (
                                <span className="aibp-error">{errors.title}</span>
                            )}
                        </div>

                        <div className="aibp-form-field">
                            <label htmlFor="aibp-subject">
                                {__('Post Topic', 'ai-bulk-post')} *
                            </label>
                            <input
                                id="aibp-subject"
                                type="text"
                                value={data.subject}
                                onChange={(e) => update('subject', e.target.value)}
                                placeholder={__(
                                    'What should the agent write about?',
                                    'ai-bulk-post'
                                )}
                                className={errors.subject ? 'aibp-input-error' : ''}
                            />
                            {errors.subject && (
                                <span className="aibp-error">{errors.subject}</span>
                            )}
                        </div>
                    </div>
                );

            case 2:
                return (
                    <div className="aibp-step-content">
                        {!hasProviders && (
                            <div className="aibp-notice aibp-notice-error">
                                {__(
                                    'No AI providers configured. Please add at least one API key in the Settings tab first.',
                                    'ai-bulk-post'
                                )}
                            </div>
                        )}

                        <div className="aibp-form-row">
                            <div className="aibp-form-field">
                                <label htmlFor="aibp-provider">
                                    {__('AI Provider', 'ai-bulk-post')}
                                </label>
                                <select
                                    id="aibp-provider"
                                    className="regular-text"
                                    value={data.provider}
                                    disabled={!hasProviders}
                                    onChange={(e) => {
                                        update('provider', e.target.value);
                                        const firstModel = Object.keys(
                                            models[e.target.value] || {}
                                        )[0];
                                        if (firstModel) update('model', firstModel);
                                    }}
                                >
                                    {Object.keys(models).map((p) => (
                                        <option key={p} value={p}>
                                            {PROVIDER_NAMES[p] || p}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div className="aibp-form-field">
                                <label htmlFor="aibp-model">
                                    {__('Model', 'ai-bulk-post')}
                                </label>
                                <select
                                    id="aibp-model"
                                    className="regular-text"
                                    value={data.model}
                                    disabled={!hasProviders}
                                    onChange={(e) => update('model', e.target.value)}
                                >
                                    {Object.entries(models[data.provider] || {}).map(
                                        ([id, model]) => (
                                            <option key={id} value={id}>
                                                {model.name}
                                            </option>
                                        )
                                    )}
                                </select>
                            </div>
                        </div>

                        <div className="aibp-form-field">
                            <label>
                                {__('Creativity', 'ai-bulk-post')}
                                <span className="aibp-label-value">
                                    {data.temperature.toFixed(1)} —{' '}
                                    {getCreativityLabel(data.temperature)}
                                </span>
                            </label>
                            <div className="aibp-creativity-slider">
                                <input
                                    type="range"
                                    min="0"
                                    max="2"
                                    step="0.1"
                                    value={data.temperature}
                                    onChange={(e) =>
                                        update('temperature', parseFloat(e.target.value))
                                    }
                                />
                                <div className="aibp-creativity-labels">
                                    <span>{__('Factual', 'ai-bulk-post')}</span>
                                    <span>{__('Balanced', 'ai-bulk-post')}</span>
                                    <span>{__('Creative', 'ai-bulk-post')}</span>
                                </div>
                            </div>
                            <p className="description">
                                {getCreativityTip(data.temperature)}
                            </p>
                        </div>

                        <div className="aibp-form-field">
                            <label>
                                {__('Content Length', 'ai-bulk-post')}
                                <span className="aibp-label-value">
                                    {data.max_tokens} —{' '}
                                    {getClosestLengthOption(data.max_tokens).label} (
                                    {getClosestLengthOption(data.max_tokens).desc})
                                </span>
                            </label>
                            <div className="aibp-creativity-slider">
                                <input
                                    type="range"
                                    min="400"
                                    max="3000"
                                    step="100"
                                    value={data.max_tokens}
                                    onChange={(e) =>
                                        update('max_tokens', parseInt(e.target.value, 10))
                                    }
                                />
                                <div className="aibp-creativity-labels">
                                    <span>{__('Short', 'ai-bulk-post')}</span>
                                    <span>{__('Medium', 'ai-bulk-post')}</span>
                                    <span>{__('Long', 'ai-bulk-post')}</span>
                                    <span>{__('Very Long', 'ai-bulk-post')}</span>
                                </div>
                            </div>
                            <p className="description">
                                {__(
                                    'Approximate word count will be close to the target length.',
                                    'ai-bulk-post'
                                )}
                            </p>
                        </div>
                    </div>
                );

            case 3:
                return (
                    <div className="aibp-step-content">
                        <div className="aibp-form-field">
                            <label>{__('Prompt Preset', 'ai-bulk-post')}</label>
                            <div className="aibp-preset-list">
                                {Object.entries(PROMPT_PRESETS).map(([key, preset]) => (
                                    <button
                                        key={key}
                                        type="button"
                                        className="button aibp-preset-btn"
                                        onClick={() => applyPreset(key)}
                                    >
                                        {preset.label}
                                    </button>
                                ))}
                            </div>
                            <p className="description">
                                {__(
                                    'Choose a preset to auto-fill prompts, or customize below.',
                                    'ai-bulk-post'
                                )}
                            </p>
                        </div>

                        <div className="aibp-form-field">
                            <label htmlFor="aibp-prompt-title">
                                {__('Title Prompt', 'ai-bulk-post')} *
                            </label>
                            <input
                                id="aibp-prompt-title"
                                type="text"
                                className={`regular-text ${errors.prompt_title ? 'aibp-input-error' : ''}`}
                                value={data.prompt_title}
                                onChange={(e) =>
                                    update('prompt_title', e.target.value)
                                }
                            />
                            {errors.prompt_title && (
                                <span className="aibp-error">
                                    {errors.prompt_title}
                                </span>
                            )}
                            <p className="description">
                                {__('Use [subject] as placeholder.', 'ai-bulk-post')}
                            </p>
                        </div>

                        <div className="aibp-form-field">
                            <label htmlFor="aibp-prompt-content">
                                {__('Content Prompt', 'ai-bulk-post')} *
                            </label>
                            <textarea
                                id="aibp-prompt-content"
                                rows="5"
                                className={errors.prompt_content ? 'aibp-input-error' : ''}
                                value={data.prompt_content}
                                onChange={(e) =>
                                    update('prompt_content', e.target.value)
                                }
                            />
                            {errors.prompt_content && (
                                <span className="aibp-error">
                                    {errors.prompt_content}
                                </span>
                            )}
                            <p className="description">
                                {__(
                                    'Use [subject] and [length] as placeholders.',
                                    'ai-bulk-post'
                                )}
                            </p>
                        </div>
                    </div>
                );

            case 4:
                return (
                    <div className="aibp-step-content">
                        <div className="aibp-form-field">
                            <div className="aibp-radio-group">
                                <label className="aibp-radio-label">
                                    <input
                                        type="radio"
                                        name="recurrence_type"
                                        value="interval"
                                        checked={data.recurrence_type === 'interval'}
                                        onChange={() =>
                                            update('recurrence_type', 'interval')
                                        }
                                    />
                                    {__('Every N days', 'ai-bulk-post')}
                                </label>
                                <label className="aibp-radio-label">
                                    <input
                                        type="radio"
                                        name="recurrence_type"
                                        value="schedule"
                                        checked={data.recurrence_type === 'schedule'}
                                        onChange={() =>
                                            update('recurrence_type', 'schedule')
                                        }
                                    />
                                    {__('Specific days', 'ai-bulk-post')}
                                </label>
                            </div>
                        </div>

                        {data.recurrence_type === 'interval' && (
                            <div className="aibp-form-row">
                                <div className="aibp-form-field">
                                    <label htmlFor="aibp-interval">
                                        {__('Every', 'ai-bulk-post')}
                                    </label>
                                    <input
                                        id="aibp-interval"
                                        type="number"
                                        min="1"
                                        max="365"
                                        value={data.recurrence_interval}
                                        onChange={(e) =>
                                            update(
                                                'recurrence_interval',
                                                parseInt(e.target.value, 10)
                                            )
                                        }
                                    />
                                    <span className="aibp-form-field-suffix">
                                        {__('days', 'ai-bulk-post')}
                                    </span>
                                </div>
                                <div className="aibp-form-field">
                                    <label htmlFor="aibp-time-interval">
                                        {__('at', 'ai-bulk-post')}
                                    </label>
                                    <input
                                        id="aibp-time-interval"
                                        type="time"
                                        value={data.recurrence_time}
                                        onChange={(e) =>
                                            update('recurrence_time', e.target.value)
                                        }
                                    />
                                </div>
                            </div>
                        )}

                        {data.recurrence_type === 'schedule' && (
                            <div className="aibp-form-field">
                                <label>{__('Run on', 'ai-bulk-post')}</label>
                                <div className="aibp-day-picker">
                                    {dayOptions.map((day) => (
                                        <button
                                            key={day.value}
                                            type="button"
                                            className={`aibp-day-btn ${
                                                data.recurrence_days.includes(day.value)
                                                    ? 'aibp-day-active'
                                                    : ''
                                            }`}
                                            onClick={() => toggleDay(day.value)}
                                        >
                                            {day.label}
                                        </button>
                                    ))}
                                </div>
                                <div
                                    className="aibp-form-field"
                                    style={{ marginTop: '8px' }}
                                >
                                    <label htmlFor="aibp-time-schedule">
                                        {__('at', 'ai-bulk-post')}
                                    </label>
                                    <input
                                        id="aibp-time-schedule"
                                        type="time"
                                        value={data.recurrence_time}
                                        onChange={(e) =>
                                            update('recurrence_time', e.target.value)
                                        }
                                    />
                                </div>
                            </div>
                        )}
                    </div>
                );

            case 5:
                return (
                    <div className="aibp-step-content">
                        <div className="aibp-form-field aibp-form-field-full">
                            <label htmlFor="aibp-post-type">
                                {__('Post Type', 'ai-bulk-post')}
                            </label>
                            <select
                                id="aibp-post-type"
                                className="regular-text"
                                value={data.post_type}
                                onChange={(e) => update('post_type', e.target.value)}
                            >
                                {Object.entries(POST_TYPES).map(([slug, label]) => (
                                    <option key={slug} value={slug}>
                                        {label}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="aibp-form-field aibp-form-field-full">
                            <label htmlFor="aibp-post-status">
                                {__('Post Status', 'ai-bulk-post')}
                            </label>
                            <select
                                id="aibp-post-status"
                                className="regular-text"
                                value={data.post_status}
                                onChange={(e) =>
                                    update('post_status', e.target.value)
                                }
                            >
                                <option value="publish">
                                    {__('Publish', 'ai-bulk-post')}
                                </option>
                                <option value="draft">
                                    {__('Draft', 'ai-bulk-post')}
                                </option>
                                <option value="pending">
                                    {__('Pending Review', 'ai-bulk-post')}
                                </option>
                            </select>
                        </div>

                        <div className="aibp-form-field">
                            <label>{__('Categories', 'ai-bulk-post')}</label>
                            <div className="aibp-category-list">
                                {categories.length === 0 && (
                                    <p className="description">
                                        {__('No categories found.', 'ai-bulk-post')}
                                    </p>
                                )}
                                {categories.map((cat) => (
                                    <button
                                        key={cat.id}
                                        type="button"
                                        className={`aibp-category-btn ${
                                            data.categories.includes(cat.id)
                                                ? 'aibp-category-active'
                                                : ''
                                        }`}
                                        onClick={() => {
                                            const cats = data.categories.includes(
                                                cat.id
                                            )
                                                ? data.categories.filter(
                                                      (c) => c !== cat.id
                                                  )
                                                : [...data.categories, cat.id];
                                            update('categories', cats);
                                        }}
                                    >
                                        {cat.name}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </div>
                );

            default:
                return null;
        }
    };

    const isLastStep = currentStep === 5;
    const isFirstStep = currentStep === 1;

    return (
        <div className="aibp-modal-overlay" onClick={onClose}>
            <div
                className="aibp-modal aibp-modal-lg"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="aibp-modal-header">
                    <h2>
                        {agent
                            ? __('Edit Agent', 'ai-bulk-post')
                            : __('Add New Agent', 'ai-bulk-post')}
                    </h2>
                    <button className="aibp-modal-close" onClick={onClose}>
                        &times;
                    </button>
                </div>

                <div className="aibp-modal-body">
                    <div className="aibp-progress-bar">
                        <div
                            className="aibp-progress-fill"
                            style={{
                                width: `${((currentStep - 1) / (STEPS.length - 1)) * 100}%`,
                            }}
                        />
                    </div>

                    <div className="aibp-step-label">
                        <span className="aibp-step-number">{currentStep}</span>
                        <span className="aibp-step-name">
                            {STEPS[currentStep - 1].label}
                        </span>
                    </div>

                    {renderStepContent()}

                    {errors.submit && (
                        <div className="aibp-notice aibp-notice-error">
                            {errors.submit}
                        </div>
                    )}
                </div>

                <div className="aibp-modal-footer">
                    <button type="button" className="button" onClick={onClose}>
                        {AIBulkPost.i18n.cancel}
                    </button>

                    <div className="aibp-modal-footer-right">
                        {!isFirstStep && (
                            <button
                                type="button"
                                className="button"
                                onClick={handleBack}
                            >
                                {__('Back', 'ai-bulk-post')}
                            </button>
                        )}

                        {!isLastStep ? (
                            <button
                                type="button"
                                className="button button-primary"
                                onClick={handleNext}
                            >
                                {__('Next', 'ai-bulk-post')}
                            </button>
                        ) : (
                            <button
                                type="button"
                                className="button button-primary"
                                onClick={handleSubmit}
                                disabled={saving}
                            >
                                {saving
                                    ? __('Saving...', 'ai-bulk-post')
                                    : AIBulkPost.i18n.save}
                            </button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}
