import {useState, useEffect, useRef} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {useSortable} from "@dnd-kit/sortable";
import {CSS} from "@dnd-kit/utilities";
import Input from "../../../../../../../../../fields/input";
import Checkbox from "../../../../../../../../../fields/checkbox";
import Toggle from "../../../../../../../../../fields/toggle";
import Description from "../../../../../../../../../sections/description";
import LeadFieldMap from "../../../../../../../../../fields/specific-fields/lead-field-map";
import Badge from "../../../../../../../../../fields/badge";

export default function LeadCaptureFieldItem({
                                                 field,
                                                 fieldIndex,
                                                 updateField,
                                                 updateFieldConfig,
                                                 toggleFieldRequired,
                                                 deleteField,
                                                 moveUp,
                                                 moveDown,
                                                 notifications,
                                                 forceOpen = false,
                                                 onOpened
                                             }) {
    // Use field.name as the sortable id (fallback to fieldIndex-based id if name doesn't exist)
    const sortableId = field.name || `field_${fieldIndex}`;

    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
    } = useSortable({id: sortableId});

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    };

    const [opened, setOpened] = useState(forceOpen);
    const prevForceOpenRef = useRef(forceOpen);
    const [showLeadCaptureDropdown, setShowLeadCaptureDropdown] = useState(() => {
        return Boolean(field.config?.lead_capture_map_field);
    });

    // Update showLeadCaptureDropdown when field config changes
    useEffect(() => {
        setShowLeadCaptureDropdown(Boolean(field.config?.lead_capture_map_field));
    }, [field.config?.lead_capture_map_field]);

    // Handle forceOpen prop (for auto-opening new fields)
    useEffect(() => {
        if (forceOpen && !prevForceOpenRef.current) {
            setOpened(true);
            if (onOpened) {
                onOpened();
            }
        }
        prevForceOpenRef.current = forceOpen;
    }, [forceOpen, onOpened]);

    return (
        <div className='lbaic-settings-table-accordion-body' style={style}>
            <div ref={setNodeRef}
                 className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-summary lbaic-settings-cb-pw-table-summary${opened ? ' active' : ''}`}>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions">
                    <div className="lbaic-settings-cb-pw-table-left-actions-in">
                        <button
                            className="lbaic-settings-cb-pw-button lbaic-settings-cb-pw-button-dragable lbaic-settings-button-reset" {...listeners} {...attributes}>
                            <svg className="lbaic-settings-cb-pw-button-i" xmlns="http://www.w3.org/2000/svg"
                                 fill="none"
                                 viewBox="0 0 24 24">
                                <use href="#lbaic-settings-drag"></use>
                            </svg>
                        </button>
                        <div className="lbaic-settings-cb-pw-table-position-actions">
                            <button
                                className="lbaic-settings-cb-pw-button lbaic-settings-button-reset lbaic-settings-cb-pw-table-position-actions-item"
                                onClick={moveUp}>
                                <svg className="lbaic-settings-cb-pw-table-position-actions-i"
                                     xmlns="http://www.w3.org/2000/svg" fill="none"
                                     viewBox="0 0 8 5">
                                    <use href="#lbaic-settings-backward"/>
                                </svg>
                            </button>
                            <button
                                className="lbaic-settings-cb-pw-button lbaic-settings-button-reset lbaic-settings-cb-pw-table-position-actions-item"
                                onClick={moveDown}>
                                <svg className="lbaic-settings-cb-pw-table-position-actions-i"
                                     xmlns="http://www.w3.org/2000/svg" fill="none"
                                     viewBox="0 0 8 5">
                                    <use href="#lbaic-settings-forward"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
                <div
                    className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions lbaic-settings-cb-pw-table-number"
                    onClick={() => setOpened(!opened)}>
                    <span
                        className="lbaic-settings-table-accordion-body-label lbaic-settings-cb-pw-table-accordion-body-label">
                        {fieldIndex + 1}
                    </span>
                </div>
                <div
                    className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-body-item"
                    onClick={() => setOpened(!opened)}>
                    <div className="lbaic-settings-actions-pi-table-title-wrapper">
                        <span
                            className={`lbaic-settings-table-accordion-body-label lbaic-settings-cb-pw-table-accordion-body-label${!field.label ? ' lbaic-settings-cb-pw-table-card-body-label-null' : ''}`}>
                            {field.label || __("no label", 'limb-chatbot')}
                        </span>
                        {Boolean(field.required) && (
                            <Badge label={__("Required", 'limb-chatbot')} isSmall={true}
                                   className='lbaic-settings-badge-red'/>
                        )}
                    </div>
                    <button
                        className="lbaic-settings-cb-pw-table-actions-item lbaic-settings-cb-pw-table-actions-edit lbaic-settings-cb-pw-button-primary lbaic-settings-button-reset"
                        onClick={(e) => {
                            e.stopPropagation();
                            setOpened(!opened);
                        }}>
                        <svg className="lbaic-settings-cb-pw-table-accordion-body-i"
                             xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <use href="#lbaic-settings-edit"/>
                        </svg>
                    </button>
                </div>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions">
                    <div className="lbaic-settings-cb-pw-table-actions-in lbaic-settings-cb-pw-table-actions-nested-in">
                        <button
                            className='lbaic-settings-cb-pw-table-actions-item lbaic-settings-cb-pw-button-primary lbaic-settings-button-reset'
                            onClick={() => deleteField(fieldIndex)}>
                            <svg className="lbaic-settings-cb-pw-table-accordion-body-i"
                                 xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <use href="#lbaic-settings-delete"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
            <div
                className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-details lbaic-settings-cb-pw-table-accordion-details${opened ? ' opened' : ''}`}>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-table-accordion-details-in">
                    <div
                        className="lbaic-settings-table-accordion-content lbaic-settings-cb-pw-table-accordion-content">
                        <div className="lbaic-settings-divider-gap-end-inner"/>
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Input
                                    value={field.label || ''}
                                    setValue={value => updateField(fieldIndex, 'label', value)}
                                    placeholder={__("Label", 'limb-chatbot')}
                                />
                            </div>
                            <div className="lbaic-settings-column-in">
                                <Input
                                    value={field.placeholder || ''}
                                    setValue={value => updateField(fieldIndex, 'placeholder', value)}
                                    placeholder={__("Placeholder", 'limb-chatbot')}
                                />
                            </div>
                        </div>
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Checkbox
                                    isChecked={field.required || false}
                                    toggleValue={() => toggleFieldRequired(fieldIndex)}
                                    label={__("Required", 'limb-chatbot')}
                                    className='lbaic-settings-checkbox-h-42'
                                />
                            </div>
                            <div className="lbaic-settings-column-in"/>
                        </div>
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Toggle
                                    isActive={showLeadCaptureDropdown}
                                    onClick={() => {
                                        const newValue = !showLeadCaptureDropdown;
                                        setShowLeadCaptureDropdown(newValue);
                                        if (!newValue) {
                                            updateFieldConfig(fieldIndex, 'lead_capture_map_field', '');
                                        }
                                    }}
                                    label={__("Lead capture field", 'limb-chatbot')}
                                />
                                <Description>{__("Mark this field as a lead capture field", 'limb-chatbot')}</Description>
                            </div>
                            <div className="lbaic-settings-column-in">
                                {showLeadCaptureDropdown && (
                                    <>
                                        <LeadFieldMap
                                            value={field.config?.lead_capture_map_field ?? ''}
                                            setValue={(value) => updateFieldConfig(fieldIndex, 'lead_capture_map_field', value)}
                                            placeholder={__("Map to Leads column", 'limb-chatbot')}
                                            notifications={notifications}
                                        />
                                        <Description>{__("Select which Leads table column to map this field to.", 'limb-chatbot')}</Description>
                                    </>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
