/**
 * Type definitions for Content Plan Plugin
 */

// Content Plan Item Status
export type ContentPlanItemStatus =
    | 'planned'
    | 'draft_ready_ai'
    | 'draft_ready_manual'
    | 'published';

// Post
export interface Post {
    id: number;
    title: string;
    slug?: string;
    content?: string;
    excerpt?: string;
    status: string;
    date?: string;
    modified?: string;
    author?: number;
    post_type: string;
}

// Content Plan Item
export interface ContentPlanItem {
    id: number;
    title: string;
    structure: string; // JSON string
    keywords: string;
    status: ContentPlanItemStatus;
    scheduled_on: string | null;
    post: string | null;
    lang?: string | null; // Language code
    created_at: string;
    updated_at?: string;
}

// Content Plan
export interface ContentPlan {
    contentPlanItems: ContentPlanItem[];
}

// User
export interface User {
    name: string;
    role: string;
}

// Settings
export interface Settings {
    [key: string]: any;
}

// Field Configuration
export interface FieldConfig {
    type:
        | 'text'
        | 'email'
        | 'url'
        | 'number'
        | 'password'
        | 'textarea'
        | 'select'
        | 'radio'
        | 'checkbox';
    label: string;
    description?: string;
    placeholder?: string;
    required?: boolean;
    options?: { [key: string]: string };
    rows?: number;
}

export interface FieldConfigs {
    [key: string]: FieldConfig;
}

// Strings
export interface Strings {
    [category: string]: {
        [key: string]: string;
    };
}

// Data
export interface Data {
    message?: string;
    version?: string;
    [key: string]: any;
}

// Context State
export interface ContentPlanContextState {
    // State
    loading: boolean;
    saving: boolean;
    error: string | null;
    contentPlan: ContentPlan;
    posts: Post[];
    postsLoading: boolean;
    postsError: string | null;
    tasks: Task[];
    tasksLoading: boolean;
    tasksError: string | null;
    logs: Log[];
    logsLoading: boolean;
    logsError: string | null;
    settings: Settings;
    fieldConfigs: FieldConfigs;
    strings: Strings;
    data: Data;
    user: User;
    usage: UsageData | null;
    usageError: string | null;
    backendConfigured: boolean;
    sidebarOpen: boolean;
    sidebarType: string | null;
    generationModalOpen: boolean;
    currentTaskId: string | null;
    taskFilterId: number | null; // Task ID to filter content plan items by
    isNewWebsite: boolean;
    opted: boolean | undefined;
    optinUrl: string | undefined;
    timezone: { string: string; offset: number } | null;

    // Actions
    updateContentPlan: (newData: Partial<ContentPlan>) => void;
    addContentPlanItem: (item: ContentPlanItem) => void;
    updateContentPlanItem: (
        itemId: number,
        updatedItem: Partial<ContentPlanItem>
    ) => void;
    deleteContentPlanItem: (itemId: number) => void;
    updateSettings: (newSettings: Partial<Settings>) => void;
    updateFieldConfigs: (newConfigs: Partial<FieldConfigs>) => void;
    updateStrings: (newStrings: Partial<Strings>) => void;
    clearError: () => void;
    setLoadingState: (isLoading: boolean) => void;
    setSavingState: (isSaving: boolean) => void;
    setErrorState: (errorMessage: string | null) => void;
    getString: (category: string, key: string, fallback?: string) => string;
    getLatestContentPlanDate: () => string | null;
    saveSettings: (settingsData: Settings) => Promise<any>;
    recalculateSchedule: () => Promise<void>;
    refreshData: () => void;
    refreshUsage: () => Promise<void>;
    openSidebar: (type: string) => void;
    closeSidebar: () => void;
    openGenerationModal: () => void;
    closeGenerationModal: () => void;
    setCurrentTaskId: (taskId: string | null) => void;
    setTaskFilter: (taskId: number | null) => void;
    clearTaskFilter: () => void;

    // API Functions
    fetchContentPlanItems: (planId?: number) => Promise<void>;
    createContentPlanItem: (
        itemData: Partial<ContentPlanItem>,
        planId?: number
    ) => Promise<void>;
    updateContentPlanItemAPI: (
        id: number,
        itemData: Partial<ContentPlanItem>,
        planId?: number
    ) => Promise<void>;
    deleteContentPlanItemAPI: (id: number, planId?: number) => Promise<void>;
    bulkDeleteContentPlanItems: (
        ids: number[],
        planId?: number
    ) => Promise<void>;
    createMultipleContentPlanItems: (
        items: ContentPlanItem[],
        publishInterval: number,
        planId?: number,
        latestScheduledDate?: string | null
    ) => Promise<void>;
    createPost: (postData: PostCreationFormData) => Promise<void>;
    fetchPosts: (
        fields?: string[],
        postTypes?: string[],
        args?: any
    ) => Promise<void>;
    generateContentPlan: (formData: ContentPlanGenerationFormData) => Promise<{
        items: ContentPlanItem[];
        devInfo?: any;
        latestScheduledDate?: string | null;
        taskId?: string;
    }>;
    fetchTasks: (args?: {
        status?: string;
        type?: string;
        limit?: number;
    }) => Promise<void>;
    markTaskAsWatched: (taskId: number) => Promise<void>;
    addFailedTask: (
        type: string,
        errorMessage: string,
        itemId?: number
    ) => void;
    fetchLogs: (args?: {
        level?: string;
        limit?: number;
        offset?: number;
    }) => Promise<void>;
}

// List Item structure
export interface ListItem {
    type: string; // Non-translatable identifier (e.g., "excerpt_tldr", "paragraph")
    subtitle?: string;
}

// Component Props
export interface DynamicListFieldProps {
    items: (string | ListItem)[];
    onChange: (items: (string | ListItem)[]) => void;
    getString: (category: string, key: string, fallback?: string) => string;
}

export interface DynamicFormFieldProps {
    fieldKey: string;
    config: FieldConfig;
    value: any;
    onChange: (fieldKey: string, value: any) => void;
}

export interface DynamicSettingsFormProps {
    settings: Settings;
    fieldConfigs: FieldConfigs;
    onSave: (formData: Settings) => Promise<void>;
}

// API Response types
export interface ApiResponse<T = any> {
    success: boolean;
    message?: string;
    data?: T;
    taskId?: string; // Optional taskId for async operations
    should_poll?: boolean; // Optional flag indicating if polling should continue
}

// Usage Data
export interface UsageData {
    blocked: boolean;
    tokensRemaining: number;
    renewDate: string | null;
}

export interface PresetResponse {
    settings?: Settings;
    field_configs?: FieldConfigs;
    strings?: Strings;
    usage?: UsageData;
    usage_error?: string;
    backend_configured?: boolean;
    is_new_website?: boolean;
    opted?: boolean;
    optin_url?: string;
    timezone?: {
        string: string;
        offset: number; // Offset in seconds
    };
}

// Form Data types
export interface ContentPlanItemFormData {
    title: string;
    structure: (string | ListItem)[];
    keywords: string[];
    status: ContentPlanItemStatus;
    scheduled_on: string;
    post: string;
    language: string;
}

export interface PostCreationFormData {
    title: string;
    content: string;
    excerpt: string;
    status: 'draft' | 'publish' | 'private';
    category: string;
    tags: string;
    featured_image: string;
    meta_description: string;
    keywords: string;
    scheduled_on: string;
}

export interface ContentPlanGenerationFormData {
    goals: string[];
    publishInterval: number;
    totalPosts: number;
    language: string;
    customLanguage: string;
    customRecommendations: string;
}

// Tab configuration
export interface Tab {
    id: string;
    label: string;
}

// Validation errors
export interface ValidationErrors {
    [key: string]: string;
}

// Task
export interface Task {
    id: number;
    task_id: string;
    type: string;
    status: 'queued' | 'processing' | 'completed' | 'failed';
    watched?: boolean; // Whether user has marked this task as watched
    result?: {
        output?: {
            item_ids?: number[]; // IDs of content plan items created by this task
            plan?: any;
            [key: string]: any;
        };
        error?: string;
        [key: string]: any;
    };
    created_at: string;
    formatted_scheduled_date?: string; // Formatted scheduled date for post generation tasks (from server)
    updated_at?: string;
}

// Log
export interface Log {
    id: number;
    created_at: string;
    level: 'info' | 'warning' | 'error' | 'debug';
    event?: string | null;
    message?: string | null;
    context?: string | null;
    task_id?: string | null;
    correlation_id?: string | null;
    error_code?: string | null;
    tokens_spent?: number | null;
}
