import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { listFromSatResponse, getLocationDisplayName, getLocationRowId } from '../../../utils/satApiResponse';
import { FORMS_URL, FORMS_LOGS_URL, FORMS_TYPE_URL, QUESTIONS_URL, LOCATIONS_URL, QUESTION_TYPE_URL } from '../../../utils/config';
import SuccessPopup from '../../common/SuccessPopup';
import ErrorPopup from '../../common/ErrorPopup';
import { useScrollToError } from '../../../hooks/useScrollToError';
import { getUserIdFromToken } from '../../../utils/authUtils';
import './styles/CreateForm.css';
import './styles/UpdateForm.css';

const UpdateForm = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const [formData, setFormData] = useState({
        form_type_id: '',
        form_parent_id: '',
        title: '',
        description: '',
        created_date: '',
        end_date: '',
        question_ids: [],
        location_ids: []
    });
    const [formTypes, setFormTypes] = useState([]);
    const [questions, setQuestions] = useState([]);
    const [locations, setLocations] = useState([]);
    const [questionTypes, setQuestionTypes] = useState([]);
    const [fetchingData, setFetchingData] = useState(true);
    const [error, setError] = useState(null);
    const [showPopup, setShowPopup] = useState(false);
    const [popupMessage, setPopupMessage] = useState('Form saved successfully!');
    const [saving, setSaving] = useState(false);
    const [originalFormData, setOriginalFormData] = useState(null);

    const [showNewQuestionModal, setShowNewQuestionModal] = useState(false);
    const [newQuestion, setNewQuestion] = useState({ question: '', question_type_id: '', options: [''] });
    const [savingQuestion, setSavingQuestion] = useState(false);

    const questionTypeNeedsOptions = (questionTypeId) => {
        if (!questionTypeId) return false;
        const type = questionTypes.find(t => String(t.question_type_id) === String(questionTypeId));
        if (!type) return false;
        const name = (type.question_type || type.type_name || type.name || '').toLowerCase();
        const id = parseInt(type.question_type_id, 10);
        return [4, 5].includes(id) || name.includes('dropdown') || name.includes('choice');
    };

    useScrollToError(error);

    useEffect(() => {
        if (!id) {
            navigate('/update-forms', { replace: true });
            return;
        }
    }, [id, navigate]);

    useEffect(() => {
        if (!id) return;

        const fetchData = async () => {
            try {
                setFetchingData(true);
                setError(null);
                const settled = await Promise.allSettled([
                    axiosInstance.get(FORMS_TYPE_URL),
                    axiosInstance.get(QUESTIONS_URL),
                    axiosInstance.get(LOCATIONS_URL),
                    axiosInstance.get(QUESTION_TYPE_URL),
                    axiosInstance.get(`${FORMS_URL}/${id}`)
                ]);

                const [ft, qy, loc, qt, formRes] = settled;

                if (ft.status === 'fulfilled') setFormTypes(listFromSatResponse(ft.value));
                else console.error('UpdateForm: form types:', ft.reason);

                if (qy.status === 'fulfilled') setQuestions(listFromSatResponse(qy.value));
                else console.error('UpdateForm: questions:', qy.reason);

                if (loc.status === 'fulfilled') setLocations(listFromSatResponse(loc.value));
                else console.error('UpdateForm: locations:', loc.reason);

                if (qt.status === 'fulfilled') setQuestionTypes(listFromSatResponse(qt.value));
                else console.error('UpdateForm: question types:', qt.reason);

                if (formRes.status === 'fulfilled') {
                    const formResponse = formRes.value;
                    if (formResponse.data?.success && formResponse.data?.data) {
                        loadFormData(formResponse.data.data);
                    } else {
                        setError('Failed to load form details. Please try again.');
                    }
                } else {
                    console.error('UpdateForm: form detail:', formRes.reason);
                    setError('Failed to load form details. Please try again.');
                }
            } catch (err) {
                console.error('Error fetching data:', err);
                setError('Failed to load form data. Please refresh the page.');
            } finally {
                setFetchingData(false);
            }
        };

        fetchData();
    }, [id]);

    const loadFormData = (form) => {
        // Handle question_ids from multiple API response shapes.
        // Backend commonly returns `sat_questions`; older shapes may use `questions`.
        let questionIds = [];
        const questionList = Array.isArray(form.sat_questions)
            ? form.sat_questions
            : Array.isArray(form.questions)
                ? form.questions
                : [];
        if (questionList.length > 0) {
            // Extract question IDs from question objects and ensure they are numbers
            questionIds = questionList
                .map(q => {
                    const id = q.question_id || q.id;
                    return id != null ? parseInt(id) : null;
                })
                .filter(id => id != null && !isNaN(id));
        } else if (form.question_ids && Array.isArray(form.question_ids)) {
            // Fallback: if question_ids is already an array of IDs, ensure they are numbers
            questionIds = form.question_ids
                .map(id => parseInt(id))
                .filter(id => !isNaN(id));
        }

        // Handle location_ids similarly
        let locationIds = [];
        if (form.locations && Array.isArray(form.locations)) {
            // Extract location IDs from location objects and ensure they are numbers
            locationIds = form.locations
                .map(l => {
                    const id = l.location_id || l.id;
                    return id != null ? parseInt(id) : null;
                })
                .filter(id => id != null && !isNaN(id));
        } else if (form.location_ids && Array.isArray(form.location_ids)) {
            // Fallback: if location_ids is already an array of IDs, ensure they are numbers
            locationIds = form.location_ids
                .map(id => parseInt(id))
                .filter(id => !isNaN(id));
        }

        console.log('Loading form data:', form);
        console.log('Form questions:', form.questions || form.sat_questions);
        console.log('Form locations:', form.locations);
        console.log('Extracted question_ids:', questionIds);
        console.log('Extracted location_ids:', locationIds);

        const data = {
            form_type_id: form.form_type_id || '',
            form_parent_id: form.form_parent_id || '',
            title: form.title || '',
            description: form.description || '',
            created_date: form.created_date ? form.created_date.slice(0, 16) : '',
            end_date: form.end_date ? form.end_date.slice(0, 16) : '',
            question_ids: questionIds,
            location_ids: locationIds
        };
        setFormData(data);
        setOriginalFormData(data);
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    // Add question to form (when adding a main question, auto-include its child questions)
    const addQuestionToForm = (question) => {
        const questionId = typeof question === 'object' ? question.question_id : question;
        const childIds = (typeof question === 'object' && question?.child_question_ids) ? question.child_question_ids : [];
        const idsToAdd = [questionId, ...childIds];
        setFormData(prev => {
            const next = [...prev.question_ids];
            idsToAdd.forEach(id => {
                if (!next.includes(id)) next.push(id);
            });
            return { ...prev, question_ids: next };
        });
    };

    // Remove question from form (when removing a main question, auto-remove its child questions)
    const removeQuestionFromForm = (question) => {
        const questionId = typeof question === 'object' ? question.question_id : question;
        const childIds = (typeof question === 'object' && question?.child_question_ids) ? question.child_question_ids : [];
        const idsToRemove = new Set([questionId, ...childIds]);
        setFormData(prev => ({
            ...prev,
            question_ids: prev.question_ids.filter(id => !idsToRemove.has(id))
        }));
    };

    const addOptionRow = () => setNewQuestion(prev => ({ ...prev, options: [...(prev.options || ['']), ''] }));
    const removeOptionRow = (index) => setNewQuestion(prev => ({
        ...prev,
        options: prev.options.filter((_, i) => i !== index).length ? prev.options.filter((_, i) => i !== index) : ['']
    }));
    const setOptionValue = (index, value) => setNewQuestion(prev => ({
        ...prev,
        options: prev.options.map((o, i) => i === index ? value : o)
    }));

    // Create new question and add to form
    const handleCreateQuestion = async () => {
        if (!newQuestion.question.trim()) {
            alert('Please enter a question text.');
            return;
        }

        if (!newQuestion.question_type_id || newQuestion.question_type_id === '') {
            alert('Please select a question type.');
            return;
        }

        const needsOptions = questionTypeNeedsOptions(newQuestion.question_type_id);
        const optionsList = (newQuestion.options || ['']).map(o => (o || '').trim()).filter(Boolean);
        if (needsOptions && optionsList.length === 0) {
            setError('Please add at least one option for this question type.');
            return;
        }

        setSavingQuestion(true);
        try {
            const userId = getUserIdFromToken();
            const payload = {
                question: newQuestion.question.trim(),
                question_type_id: parseInt(newQuestion.question_type_id),
                allows_media: false
            };
            if (needsOptions && optionsList.length > 0) payload.options = optionsList;
            const response = await axiosInstance.post(QUESTIONS_URL, payload);

            if (response.data.success) {
                // Fetch the created question to get full details
                const questionId = response.data.data?.question_id;
                if (questionId) {
                    const questionResponse = await axiosInstance.get(`${QUESTIONS_URL}/${questionId}`);
                    if (questionResponse.data.success) {
                        const createdQuestion = questionResponse.data.data;
                        // Add to questions list
                        setQuestions(prev => [...prev, createdQuestion]);
                        // Automatically add to form
                        addQuestionToForm(createdQuestion.question_id);
                    }
                }
                // Reset modal
                setNewQuestion({ question: '', question_type_id: '', options: [''] });
                setShowNewQuestionModal(false);
                setShowPopup(true);
            }
        } catch (error) {
            console.error('Error creating question:', error);
            setError(error.response?.data?.message || 'Failed to create question. Please try again.');
        } finally {
            setSavingQuestion(false);
        }
    };

    // Handle location checkbox (store as numbers so all selected locations are sent and saved)
    const handleLocationChange = (locationId) => {
        const id = parseInt(locationId, 10);
        if (isNaN(id)) return;
        setFormData(prev => {
            const currentIds = prev.location_ids;
            const hasId = currentIds.some(lid => parseInt(lid, 10) === id);
            const newIds = hasId
                ? currentIds.filter(lid => parseInt(lid, 10) !== id)
                : [...currentIds, id];
            return { ...prev, location_ids: newIds };
        });
    };

    // Compare arrays (order-independent) for question_ids and location_ids
    const arraysEqual = (a, b) => {
        if (!a && !b) return true;
        if (!a || !b || a.length !== b.length) return false;
        const sa = [...a].sort((x, y) => (x || 0) - (y || 0));
        const sb = [...b].sort((x, y) => (x || 0) - (y || 0));
        return sa.every((v, i) => v === sb[i]);
    };

    const hasFormChanges = () => {
        if (!originalFormData) return true; // No baseline, treat as changed
        const o = originalFormData;
        return (
            String(formData.form_type_id) !== String(o.form_type_id) ||
            String(formData.title || '').trim() !== String(o.title || '').trim() ||
            String(formData.description || '').trim() !== String(o.description || '').trim() ||
            !arraysEqual(formData.question_ids || [], o.question_ids || []) ||
            !arraysEqual(formData.location_ids || [], o.location_ids || [])
        );
    };

    // Only question changes should create a new version
    const hasQuestionChanges = () => {
        if (!originalFormData) return false;
        return !arraysEqual(formData.question_ids || [], originalFormData.question_ids || []);
    };

    // Location/metadata changes (no question change) → update in place, logged in form logs
    const hasOnlyNonQuestionChanges = () => {
        return hasFormChanges() && !hasQuestionChanges();
    };

    // Save: new version only when questions change; otherwise update in place (shown in form logs)
    const handleSave = async (e) => {
        e.preventDefault();

        if (!id) {
            setError('Form not found. Please go back and select a form.');
            return;
        }

        const userId = getUserIdFromToken();
        if (!userId) {
            setError('User not authenticated. Please login again.');
            return;
        }

        if (!formData.form_type_id || !formData.title?.trim()) {
            setError('Form type and title are required.');
            return;
        }

        if (!hasFormChanges()) {
            setPopupMessage('No changes to save. Edit the form and click Save.');
            setShowPopup(true);
            return;
        }

        setSaving(true);
        setError(null);

        try {
            if (hasQuestionChanges()) {
                // Ensure location_ids is always an array of numbers so backend stores all locations
                const locationIds = Array.isArray(formData.location_ids)
                ? formData.location_ids.map(lid => parseInt(lid, 10)).filter(n => !isNaN(n))
                : [];
                // Create new version only when questions change
                const payload = {
                    form_type_id: parseInt(formData.form_type_id),
                    title: formData.title.trim(),
                    created_by: userId,
                    form_parent_id: parseInt(id),
                    ...(formData.description?.trim() && { description: formData.description.trim() }),
                    ...(formData.question_ids?.length > 0 && { question_ids: formData.question_ids }),
                    ...(formData.location_ids?.length > 0 && { location_ids: formData.location_ids })
                };

                const response = await axiosInstance.post(FORMS_URL, payload);

                if (response.data.success) {
                    const newFormId = response.data.data?.form_id;
                    setPopupMessage(
                        newFormId
                            ? 'New version saved successfully! You are now editing the new version.'
                            : 'New version saved successfully!'
                    );
                    setShowPopup(true);
                    if (newFormId) {
                        navigate(`/update-forms/${newFormId}`, { replace: true });
                    }
                } else {
                    setError(response.data.message || 'Failed to save new version.');
                }
                try {
                    await axiosInstance.post(FORMS_LOGS_URL, {
                        form_id: parseInt(id, 10),
                        user_id: userId,
                        action: 'UPDATED'
                    });
                } catch (logErr) {
                    console.warn('Form log sub-API (form_logs) failed:', logErr?.response?.data || logErr.message);
                }
            } else {
                // Only location/metadata changed → update current form in place (logged in form logs)
                const payload = {
                    form_type_id: parseInt(formData.form_type_id),
                    title: formData.title.trim(),
                    ...(formData.description?.trim() !== undefined && { description: formData.description.trim() }),
                    question_ids: formData.question_ids,
                    location_ids: formData.location_ids || [],
                    updated_by: userId
                };

                const response = await axiosInstance.put(`${FORMS_URL}/${id}`, payload);

                if (response.data.success) {
                    setPopupMessage('Form updated successfully. Changes are recorded in form logs.');
                    setShowPopup(true);
                    setOriginalFormData({ ...formData });
                } else {
                    setError(response.data.message || 'Failed to update form.');
                }
            }
        } catch (error) {
            console.error('Error saving form:', error);
            setError(error.response?.data?.message || 'Failed to save. Please try again.');
        } finally {
            setSaving(false);
        }
    };

    // Get selected questions details - ensure proper type comparison
    const selectedQuestions = questions.filter(q => {
        const qId = parseInt(q.question_id);
        return formData.question_ids.some(id => parseInt(id) === qId);
    });
    // In the builder, only show main questions in the Available list; child questions are managed automatically
    const availableQuestions = questions.filter(q => {
        if (q.main_question_id != null) return false;
        const qId = parseInt(q.question_id);
        return !formData.question_ids.some(id => parseInt(id) === qId);
    });

    if (!id) return null;

    if (fetchingData) {
        return (
            <div className="create-form-container">
                <div style={{ textAlign: 'center', padding: '2rem' }}>
                    <p>Loading form data...</p>
                </div>
            </div>
        );
    }

    return (
        <>
            <SuccessPopup
                show={showPopup}
                message={popupMessage}
                onClose={() => {
                    setShowPopup(false);
                    navigate('/view-forms');
                }}
                onOk={() => {
                    setShowPopup(false);
                    navigate('/view-forms');
                }}
            />
            <ErrorPopup
                show={!!error}
                message={error || ''}
                onClose={() => setError(null)}
            />
            <div className="create-form-container">
                <div className="create-form-header">
                    <h1 className="create-form-title">Update Form</h1>
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={() => navigate('/update-forms')}
                    >
                        Back to list
                    </button>
                </div>

                {error && (
                    <div className="error-message">
                        {error}
                    </div>
                )}

            {id && (
                <form onSubmit={handleSave}>
                    {/* Basic Form Fields */}
                    <div className="form-grid">
                        <div className="form-group">
                            <label htmlFor="form_type_id" className="form-label">
                                Form Type <span style={{ color: 'red' }}>*</span>
                            </label>
                            <select
                                id="form_type_id"
                                name="form_type_id"
                                className="form-input"
                                value={formData.form_type_id}
                                onChange={handleChange}
                                disabled
                            >
                                <option value="">Select Form Type</option>
                                {formTypes.map(type => (
                                    <option key={type.form_type_id} value={type.form_type_id}>
                                        {type.form_type}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="form-group">
                            <label htmlFor="title" className="form-label">
                                Form Title <span style={{ color: 'red' }}>*</span>
                            </label>
                            <input
                                type="text"
                                id="title"
                                name="title"
                                className="form-input"
                                value={formData.title}
                                onChange={handleChange}
                                placeholder="Enter form title"
                                disabled
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label htmlFor="description" className="form-label">
                            Description
                        </label>
                        <textarea
                            id="description"
                            name="description"
                            className="form-textarea"
                            value={formData.description}
                            onChange={handleChange}
                            placeholder="Enter form description"
                            rows="3"
                        />
                    </div>

                    {/* Questions Management Section */}
                    <div className="question-management-section">
                        <div className="section-header">
                            <h2 className="section-title">Manage Questions</h2>
                            <button
                                type="button"
                                className="btn btn-add"
                                onClick={() => {
                                    setError(null);
                                    setNewQuestion({ question: '', question_type_id: '', options: [''] });
                                    setShowNewQuestionModal(true);
                                }}
                            >
                                + Create New Question
                            </button>
                        </div>

                        {/* Selected Questions */}
                        <div className="questions-panel">
                            <h3 className="panel-title">
                                Selected Questions ({selectedQuestions.length})
                            </h3>
                            <div className="questions-list selected">
                                {selectedQuestions.length === 0 ? (
                                    <div className="empty-state">No questions added to this form yet.</div>
                                ) : (
                                    selectedQuestions.map((question, index) => (
                                            <div
                                                key={question.question_id}
                                                className="question-card selected"
                                            >
                                                <span className="question-order">{index + 1}</span>
                                                <span className="question-text">{question.question}</span>
                                                <button
                                                    type="button"
                                                    className="btn-icon btn-remove"
                                                    onClick={() => removeQuestionFromForm(question)}
                                                    title="Remove from form"
                                                >
                                                    ✕
                                                </button>
                                            </div>
                                        ))
                                )}
                            </div>
                        </div>

                        {/* Available Questions */}
                        <div className="questions-panel">
                            <h3 className="panel-title">
                                Available Questions ({availableQuestions.length})
                            </h3>
                            <div className="questions-list available">
                                {availableQuestions.length === 0 ? (
                                    <div className="empty-state">All questions are already added.</div>
                                ) : (
                                    availableQuestions.map(question => (
                                        <div key={question.question_id} className="question-card available">
                                            <span className="question-text">{question.question}</span>
                                            <button
                                                type="button"
                                                className="btn-icon btn-add-small"
                                                onClick={() => addQuestionToForm(question)}
                                                title="Add to form"
                                            >
                                                +
                                            </button>
                                        </div>
                                    ))
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Locations Section - same design as Create Form */}
                    <div className="form-group location-sites-section" style={{ marginTop: '2rem' }}>
                        <label className="form-label location-sites-section__title">Update Sites</label>
                        <p className="location-sites-section__hint">Select sites from any country below.</p>
                        {(() => {
                            const byCountry = (locations || []).reduce((acc, loc) => {
                                const key = loc.country_id ?? 'unknown';
                                const name = loc.country_name || `Country ${key}`;
                                if (!acc[key]) acc[key] = { countryName: name, locations: [] };
                                acc[key].locations.push(loc);
                                return acc;
                            }, {});
                            const countryKeys = Object.keys(byCountry).sort((a, b) =>
                                (byCountry[a].countryName || '').localeCompare(byCountry[b].countryName || '')
                            );
                            if (countryKeys.length === 0) {
                                return (
                                    <div className="location-sites-empty">
                                        <span className="location-sites-empty__icon">📍</span>
                                        <p>No locations available.</p>
                                    </div>
                                );
                            }
                            return (
                                <div className="location-sites-cards">
                                    {countryKeys.map(countryId => {
                                        const { countryName, locations: locs } = byCountry[countryId];
                                        return (
                                            <div key={countryId} className="location-sites-card">
                                                <div className="location-sites-card__header">
                                                    <span className="location-sites-card__title">{countryName}</span>
                                                    <span className="location-sites-card__badge">{locs.length} site{locs.length !== 1 ? 's' : ''}</span>
                                                </div>
                                                <div className="location-sites-card__list">
                                                    {locs.map((site, idx) => {
                                                        const siteId = getLocationRowId(site);
                                                        const isSiteSelected = formData.location_ids.some(
                                                            (lid) => parseInt(lid, 10) === siteId
                                                        );
                                                        return (
                                                            <button
                                                                key={Number.isFinite(siteId) ? siteId : `site-row-${idx}`}
                                                                type="button"
                                                                className={`location-site-tile ${isSiteSelected ? 'location-site-tile--selected' : ''}`}
                                                                onClick={() => handleLocationChange(siteId)}
                                                            >
                                                                <span className="location-site-tile__check">{isSiteSelected ? '✓' : ''}</span>
                                                                <span className="location-site-tile__name">{getLocationDisplayName(site)}</span>
                                                                {(site.location_type || site.Location_type) && (
                                                                    <span className="location-site-tile__type">{site.location_type || site.Location_type}</span>
                                                                )}
                                                            </button>
                                                        );
                                                    })}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            );
                        })()}
                        <div className="location-sites-summary">
                            <span className="location-sites-summary__count">{formData.location_ids.length}</span>
                            <span>site{formData.location_ids.length !== 1 ? 's' : ''} selected</span>
                        </div>
                    </div>

                    {/* Form Actions */}
                    <div className="form-actions">
                        <button
                            type="button"
                            className="btn btn-secondary"
                            onClick={async () => {
                                if (id) {
                                    try {
                                        setFetchingData(true);
                                        const response = await axiosInstance.get(`${FORMS_URL}/${id}`);
                                        if (response.data.success && response.data.data) {
                                            loadFormData(response.data.data);
                                        }
                                    } catch (error) {
                                        console.error('Error resetting form:', error);
                                        setError('Failed to reset form. Please try again.');
                                    } finally {
                                        setFetchingData(false);
                                    }
                                }
                            }}
                        >
                            Reset Changes
                        </button>
                        <button
                            type="submit"
                            className="btn btn-primary"
                            disabled={saving}
                            title={hasFormChanges() ? (hasQuestionChanges() ? 'Save as new version (questions changed)' : 'Save changes (location/metadata only; no new version)') : 'No changes to save'}
                        >
                            {saving ? 'Saving...' : 'Save'}
                        </button>
                    </div>
                </form>
            )}
        </div>

            {/* New Question Modal - rendered outside create-form-container so position:fixed works on mobile */}
            {showNewQuestionModal && (
                <div className="modal-overlay" onClick={() => {
                    setShowNewQuestionModal(false);
                    setNewQuestion({ question: '', question_type_id: '', options: [''] });
                }}>
                    <div className="modal-content" onClick={e => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2>Create New Question</h2>
                        </div>
                        <div className="modal-body">
                            <div className="form-group">
                                <label className="form-label">Question Text <span style={{ color: 'red' }}>*</span></label>
                                <textarea
                                    className="form-textarea"
                                    value={newQuestion.question}
                                    onChange={(e) => setNewQuestion(prev => ({ ...prev, question: e.target.value }))}
                                    placeholder="Enter question text..."
                                    rows="3"
                                />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Question Type <span style={{ color: 'red' }}>*</span></label>
                                <select
                                    className="form-input"
                                    value={newQuestion.question_type_id}
                                    onChange={(e) => setNewQuestion(prev => ({ ...prev, question_type_id: e.target.value }))}
                                    required
                                >
                                    <option value="">Select Question Type</option>
                                    {questionTypes.map(type => (
                                        <option key={type.question_type_id} value={type.question_type_id}>
                                            {type.question_type}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            {questionTypeNeedsOptions(newQuestion.question_type_id) && (
                                <div className="form-group question-options-group">
                                    <label className="form-label">Options <span style={{ color: 'red' }}>*</span></label>
                                    <p className="form-hint">Add at least one option. These will appear as choices or dropdown items.</p>
                                    <div className="question-options-list">
                                        {(newQuestion.options || ['']).map((opt, index) => (
                                            <div key={index} className="question-option-row">
                                                <input
                                                    type="text"
                                                    className="form-input question-option-input"
                                                    value={opt}
                                                    onChange={(e) => setOptionValue(index, e.target.value)}
                                                    placeholder={`Option ${index + 1}`}
                                                />
                                                <button
                                                    type="button"
                                                    className="btn btn-icon-remove question-option-remove"
                                                    onClick={() => removeOptionRow(index)}
                                                    title="Remove option"
                                                    aria-label="Remove option"
                                                    disabled={(newQuestion.options || []).length <= 1}
                                                >
                                                    −
                                                </button>
                                            </div>
                                        ))}
                                        <button
                                            type="button"
                                            className="btn btn-secondary question-option-add"
                                            onClick={addOptionRow}
                                        >
                                            + Add option
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => {
                                    setShowNewQuestionModal(false);
                                    setNewQuestion({ question: '', question_type_id: '', options: [''] });
                                }}
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                className="btn btn-primary"
                                onClick={handleCreateQuestion}
                                disabled={savingQuestion}
                            >
                                {savingQuestion ? 'Creating...' : 'Create & Add'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
};

export default UpdateForm;
