import {useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {closestCenter, DndContext, PointerSensor, useSensor, useSensors} from "@dnd-kit/core";
import {arrayMove, SortableContext, verticalListSortingStrategy} from "@dnd-kit/sortable";
import Input from "../../../../../../../../../fields/input";
import BlockEditable from "../../../../../../../../../fields/blockeditable";
import Emoji from "../../../../../../../../../button/emoji";
import SectionHeader from "../../../../../../../../../sections/section-header";
import LeadCaptureFieldItem from "./lead-capture-field-item";
import Toggle from "../../../../../../../../../fields/toggle";
import {generateUniqueId} from "../../../../../../../../../../../helpers";
import confirm from "../../../../../../../../../../helpers/confirm";
import Description from "../../../../../../../../../sections/description";

export default function LeadCaptureWidget({widgetItem, index, update, notifications}) {
    // Track opened state for new fields (by field name) - for auto-opening newly added fields
    const [newFieldNames, setNewFieldNames] = useState(new Set());

    // DnD context for fields
    const sensors = useSensors(useSensor(PointerSensor));

    // Helper function to update widget data property
    const updateDataProperty = (property, value) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            return {
                ...item,
                data: {
                    ...item.data,
                    [property]: value
                }
            };
        }));
    };

    // Helper function to update field property
    const updateField = (fieldIndex, prop, value) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            return {
                ...item,
                data: {
                    ...item.data,
                    fields: (item.data?.fields || []).map((f, fi) => {
                        if (fi === fieldIndex) {
                            return {...f, [prop]: value};
                        }
                        return f;
                    })
                }
            };
        }));
    };

    // Helper function to update field config property
    const updateFieldConfig = (fieldIndex, prop, value) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            return {
                ...item,
                data: {
                    ...item.data,
                    fields: (item.data?.fields || []).map((f, fi) => {
                        if (fi === fieldIndex) {
                            return {
                                ...f,
                                config: {
                                    ...(f.config || {}),
                                    [prop]: value
                                }
                            };
                        }
                        return f;
                    })
                }
            };
        }));
    };

    // Helper function to toggle field required
    const toggleFieldRequired = (fieldIndex) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            return {
                ...item,
                data: {
                    ...item.data,
                    fields: (item.data?.fields || []).map((f, fi) => {
                        if (fi === fieldIndex) {
                            return {...f, required: !(f.required || false)};
                        }
                        return f;
                    })
                }
            };
        }));
    };

    // Helper function to delete field
    const deleteField = async (fieldIndex) => {
        if (await confirm(__("Are you sure you want to delete this field?", 'limb-chatbot'))) {
            update(prevState => prevState.map((item, i) => {
                if (i !== index) return item;
                return {
                    ...item,
                    data: {
                        ...item.data,
                        fields: (item.data?.fields || []).filter((f, fi) => fi !== fieldIndex)
                    }
                };
            }));
        }
    };

    // Helper function to add field
    const addField = () => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            const currentFields = item.data?.fields || [];
            const newFieldName = `field_${generateUniqueId()}`;
            const newField = {
                type: 'text',
                required: false,
                name: newFieldName,
                label: '',
                placeholder: ''
            };
            // Track new field name for auto-opening
            setNewFieldNames(prev => new Set([...prev, newFieldName]));
            return {
                ...item,
                data: {
                    ...item.data,
                    fields: [...currentFields, newField]
                }
            };
        }));
    };

    // Helper function to append emoji
    const appendEmoji = (property, emoji) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            return {
                ...item,
                data: {
                    ...item.data,
                    [property]: (item.data?.[property] || '') + emoji
                }
            };
        }));
    };

    // Move field up
    const moveFieldUp = (fieldIndex) => {
        if (fieldIndex !== 0) {
            update(prevState => prevState.map((item, i) => {
                if (i !== index) return item;
                const fields = item.data?.fields || [];
                const moved = arrayMove(fields, fieldIndex, fieldIndex - 1);
                return {
                    ...item,
                    data: {
                        ...item.data,
                        fields: moved
                    }
                };
            }));
        }
    };

    // Move field down
    const moveFieldDown = (fieldIndex) => {
        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;
            const fields = item.data?.fields || [];
            if (fieldIndex !== fields.length - 1) {
                const moved = arrayMove(fields, fieldIndex, fieldIndex + 1);
                return {
                    ...item,
                    data: {
                        ...item.data,
                        fields: moved
                    }
                };
            }
            return item;
        }));
    };

    // Handle DnD end for fields
    const handleFieldDragEnd = (event) => {
        const {active, over} = event;

        if (!over || active.id === over.id) {
            return;
        }

        update(prevState => prevState.map((item, i) => {
            if (i !== index) return item;

            const fields = item.data?.fields || [];
            // Find indices using name or fallback to index-based id
            const oldIndex = fields.findIndex((f, idx) => {
                const fieldId = f.name || `field_${idx}`;
                return fieldId === active.id;
            });
            const newIndex = fields.findIndex((f, idx) => {
                const fieldId = f.name || `field_${idx}`;
                return fieldId === over.id;
            });

            if (oldIndex === -1 || newIndex === -1) {
                return item;
            }

            const moved = arrayMove(fields, oldIndex, newIndex);

            return {
                ...item,
                data: {
                    ...item.data,
                    fields: moved
                }
            };
        }));
    };

    return (
        <>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={widgetItem.data?.heading || ''}
                        setValue={value => updateDataProperty('heading', value)}
                        placeholder={__("Heading", 'limb-chatbot')}
                        autofocus
                        actions={[
                            {
                                component: Emoji,
                                props: {
                                    chosen: obj => appendEmoji('heading', obj.emoji)
                                },
                            },
                        ]}/>
                </div>
                <div className="lbaic-settings-column-in">
                    {widgetItem.locations?.[0]?.[0]?.value === 'chatbot_icon' && (
                        <>
                            <Toggle
                                label={__("Required", 'limb-chatbot')}
                                isActive={Boolean(widgetItem.data?.required)}
                                onClick={() => updateDataProperty('required', !widgetItem.data?.required)}
                            />
                            <Description>{__("If enabled, users must complete the form before opening the chatbot.", 'limb-chatbot')}</Description>
                        </>
                    )}
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <BlockEditable
                        value={widgetItem.data?.description || ''}
                        setValue={value => updateDataProperty('description', value)}
                        label={__("Description", 'limb-chatbot')}
                        emoji={true}
                        notifications={notifications}
                        className="lbaic-settings-blockeditable-white"
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={widgetItem.data?.submit_button_text || ''}
                        setValue={value => updateDataProperty('submit_button_text', value)}
                        placeholder={__("Submit button text", 'limb-chatbot')}
                        actions={[
                            {
                                component: Emoji,
                                props: {
                                    chosen: obj => appendEmoji('submit_button_text', obj.emoji)
                                },
                            },
                        ]}/>
                </div>
                <div className="lbaic-settings-column-in"/>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    {(widgetItem.data?.fields || []).length > 0 ? (
                        <>
                            <SectionHeader
                                title={__("Form fields", 'limb-chatbot')}
                                description={__("Fields to collect from users in the lead capture form", 'limb-chatbot')}
                                onButtonClick={addField}
                                buttonLabel={__("+ Add field", 'limb-chatbot')}
                                badgeLabel={(widgetItem.data?.fields || []).length}
                            />
                            <div className='lbaic-settings-table-accordion lbaic-settings-cb-pw-table-inside lbaic-settings-table-accordion-lc'>
                                <DndContext sensors={sensors} collisionDetection={closestCenter}
                                            onDragEnd={handleFieldDragEnd}>
                                    <SortableContext
                                        items={(widgetItem.data?.fields || []).map((f, idx) => f.name || `field_${idx}`)}
                                        strategy={verticalListSortingStrategy}>
                                        {(widgetItem.data?.fields || []).map((field, fieldIndex) => (
                                            <LeadCaptureFieldItem
                                                key={field.name || fieldIndex}
                                                field={field}
                                                fieldIndex={fieldIndex}
                                                updateField={updateField}
                                                updateFieldConfig={updateFieldConfig}
                                                toggleFieldRequired={toggleFieldRequired}
                                                deleteField={deleteField}
                                                moveUp={() => moveFieldUp(fieldIndex)}
                                                moveDown={() => moveFieldDown(fieldIndex)}
                                                notifications={notifications}
                                                forceOpen={newFieldNames.has(field.name)}
                                                onOpened={() => {
                                                    // Remove from newFieldNames once opened
                                                    if (newFieldNames.has(field.name)) {
                                                        setNewFieldNames(prev => {
                                                            const newSet = new Set(prev);
                                                            newSet.delete(field.name);
                                                            return newSet;
                                                        });
                                                    }
                                                }}
                                            />
                                        ))}
                                    </SortableContext>
                                </DndContext>
                            </div>
                        </>
                    ) : (
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <button
                                    type="button"
                                    className="lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-32 lbaic-settings-button-secondary"
                                    onClick={addField}
                                >
                                    <svg className='lbaic-settings-button-i' xmlns='http://www.w3.org/2000/svg'
                                         fill='none' viewBox='0 0 24 24'>
                                        <use href='#lbaic-settings-plus'/>
                                    </svg>
                                    <span
                                        className='lbaic-settings-button-label'>{__("Add field", 'limb-chatbot')}</span>
                                </button>
                            </div>
                            <div className="lbaic-settings-column-in"/>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}
