/**
 * Content Plan Item Sidebar Component
 *
 * A sidebar component for creating and editing content plan items
 */

import React, { useState, useEffect, useRef } from 'react';
import type { FC, FormEvent, ChangeEvent } from 'react';
import { __ } from '@wordpress/i18n';
import Select from 'react-select';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { useContentPlan } from '../context/ContentPlanContext';
import DynamicListField from './DynamicListField';
import KeywordInput from './KeywordInput';
import DeleteConfirmationModal from './DeleteConfirmationModal';
import ErrorMessage from './ErrorMessage';
import {
    ContentPlanItem,
    ContentPlanItemFormData,
    ValidationErrors,
} from '../types';
import { LANGUAGE_OPTIONS } from '../utils/languageOptions';

/**
 * Safely parse a date string for DatePicker. Returns null for invalid dates
 * to prevent "Invalid time value" errors from date-fns format().
 */
const parseDateSafe = (value: string | null | undefined): Date | null => {
    if (!value || typeof value !== 'string') return null;
    const trimmed = value.trim();
    if (!trimmed) return null;
    const date = new Date(trimmed);
    return isNaN(date.getTime()) ? null : date;
};

/**
 * Extract YYYY-MM-DD from scheduled_on (handles "YYYY-MM-DD H:i:s" and ISO formats).
 */
const getDatePart = (scheduledOn: string | null | undefined): string => {
    if (!scheduledOn || typeof scheduledOn !== 'string') return '';
    const part = scheduledOn.split(' ')[0] || scheduledOn.split('T')[0] || '';
    return part.substring(0, 10) || '';
};

const ContentPlanItemSidebar: FC = () => {
    // Custom styles for react-select
    const selectStyles = {
        control: (provided: any, state: any) => ({
            ...provided,
            minHeight: '48px',
            border: state.isFocused ? '1px solid #3b82f6' : '1px solid #d1d5db',
            borderRadius: '6px',
            boxShadow: state.isFocused ? '0 0 0 1px #3b82f6' : 'none',
            '&:hover': {
                border: '1px solid #3b82f6',
            },
        }),
        valueContainer: (provided: any) => ({
            ...provided,
            padding: '0 12px',
        }),
        input: (provided: any) => ({
            ...provided,
            margin: '0',
        }),
        indicatorSeparator: () => ({
            display: 'none',
        }),
        indicatorsContainer: (provided: any) => ({
            ...provided,
            paddingRight: '12px',
        }),
        dropdownIndicator: (provided: any) => ({
            ...provided,
            color: '#6b7280',
            '&:hover': {
                color: '#374151',
            },
        }),
        option: (provided: any, state: any) => ({
            ...provided,
            backgroundColor: state.isSelected
                ? '#3b82f6'
                : state.isFocused
                  ? '#f3f4f6'
                  : 'white',
            color: state.isSelected ? 'white' : '#374151',
            padding: '12px 16px',
            '&:hover': {
                backgroundColor: state.isSelected ? '#3b82f6' : '#f3f4f6',
            },
        }),
        menu: (provided: any) => ({
            ...provided,
            borderRadius: '6px',
            border: '1px solid #e5e7eb',
            boxShadow:
                '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
        }),
    };
    const {
        sidebarOpen,
        sidebarType,
        closeSidebar,
        getString,
        error,
        clearError,
        setErrorState,
        createContentPlanItem,
        updateContentPlanItemAPI,
        fetchPosts,
        posts,
    } = useContentPlan();

    const [formData, setFormData] = useState<ContentPlanItemFormData>({
        title: '',
        structure: [],
        keywords: [],
        status: 'planned',
        scheduled_on: '',
        post: '',
        language: 'English',
    });

    const [editingItem, setEditingItem] = useState<ContentPlanItem | undefined>(
        undefined
    );
    const [saving, setSaving] = useState<boolean>(false);
    const [currentPlanId] = useState<number>(1); // Default to plan ID 1 for now
    const [validationErrors, setValidationErrors] = useState<ValidationErrors>(
        {}
    );
    const [deleteModalOpen, setDeleteModalOpen] = useState<boolean>(false);

    // Reset form when sidebar opens/closes
    useEffect(() => {
        if (sidebarOpen && sidebarType === 'content-plan-item') {
            // Form will be populated by the parent component
        } else if (!sidebarOpen) {
            resetForm();
        }
    }, [sidebarOpen, sidebarType]);

    // Fetch posts when sidebar opens
    useEffect(() => {
        if (sidebarOpen && sidebarType === 'content-plan-item') {
            fetchPosts(['id', 'title', 'slug', 'status'], ['post', 'page'], {
                limit: 50,
                orderby: 'date',
                order: 'DESC',
            });
        }
    }, [sidebarOpen, sidebarType]);

    // Prevent body scroll when sidebar is open
    useEffect(() => {
        if (sidebarOpen && sidebarType === 'content-plan-item') {
            // Save current overflow value
            const originalOverflow = document.body.style.overflow;
            // Prevent scrolling
            document.body.style.overflow = 'hidden';

            // Cleanup: restore original overflow when sidebar closes
            return () => {
                document.body.style.overflow = originalOverflow;
            };
        }
    }, [sidebarOpen, sidebarType]);

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

        // Clear validation error for this field when user starts typing
        if (validationErrors[field]) {
            setValidationErrors(prev => {
                const newErrors = { ...prev };
                delete newErrors[field];
                return newErrors;
            });
        }
    };

    const validateForm = (): boolean => {
        const errors: ValidationErrors = {};

        // Title is required
        if (!formData.title.trim()) {
            errors.title = getString(
                'content_plan_table',
                'title_required',
                'Title is required'
            );
        }

        // Structure is required
        if (!formData.structure.length) {
            errors.structure = getString(
                'content_plan_table',
                'structure_required',
                'At least one structure item is required'
            );
        }

        // Scheduled On is required
        if (!formData.scheduled_on) {
            errors.scheduled_on = getString(
                'content_plan_table',
                'scheduled_on_required',
                'Scheduled date is required'
            );
        }

        // Keywords are optional, so no validation needed

        setValidationErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const handleSubmit = async (
        e: FormEvent<HTMLFormElement>
    ): Promise<void> => {
        e.preventDefault();

        // Validate all required fields
        if (!validateForm()) {
            return;
        }

        setSaving(true);
        setErrorState(null);

        try {
            const itemData = {
                title: formData.title.trim(),
                structure: JSON.stringify(formData.structure),
                keywords: formData.keywords.join(', '),
                status: formData.status,
                scheduled_on: formData.scheduled_on
                    ? `${formData.scheduled_on}T00:00:00`
                    : null,
                post: formData.post.trim() || null,
                lang: formData.language || null,
            };

            if (editingItem) {
                await updateContentPlanItemAPI(
                    editingItem.id,
                    itemData,
                    currentPlanId
                );
            } else {
                await createContentPlanItem(itemData, currentPlanId);
            }

            closeSidebar();
            resetForm();
        } catch (err: any) {
            setErrorState(err.message);
            console.error('Error saving content plan item:', err);
        } finally {
            setSaving(false);
        }
    };

    const handleClose = (): void => {
        closeSidebar();
        resetForm();
    };

    const resetForm = (): void => {
        setFormData({
            title: '',
            structure: [],
            keywords: [],
            status: 'planned',
            scheduled_on: '',
            post: '',
            language: 'English',
        });
        setEditingItem(undefined);
        setErrorState(null);
        setValidationErrors({});
    };

    // Listen for edit events from parent component
    useEffect(() => {
        const handleEditItem = (
            event: CustomEvent<{ item: ContentPlanItem }>
        ) => {
            const { item } = event.detail;
            setEditingItem(item);
            let structureArray = [];
            try {
                structureArray = item.structure
                    ? JSON.parse(item.structure)
                    : [];
                if (!Array.isArray(structureArray)) {
                    structureArray = [];
                }
            } catch (e) {
                console.error('Error parsing structure:', e);
            }

            setFormData({
                title: item.title || '',
                structure: structureArray,
                keywords: item.keywords
                    ? item.keywords.split(',').map(k => k.trim())
                    : [],
                status: item.status || 'planned',
                scheduled_on: getDatePart(item.scheduled_on),
                post: item.post || '',
                language: item.lang || 'English',
            });
        };

        window.addEventListener(
            'editContentPlanItem',
            handleEditItem as EventListener
        );
        return () => {
            window.removeEventListener(
                'editContentPlanItem',
                handleEditItem as EventListener
            );
        };
    }, []);

    if (!sidebarOpen || sidebarType !== 'content-plan-item') {
        return null;
    }

    return (
        <>
            {/* Backdrop */}
            <div
                className={`cpepai-sidebar-backdrop ${sidebarOpen ? 'open' : ''}`}
                onClick={handleClose}
            />

            {/* Sidebar */}
            <div className={`cpepai-sidebar ${sidebarOpen ? 'open' : ''}`}>
                <div className="cpepai-sidebar-header">
                    <h2 className="cpepai-sidebar-title text-base sm:text-lg">
                        {editingItem
                            ? getString(
                                  'content_plan_table',
                                  'edit_item',
                                  'Edit Content Plan Item'
                              )
                            : getString(
                                  'content_plan_table',
                                  'add_item',
                                  'Add New Content Plan Item'
                              )}
                    </h2>
                    <button
                        className="cpepai-sidebar-close"
                        onClick={handleClose}
                        type="button"
                    >
                        <svg
                            className="w-4 h-4 sm:w-5 sm:h-5"
                            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>

                <form
                    onSubmit={handleSubmit}
                    className="cpepai-form flex flex-col flex-1 overflow-hidden"
                >
                    <div className="cpepai-sidebar-content">
                        {/* Error Message */}
                        {error && (
                            <div className="mb-4">
                                <ErrorMessage
                                    message={error}
                                    title={getString(
                                        'common',
                                        'error',
                                        'Error'
                                    )}
                                />
                                <div className="mt-2">
                                    <button
                                        onClick={clearError}
                                        className="cpepai-button-secondary text-sm"
                                        type="button"
                                    >
                                        {getString(
                                            'common',
                                            'dismiss',
                                            'Dismiss'
                                        )}
                                    </button>
                                </div>
                            </div>
                        )}

                        {/* Title */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-title"
                        >
                            <label className="cpepai-form-label">
                                {getString(
                                    'content_plan_table',
                                    'title_label',
                                    'Title'
                                )}{' '}
                                *
                            </label>
                            <input
                                type="text"
                                value={formData.title}
                                onChange={(e: ChangeEvent<HTMLInputElement>) =>
                                    handleInputChange('title', e.target.value)
                                }
                                className={`cpepai-form-input h-10 sm:h-12 px-2 sm:px-3 py-2 sm:py-3 text-sm sm:text-base ${
                                    validationErrors.title
                                        ? 'cpepai-form-input--error'
                                        : ''
                                }`}
                                placeholder={getString(
                                    'content_plan_table',
                                    'title_placeholder',
                                    'Enter item title...'
                                )}
                                required
                            />
                            {validationErrors.title && (
                                <div className="cpepai-form-error">
                                    {validationErrors.title}
                                </div>
                            )}
                        </div>

                        {/* Structure */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-structure"
                        >
                            <label className="cpepai-form-label">
                                {getString(
                                    'content_plan_table',
                                    'structure_label',
                                    'Structure'
                                )}{' '}
                                *
                            </label>
                            <DynamicListField
                                items={formData.structure}
                                onChange={items =>
                                    handleInputChange('structure', items)
                                }
                                getString={getString}
                            />
                            {validationErrors.structure && (
                                <div className="cpepai-form-error">
                                    {validationErrors.structure}
                                </div>
                            )}
                        </div>

                        {/* Status */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-status"
                        >
                            <label
                                htmlFor="status"
                                className="cpepai-form-label"
                            >
                                {getString(
                                    'content_plan_table',
                                    'status_label',
                                    'Status'
                                )}
                            </label>
                            <Select
                                id="status"
                                value={{
                                    value: formData.status,
                                    label: getString(
                                        `status_${formData.status}`,
                                        'label',
                                        formData.status
                                            .charAt(0)
                                            .toUpperCase() +
                                            formData.status.slice(1)
                                    ),
                                }}
                                onChange={selectedOption =>
                                    handleInputChange(
                                        'status',
                                        selectedOption?.value || 'planned'
                                    )
                                }
                                options={[
                                    {
                                        value: 'planned',
                                        label: getString(
                                            'status_planned',
                                            'label',
                                            'Planned'
                                        ),
                                    },
                                    {
                                        value: 'draft_ready_ai',
                                        label: getString(
                                            'status_draft_ready_ai',
                                            'label',
                                            'Draft Ready (AI)'
                                        ),
                                    },
                                    {
                                        value: 'draft_ready_manual',
                                        label: getString(
                                            'status_draft_ready_manual',
                                            'label',
                                            'Draft Ready (Manual)'
                                        ),
                                    },
                                    {
                                        value: 'published',
                                        label: getString(
                                            'status_published',
                                            'label',
                                            'Published'
                                        ),
                                    },
                                ]}
                                styles={selectStyles}
                                isSearchable={false}
                                className="react-select-container"
                                classNamePrefix="react-select"
                            />
                        </div>

                        {/* Post - Only available when status is not 'planned' */}
                        {formData.status !== 'planned' && (
                            <div
                                className="cpepai-form-group"
                                data-testid="cpepai-field-post"
                            >
                                <label
                                    htmlFor="post"
                                    className="cpepai-form-label"
                                >
                                    {getString(
                                        'content_plan_table',
                                        'post_label',
                                        'Post'
                                    )}
                                </label>
                                <Select
                                    id="post"
                                    value={
                                        formData.post
                                            ? {
                                                  value: formData.post,
                                                  label:
                                                      posts.find(
                                                          p =>
                                                              p.id.toString() ===
                                                              formData.post
                                                      )?.title || formData.post,
                                              }
                                            : null
                                    }
                                    onChange={selectedOption =>
                                        handleInputChange(
                                            'post',
                                            selectedOption?.value || ''
                                        )
                                    }
                                    options={[
                                        {
                                            value: '',
                                            label: getString(
                                                'content_plan_table',
                                                'select_post',
                                                'Select a post...'
                                            ),
                                        },
                                        ...(posts.length > 0
                                            ? posts.map(post => ({
                                                  value: post.id.toString(),
                                                  label: `${post.title} (${post.status})`,
                                              }))
                                            : [
                                                  {
                                                      value: '',
                                                      label: getString(
                                                          'content_plan_table',
                                                          'no_posts_available',
                                                          'No posts available'
                                                      ),
                                                  },
                                              ]),
                                    ]}
                                    styles={selectStyles}
                                    isSearchable={false}
                                    className="react-select-container"
                                    classNamePrefix="react-select"
                                />
                            </div>
                        )}

                        {/* Keywords */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-keywords"
                        >
                            <label className="cpepai-form-label">
                                {getString(
                                    'content_plan_table',
                                    'keywords_label',
                                    'Keywords'
                                )}
                            </label>
                            <KeywordInput
                                keywords={formData.keywords}
                                onChange={keywords =>
                                    handleInputChange('keywords', keywords)
                                }
                                getString={getString}
                            />
                        </div>

                        {/* Language */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-language"
                        >
                            <label
                                htmlFor="language"
                                className="cpepai-form-label"
                            >
                                {getString(
                                    'content_plan_table',
                                    'language_label',
                                    'Language'
                                )}
                            </label>
                            <Select
                                id="language"
                                value={LANGUAGE_OPTIONS.find(
                                    option => option.value === formData.language
                                )}
                                onChange={selectedOption =>
                                    handleInputChange(
                                        'language',
                                        selectedOption?.value || 'English'
                                    )
                                }
                                options={LANGUAGE_OPTIONS}
                                isSearchable={false}
                                placeholder={getString(
                                    'content_plan_table',
                                    'language_placeholder',
                                    'Select a language'
                                )}
                                styles={selectStyles}
                                className="react-select-container"
                                classNamePrefix="react-select"
                            />
                        </div>

                        {/* Scheduled On */}
                        <div
                            className="cpepai-form-group"
                            data-testid="cpepai-field-scheduled-on"
                        >
                            <label
                                htmlFor="scheduled_on"
                                className="cpepai-form-label"
                            >
                                {getString(
                                    'content_plan_table',
                                    'scheduled_on_label',
                                    'Scheduled On'
                                )}{' '}
                                *
                            </label>
                            <DatePicker
                                id="scheduled_on"
                                selected={parseDateSafe(formData.scheduled_on)}
                                onChange={(date: Date | null) =>
                                    handleInputChange(
                                        'scheduled_on',
                                        date
                                            ? date.toISOString().split('T')[0]
                                            : ''
                                    )
                                }
                                dateFormat="yyyy-MM-dd"
                                className={`cpepai-form-input h-12 px-3 py-3 w-full ${
                                    validationErrors.scheduled_on
                                        ? 'cpepai-form-input--error'
                                        : ''
                                }`}
                                placeholderText={getString(
                                    'content_plan_table',
                                    'scheduled_on_placeholder',
                                    'Select a date'
                                )}
                            />
                            {validationErrors.scheduled_on && (
                                <div className="cpepai-form-error">
                                    {validationErrors.scheduled_on}
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Form Actions */}
                    <div className="cpepai-form-actions px-4 sm:px-6 pb-4 sm:pb-16">
                        <div className="flex flex-col sm:flex-row justify-between w-full gap-3 sm:gap-0">
                            {/* Delete Button - Only show for existing items */}
                            {editingItem && (
                                <button
                                    type="button"
                                    onClick={() => {
                                        setDeleteModalOpen(true);
                                    }}
                                    className="cpepai-button cpepai-button-danger w-full sm:w-auto order-3 sm:order-1"
                                >
                                    {getString(
                                        'content_plan_table',
                                        'delete_item',
                                        'Delete Item'
                                    )}
                                </button>
                            )}

                            {/* Right side buttons */}
                            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 sm:space-x-0 w-full sm:w-auto order-1 sm:order-2">
                                <button
                                    type="button"
                                    onClick={handleClose}
                                    className="cpepai-button cpepai-button--secondary w-full sm:w-auto"
                                    disabled={saving}
                                >
                                    {getString(
                                        'content_plan_table',
                                        'cancel',
                                        'Cancel'
                                    )}
                                </button>
                                <button
                                    type="submit"
                                    className="cpepai-button cpepai-button--primary w-full sm:w-auto"
                                    disabled={saving}
                                >
                                    {saving
                                        ? getString(
                                              'content_plan_table',
                                              'saving',
                                              'Saving...'
                                          )
                                        : editingItem
                                          ? getString(
                                                'content_plan_table',
                                                'update',
                                                'Update'
                                            )
                                          : getString(
                                                'content_plan_table',
                                                'create',
                                                'Create'
                                            )}
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            {/* Delete Confirmation Modal */}
            <DeleteConfirmationModal
                isOpen={deleteModalOpen}
                onClose={() => {
                    setDeleteModalOpen(false);
                }}
                onConfirm={() => {
                    if (editingItem) {
                        // Dispatch a custom event for deletion
                        window.dispatchEvent(
                            new CustomEvent('deleteContentPlanItem', {
                                detail: { itemId: editingItem.id },
                            })
                        );
                        handleClose();
                    }
                }}
                itemTitle={editingItem?.title}
                item={editingItem}
            />
        </>
    );
};

export default ContentPlanItemSidebar;
