import React, { useState, useEffect, useLayoutEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { FORMS_FOR_SELECTION_URL } from '../../../utils/config';
import './styles/CreateForm.css';
import './styles/UpdateForm.css';

const SelectFormToUpdate = () => {
    const navigate = useNavigate();
    const [existingForms, setExistingForms] = useState([]);
    const [fetchingData, setFetchingData] = useState(true);
    const [error, setError] = useState(null);
    const [selectedFormId, setSelectedFormId] = useState('');
    const [formSearchQuery, setFormSearchQuery] = useState('');
    const [formDropdownOpen, setFormDropdownOpen] = useState(false);
    const [dropdownPosition, setDropdownPosition] = useState(null);
    const formComboboxRef = useRef(null);
    const dropdownListRef = useRef(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                setFetchingData(true);
                const formsRes = await axiosInstance.get(FORMS_FOR_SELECTION_URL);
                setExistingForms(formsRes?.data?.data ?? formsRes?.data ?? []);
            } catch (err) {
                console.error('Error fetching forms:', err);
                setError('Failed to load forms. Please refresh the page.');
            } finally {
                setFetchingData(false);
            }
        };
        fetchData();
    }, []);

    useLayoutEffect(() => {
        if (!formDropdownOpen) {
            setDropdownPosition(null);
            return;
        }
        const input = formComboboxRef.current?.querySelector('input.form-combobox-input');
        if (!input) return;
        const update = () => {
            const rect = input.getBoundingClientRect();
            setDropdownPosition({
                top: rect.bottom + 6,
                left: rect.left,
                width: rect.width
            });
        };
        update();
        window.addEventListener('scroll', update, true);
        window.addEventListener('resize', update);
        return () => {
            window.removeEventListener('scroll', update, true);
            window.removeEventListener('resize', update);
        };
    }, [formDropdownOpen]);

    useEffect(() => {
        const handleClickOutside = (e) => {
            const inCombobox = formComboboxRef.current?.contains(e.target);
            const inDropdown = dropdownListRef.current?.contains(e.target);
            if (!inCombobox && !inDropdown) {
                setFormDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleSelectForm = (formId) => {
        setSelectedFormId(formId);
        const form = existingForms.find(f => String(f.form_id) === String(formId));
        if (form) {
            setFormSearchQuery(`${form.title || ''} (v${form.version || 1})`);
        }
        setFormDropdownOpen(false);
    };

    const handleEditForm = () => {
        if (selectedFormId) {
            navigate(`/update-forms/${selectedFormId}`);
        }
    };

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

    return (
        <div className="create-form-container">
            <div className="create-form-header">
                <h1 className="create-form-title">Update Form</h1>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/dashboard')}
                >
                    Cancel
                </button>
            </div>

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

            <div
                className={`form-combobox-wrapper${formDropdownOpen ? ' form-combobox-wrapper--open' : ''}`}
                ref={formComboboxRef}
                style={{ marginBottom: '2rem' }}
            >
                <label htmlFor="form_combobox" className="form-label">
                    Select Form to Update <span style={{ color: 'red' }}>*</span>
                </label>
                <input
                    type="text"
                    id="form_combobox"
                    className="form-input form-combobox-input"
                    placeholder="Search or select a form..."
                    value={formSearchQuery}
                    onChange={(e) => {
                        setFormSearchQuery(e.target.value);
                        setFormDropdownOpen(true);
                    }}
                    onFocus={() => setFormDropdownOpen(true)}
                    autoComplete="off"
                    aria-label="Search or select form"
                    aria-expanded={formDropdownOpen}
                    aria-haspopup="listbox"
                />
            </div>

            {formDropdownOpen && dropdownPosition && ReactDOM.createPortal(
                <div
                    ref={dropdownListRef}
                    className="form-combobox-list-portal"
                    style={{
                        position: 'fixed',
                        top: dropdownPosition.top,
                        left: dropdownPosition.left,
                        width: dropdownPosition.width,
                        zIndex: 10000
                    }}
                >
                    <ul
                        className="form-combobox-list"
                        role="listbox"
                        aria-label="Forms"
                    >
                        {(() => {
                            const query = (formSearchQuery || '').trim().toLowerCase();
                            const filtered = query
                                ? existingForms.filter(
                                    form =>
                                        (form.title || '').toLowerCase().includes(query) ||
                                        String(form.version || 1).includes(query)
                                )
                                : existingForms;
                            if (filtered.length === 0) {
                                return (
                                    <li className="form-combobox-item form-combobox-item--empty" role="option">
                                        No forms match your search.
                                    </li>
                                );
                            }
                            return filtered.map(form => {
                                const label = `${form.title} (v${form.version || 1})`;
                                const isSelected = String(form.form_id) === String(selectedFormId);
                                return (
                                    <li
                                        key={form.form_id}
                                        className={`form-combobox-item ${isSelected ? 'form-combobox-item--selected' : ''}`}
                                        role="option"
                                        aria-selected={isSelected}
                                        onClick={() => handleSelectForm(String(form.form_id))}
                                    >
                                        {label}
                                    </li>
                                );
                            });
                        })()}
                    </ul>
                </div>,
                document.body
            )}

            <div className="form-actions" style={{ marginTop: '1rem' }}>
                <button
                    type="button"
                    className="btn btn-primary"
                    onClick={handleEditForm}
                    disabled={!selectedFormId}
                >
                    Edit Form
                </button>
            </div>
        </div>
    );
};

export default SelectFormToUpdate;
