import {useMemo, useState} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import {marked} from "marked";
import {validateEmailInput} from "../inputs/email";
import ButtonPrimary from "../../button/primary";
import {generateUniqueId} from "../../../../../helpers";

export default function LeadCapture({
                                        widget,
                                        sendUserMessage,
                                        userMessageArgsRef,
                                        setShowLeadCaptureWidget,
                                        chatbotUtility,
                                        isInPreviewMode
                                    }) {
    // Get all fields
    const visibleFields = widget?.data?.fields || [];
    const [captureError, setCaptureError] = useState(false);

    const uniqueId = useMemo(() => generateUniqueId(), []);

    // Initialize form state
    const [formData, setFormData] = useState(() => {
        const initial = {};
        visibleFields.forEach(field => {
            initial[field.name] = '';
        });
        return initial;
    });

    const [errors, setErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Handle input change
    const handleInputChange = (name, value, field) => {
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));

        // Validate
        if (field.type === 'email') {
            if (!value.trim()) {
                setErrors(prev => ({
                    ...prev,
                    [name]: field.required
                }));
            } else {
                setErrors(prev => ({
                    ...prev,
                    [name]: !validateEmailInput(value)
                }));
            }
        } else if (field?.required) {
            setErrors(prev => ({
                ...prev,
                [name]: !value.trim()
            }));
        }
    };

    // Validate form
    const validateForm = () => {
        const newErrors = {};

        visibleFields.forEach(field => {
            const value = formData[field.name] || '';

            if (field.required && !value.trim()) {
                newErrors[field.name] = true;
            } else if (field.type === 'email' && value.trim()) {
                // Basic email validation
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(value.trim())) {
                    newErrors[field.name] = true;
                }
            }
        });

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // Handle form submission
    const handleSubmit = async () => {
        if (!validateForm()) {
            return;
        }

        if (!isInPreviewMode) {
            setIsSubmitting(true);
            // Send lead capture data
            const res = await chatbotUtility?.widgetCallback(widget.id, formData);

            if (!res.success) {
                setCaptureError(res.data.message || __("Something went wrong. Please try again.", 'limb-chatbot'));
                setIsSubmitting(false);
                return;
            }

            LimbChatbot.Hooks.doAction('limb.chatbot.lead_captured', res);

            setIsSubmitting(false);
        }

        setShowLeadCaptureWidget(false);

        // If there's a pending message to send after lead capture, send
        if (userMessageArgsRef?.current) {
            userMessageArgsRef.current[userMessageArgsRef.current.length - 1].ignoreLeadCapture = true;
            // Then send the original message
            await sendUserMessage(...userMessageArgsRef.current);
            userMessageArgsRef.current = null;
        }
    };

    if (!widget?.data) {
        return null;
    }

    const heading = widget.data.heading || '';
    const description = widget.data.description || '';
    const submitButtonText = widget.data.submit_button_text || __("Start chat", 'limb-chatbot');

    // Check if button should be disabled
    const hasRequiredFieldsEmpty = visibleFields.some(field => {
        if (field.required) {
            const value = formData[field.name] || '';
            return !value.trim();
        }
        return false;
    });

    const isButtonDisabled = isSubmitting || hasRequiredFieldsEmpty || Object.values(errors).some(Boolean);

    const onKeyDown = (e) => {
        if (e.key === 'Enter' && !isButtonDisabled) {
            handleSubmit();
        }
    }

    return (
        <div className='lbaic-lead-capture'>
            <div className='lbaic-lead-capture-container'>
                {(heading || description) && (
                    <div className='lbaic-lead-capture-header'>
                        {heading && (
                            <h3 className='lbaic-lead-capture-header-title'
                                dangerouslySetInnerHTML={{__html: heading}}></h3>
                        )}
                        {description && (
                            <p className='lbaic-lead-capture-header-description'
                               dangerouslySetInnerHTML={{__html: marked.parse(description)}}></p>
                        )}
                    </div>
                )}

                <div className='lbaic-lead-capture-form'>
                    <div className='lbaic-lead-capture-form-fields'>
                        {visibleFields.map((field, index) => {
                            const value = formData[field.name] || '';
                            const hasError = errors[field.name];
                            const id = `lbaic-lead-capture-form-field-${uniqueId}-${field.name}`;

                            return (
                                <div key={index} className='lbaic-lead-capture-form-field'>
                                    <label
                                        htmlFor={id}
                                        className='lbaic-lead-capture-form-field-label'
                                    >
                                        {field.label || (field.type === 'email' ? __("Email", 'limb-chatbot') : __("Name", 'limb-chatbot'))}
                                        {field.required &&
                                            <sup className='lbaic-lead-capture-form-field-label-optional'> *</sup>}
                                    </label>
                                    <input
                                        id={id}
                                        type={field.type === 'email' ? 'email' : 'text'}
                                        className={`lbaic-textarea${hasError ? ' lbaic-textarea-invalid' : ''}`}
                                        placeholder={field.placeholder || undefined}
                                        value={value}
                                        onChange={(e) => handleInputChange(field.name, e.target.value, field)}
                                        onKeyDown={onKeyDown}
                                        disabled={isSubmitting}
                                        autoComplete="off"
                                        autoFocus={index === 0}
                                    />
                                </div>
                            );
                        })}
                    </div>

                    <ButtonPrimary
                        loading={isSubmitting}
                        label={submitButtonText}
                        onClick={handleSubmit}
                        disabled={isButtonDisabled}
                        labelProps={{
                            '--lbaic-button-label-fw': 'var(--lbaic-fw-500)'
                        }}
                        style={{
                            '--lbaic-button-padding': '8px 16px'
                        }}
                    />
                    {captureError && (
                        <div className="lbaic-lead-capture-error">
                            <span className="lbaic-lead-capture-error-text">{captureError}</span>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
