/**
 * Dynamic List Field Component
 *
 * A reusable component for managing a dynamic list of items
 */

import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import Select from 'react-select';
import { DynamicListFieldProps, ListItem } from '../types';

const DynamicListField = ({
    items = [],
    onChange,
    getString,
}: DynamicListFieldProps) => {
    const [selectedItem, setSelectedItem] = useState<string>('');
    const [subtitle, setSubtitle] = useState<string>('');

    // 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)',
        }),
    };

    // Predefined options with non-translatable types and translatable labels
    const predefinedOptions = [
        {
            type: 'excerpt_tldr',
            label: getString('dynamic_list', 'excerpt_tldr', 'Excerpt / TL;DR'),
        },
        {
            type: 'paragraph',
            label: getString('dynamic_list', 'paragraph', 'Subtopic'),
        },
        {
            type: 'key_takeaways',
            label: getString('dynamic_list', 'key_takeaways', 'Key Takeaways'),
        },
        {
            type: 'faq',
            label: getString('dynamic_list', 'faq', 'FAQ'),
        },
        {
            type: 'conclusion_summary',
            label: getString(
                'dynamic_list',
                'conclusion_summary',
                'Conclusion / summary'
            ),
        },
    ];

    const handleAddItem = (): void => {
        if (selectedItem) {
            // Convert string items to ListItem objects for backward compatibility
            const currentItems = items.map(item =>
                typeof item === 'string' ? { type: item, subtitle: '' } : item
            );

            const newItem: ListItem = {
                type: selectedItem, // Non-translatable type (e.g., "excerpt_tldr")
                subtitle: selectedItem === 'paragraph' ? subtitle : undefined,
            };

            onChange([...currentItems, newItem]);
            setSelectedItem('');
            setSubtitle('');
        }
    };

    const handleRemoveItem = (index: number): void => {
        const newItems = items.filter((_, i) => i !== index);
        onChange(newItems);
    };

    const handleSubtitleChange = (index: number, newSubtitle: string): void => {
        const currentItems = items.map(item =>
            typeof item === 'string' ? { type: item, subtitle: '' } : item
        );

        const updatedItems = currentItems.map((item, i) =>
            i === index ? { ...item, subtitle: newSubtitle } : item
        );

        onChange(updatedItems);
    };

    // All options are always available (users can select the same item multiple times)
    const availableOptions = predefinedOptions;

    return (
        <div className="dynamic-list-field">
            {/* Dropdown for selecting new items */}
            <div className="flex flex-col sm:flex-row gap-2 mb-2">
                <div className="flex-1 w-full">
                    <Select
                        value={
                            selectedItem
                                ? {
                                      value: selectedItem,
                                      label:
                                          availableOptions.find(
                                              opt => opt.type === selectedItem
                                          )?.label || selectedItem,
                                  }
                                : null
                        }
                        onChange={selectedOption =>
                            setSelectedItem(selectedOption?.value || '')
                        }
                        options={[
                            {
                                value: '',
                                label: getString(
                                    'dynamic_list',
                                    'select_item_placeholder',
                                    'Select an item to add...'
                                ),
                            },
                            ...availableOptions.map(option => ({
                                value: option.type,
                                label: option.label,
                            })),
                        ]}
                        styles={selectStyles}
                        isSearchable={false}
                        className="react-select-container"
                        classNamePrefix="react-select"
                    />
                </div>
                <button
                    type="button"
                    onClick={handleAddItem}
                    className="cpepai-button cpepai-button--secondary w-full sm:w-auto"
                    disabled={!selectedItem}
                >
                    {getString('dynamic_list', 'add', 'Add')}
                </button>
            </div>

            {/* Subtitle input for Subtopics */}
            {selectedItem === 'paragraph' && (
                <div className="mb-2">
                    <input
                        type="text"
                        value={subtitle}
                        onChange={e => setSubtitle(e.target.value)}
                        className="cpepai-form-input w-full text-sm sm:text-base"
                        placeholder={getString(
                            'dynamic_list',
                            'subtitle_placeholder',
                            'Enter subtitle for this paragraph section...'
                        )}
                    />
                </div>
            )}

            {/* List of items */}
            <div className="space-y-2">
                {items.map((item, index) => {
                    // Handle backward compatibility: convert string items to objects
                    const itemType =
                        typeof item === 'string' ? item : item.type;
                    const itemSubtitle =
                        typeof item === 'string' ? '' : item.subtitle || '';

                    // Find the predefined option to get the current label
                    const predefinedOption = predefinedOptions.find(
                        option => option.type === itemType
                    );
                    const displayLabel = predefinedOption
                        ? predefinedOption.label
                        : itemType;

                    return (
                        <div
                            key={index}
                            className="bg-gray-200 p-2 sm:p-3 rounded"
                        >
                            <div className="flex items-center gap-2 mb-2">
                                <span className="flex-1 font-medium text-xs sm:text-sm break-words">
                                    {displayLabel}
                                </span>
                                <button
                                    type="button"
                                    onClick={() => handleRemoveItem(index)}
                                    className="text-red-600 hover:text-red-700 flex-shrink-0"
                                    title={getString(
                                        'dynamic_list',
                                        'remove',
                                        'Remove'
                                    )}
                                >
                                    <svg
                                        className="w-3 h-3 sm:w-4 sm:h-4"
                                        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>

                            {/* Subtitle field for Subtopics */}
                            {itemType === 'paragraph' && (
                                <input
                                    type="text"
                                    value={itemSubtitle}
                                    onChange={e =>
                                        handleSubtitleChange(
                                            index,
                                            e.target.value
                                        )
                                    }
                                    className="cpepai-form-input w-full text-xs sm:text-sm"
                                    placeholder={getString(
                                        'dynamic_list',
                                        'subtitle_placeholder',
                                        'Enter subtitle for this paragraph section...'
                                    )}
                                />
                            )}
                        </div>
                    );
                })}
            </div>

            {/* Empty state */}
            {items.length === 0 && (
                <div className="text-gray-500 text-xs sm:text-sm italic">
                    {getString(
                        'dynamic_list',
                        'no_items',
                        'No items added yet. Choose from the dropdown above to build your structure.'
                    )}
                </div>
            )}
        </div>
    );
};

export default DynamicListField;
