import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../../utils/axiosConfig';
import { listFromSatResponse, getLocationDisplayName, getLocationRowId } from '../../../utils/satApiResponse';
import { FORMS_URL, FORMS_TYPE_URL, QUESTIONS_URL, LOCATIONS_URL, QUESTION_TYPE_URL, COUNTRY_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';

const CreateForm = () => {
    const navigate = useNavigate();
    const [formData, setFormData] = useState({
        form_type_id: '',
        title: '',
        description: '',
        question_ids: [],
        location_ids: []
    });
    const [formTypes, setFormTypes] = useState([]);
    const [questions, setQuestions] = useState([]);
    const [countries, setCountries] = useState([]);
    const [locationsByCountry, setLocationsByCountry] = useState({});
    const [selectedCountryIds, setSelectedCountryIds] = useState([]);
    const [expandedCountryIds, setExpandedCountryIds] = useState(new Set());
    const [loading, setLoading] = useState(false);
    const [fetchingData, setFetchingData] = useState(true);
    const [error, setError] = useState(null);
    const [showPopup, setShowPopup] = useState(false);
    const [popupMessage, setPopupMessage] = useState('Form created successfully!');
    const [reloadOnPopupClose, setReloadOnPopupClose] = useState(false);

    useScrollToError(error);

    // Add question from Create Form section
    const [questionTypes, setQuestionTypes] = useState([]);
    const [showNewQuestionModal, setShowNewQuestionModal] = useState(false);
    const [newQuestion, setNewQuestion] = useState({ question: '', question_type_id: '', options: [''] });
    const [savingQuestion, setSavingQuestion] = useState(false);

    // Question types that require options (multiple/single choice, dropdowns)
    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');
    };

    // Fetch form types, questions, countries, and question types on component mount.
    // Use allSettled so one failed / slow endpoint does not block others (Promise.all left every list empty).
    useEffect(() => {
        const fetchData = async () => {
            try {
                setFetchingData(true);
                const labels = ['form types', 'questions', 'countries', 'question types'];
                const settled = await Promise.allSettled([
                    axiosInstance.get(FORMS_TYPE_URL),
                    axiosInstance.get(QUESTIONS_URL),
                    axiosInstance.get(COUNTRY_URL),
                    axiosInstance.get(QUESTION_TYPE_URL)
                ]);

                const [ft, qy, co, qt] = settled;

                if (ft.status === 'fulfilled') {
                    setFormTypes(listFromSatResponse(ft.value));
                } else {
                    console.error('CreateForm: form types failed:', ft.reason?.message || ft.reason);
                }

                if (qy.status === 'fulfilled') {
                    setQuestions(listFromSatResponse(qy.value));
                } else {
                    console.error('CreateForm: questions failed:', qy.reason?.message || qy.reason);
                }

                if (co.status === 'fulfilled') {
                    setCountries(listFromSatResponse(co.value));
                } else {
                    console.error('CreateForm: countries failed:', co.reason?.message || co.reason);
                }

                if (qt.status === 'fulfilled') {
                    setQuestionTypes(listFromSatResponse(qt.value));
                } else {
                    console.error('CreateForm: question types failed:', qt.reason?.message || qt.reason);
                }

                const failed = settled.filter((s) => s.status === 'rejected');
                if (failed.length > 0) {
                    setError(
                        `Could not load: ${failed
                            .map((s, i) => (s.status === 'rejected' ? labels[i] : null))
                            .filter(Boolean)
                            .join(', ')}. Check API URL / server and refresh.`
                    );
                }
            } catch (error) {
                console.error('Error fetching data:', error);
                setError('Failed to load form data. Please refresh the page.');
            } finally {
                setFetchingData(false);
            }
        };

        fetchData();
    }, []);

    // Toggle country selection: fetch locations when adding, clear when removing
    const handleCountryToggle = async (countryId, countryName) => {
        const id = parseInt(countryId, 10);
        if (isNaN(id)) return;

        const isAdding = !selectedCountryIds.includes(id);
        if (isAdding) {
            setSelectedCountryIds(prev => [...prev, id]);
            setExpandedCountryIds(prev => new Set([...prev, id]));
            try {
                const res = await axiosInstance.get(`${LOCATIONS_URL}/country/${id}`);
                const list = listFromSatResponse(res);
                setLocationsByCountry(prev => ({
                    ...prev,
                    [id]: { countryName, locations: list }
                }));
            } catch (err) {
                console.error('Error fetching locations by country:', err);
                setLocationsByCountry(prev => ({ ...prev, [id]: { countryName, locations: [] } }));
            }
        } else {
            const removedLocIds = (locationsByCountry[id]?.locations || [])
                .map((l) => getLocationRowId(l))
                .filter((n) => Number.isFinite(n));
            setSelectedCountryIds(prev => prev.filter(cid => cid !== id));
            setExpandedCountryIds(prev => {
                const next = new Set(prev);
                next.delete(id);
                return next;
            });
            setLocationsByCountry(prev => {
                const next = { ...prev };
                delete next[id];
                return next;
            });
            setFormData(prev => ({
                ...prev,
                location_ids: (prev.location_ids || []).filter(lid => !removedLocIds.includes(parseInt(lid, 10)))
            }));
        }
    };

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

    const handleCheckboxChange = (name, idOrQuestion) => {
        setFormData(prev => {
            const currentIds = prev[name];
            if (name === 'question_ids' && idOrQuestion && typeof idOrQuestion === 'object') {
                const question = idOrQuestion;
                const questionId = question.question_id;
                const childIds = question.child_question_ids || [];
                const isAdding = !currentIds.includes(questionId);
                let newIds;
                if (isAdding) {
                    newIds = [...new Set([...currentIds, questionId, ...childIds])];
                } else {
                    const toRemove = new Set([questionId, ...childIds]);
                    newIds = currentIds.filter(id => !toRemove.has(id));
                }
                return { ...prev, [name]: newIds };
            }
            const id = typeof idOrQuestion === 'object' ? idOrQuestion?.question_id ?? idOrQuestion : idOrQuestion;
            if (name === 'location_ids') {
                const n = Number(id);
                if (!Number.isFinite(n)) return prev;
                const has = currentIds.some((lid) => Number(lid) === n);
                const newIds = has
                    ? currentIds.filter((item) => Number(item) !== n)
                    : [...currentIds, n];
                return { ...prev, [name]: newIds };
            }
            const newIds = currentIds.includes(id)
                ? currentIds.filter(item => item !== id)
                : [...currentIds, id];
            return { ...prev, [name]: newIds };
        });
    };

    // Add question to form (used when creating a new question from this page)
    const addQuestionToForm = (questionId) => {
        setFormData(prev => ({
            ...prev,
            question_ids: [...new Set([...prev.question_ids, questionId])]
        }));
    };

    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()) {
            setError('Please enter question text.');
            return;
        }
        if (!newQuestion.question_type_id || newQuestion.question_type_id === '') {
            setError('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);
        setError(null);
        try {
            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) {
                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;
                        setQuestions(prev => [...prev, createdQuestion]);
                        addQuestionToForm(createdQuestion.question_id);
                    }
                }
                setNewQuestion({ question: '', question_type_id: '', options: [''] });
                setShowNewQuestionModal(false);
                setPopupMessage('Question added to form!');
                setShowPopup(true);
            } else {
                setError(response.data.message || 'Failed to create question.');
            }
        } catch (err) {
            console.error('Error creating question:', err);
            setError(err.response?.data?.message || 'Failed to create question. Please try again.');
        } finally {
            setSavingQuestion(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

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

        // Validate required fields
        if (!formData.form_type_id || formData.form_type_id === '') {
            setError('Form Type is required.');
            setLoading(false);
            return;
        }

        if (!formData.title || formData.title.trim() === '') {
            setError('Form Title is required.');
            setLoading(false);
            return;
        }

        const formTypeId = parseInt(formData.form_type_id);
        if (isNaN(formTypeId)) {
            setError('Invalid Form Type selected.');
            setLoading(false);
            return;
        }

        try {
            const payload = {
                form_type_id: formTypeId,
                title: formData.title.trim(),
                created_by: userId
            };

            // Child forms (new versions) are created only from Update Form page, not here.

            if (formData.description && formData.description.trim() !== '') {
                payload.description = formData.description.trim();
            }
            
            if (formData.question_ids && formData.question_ids.length > 0) {
                payload.question_ids = [...new Set(formData.question_ids)];
            }
            
            if (formData.location_ids && formData.location_ids.length > 0) {
                payload.location_ids = [...new Set(formData.location_ids)];
            }

            console.log('Submitting form with payload:', payload);

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

            console.log('Form creation response:', response.data);

            if (response.data.success) {
                setPopupMessage('Form has been created');
                setReloadOnPopupClose(true);
                setShowPopup(true);
            } else {
                setError(response.data.message || 'Failed to create form. Please try again.');
            }
        } catch (error) {
            console.error('Error creating form:', error);
            console.error('Error response:', error.response);
            console.error('Error response data:', error.response?.data);
            console.error('Error response status:', error.response?.status);
            
            let errorMessage = 'Failed to create form. Please try again.';
            
            if (error.response) {
                // Server responded with error status
                errorMessage = error.response.data?.message 
                    || error.response.data?.error 
                    || `Server error: ${error.response.status} ${error.response.statusText}`;
            } else if (error.request) {
                // Request was made but no response received
                errorMessage = 'No response from server. Please check your connection.';
            } else {
                // Error in setting up the request
                errorMessage = error.message || 'An error occurred while creating the form.';
            }
            
            setError(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    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={() => {
                    if (reloadOnPopupClose) {
                        navigate('/view-forms');
                    } else {
                        setShowPopup(false);
                        setPopupMessage('Form created successfully!');
                        setReloadOnPopupClose(false);
                    }
                }}
                onOk={() => {
                    if (reloadOnPopupClose) {
                        navigate('/view-forms');
                    } else {
                        setShowPopup(false);
                        setPopupMessage('Form created successfully!');
                        setReloadOnPopupClose(false);
                    }
                }}
            />
            <ErrorPopup
                show={!!error}
                message={error || ''}
                onClose={() => setError(null)}
            />
            <div className="create-form-container">
                <div className="create-form-header">
                <h1 className="create-form-title">Create New Form</h1>
                <button
                    className="btn btn-secondary"
                    onClick={() => navigate('/dashboard')}
                >
                    Cancel
                </button>
            </div>

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

            <form onSubmit={handleSubmit}>
                <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}
                            required
                        >
                            <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"
                            required
                        />
                    </div>
                </div>

                <div className="form-grid form-grid--description-questions">
                    <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="4"
                        />
                    </div>
                    <div className="form-group">
                        <div className="form-grid-header">
                            <label className="form-label form-grid-header-label">
                                Questions (Select multiple)
                            </label>
                            <button
                                type="button"
                                className="btn btn-primary form-grid-header-btn"
                                onClick={() => {
                                    setError(null);
                                    setNewQuestion({ question: '', question_type_id: '', options: [''] });
                                    setShowNewQuestionModal(true);
                                }}
                            >
                                + Add Question
                            </button>
                        </div>
                        <div className="checkbox-list-container">
                            {questions.length === 0 ? (
                                <div style={{ padding: '0.5rem', color: '#4d4d4f' }}>No questions available</div>
                            ) : (
                                questions
                                    .filter(question => !question.main_question_id) // hide child questions in builder
                                    .map(question => {
                                    const isSelected = formData.question_ids.includes(question.question_id);
                                    return (
                                        <div key={question.question_id} className="checkbox-item">
                                            <input
                                                type="checkbox"
                                                id={`question-${question.question_id}`}
                                                className="checkbox-input"
                                                checked={isSelected}
                                                onChange={() => handleCheckboxChange('question_ids', question)}
                                            />
                                            <label
                                                htmlFor={`question-${question.question_id}`}
                                                className="checkbox-text"
                                            >
                                                {question.question}
                                            </label>
                                        </div>
                                    );
                                })
                            )}
                        </div>
                        <small className="selected-count">
                            {formData.question_ids.length} question(s) selected
                        </small>
                    </div>
                </div>

                <div className="form-group location-sites-section">
                    <label className="form-label location-sites-section__title">Locations &amp; Sites</label>
                    <p className="location-sites-section__hint">Choose one or more countries, then select sites for each.</p>

                    <div className="location-country-chips">
                        {countries.length === 0 ? (
                            <span className="location-empty-hint">No countries available</span>
                        ) : (
                            countries.map(c => {
                                const isSelected = selectedCountryIds.includes(c.country_id);
                                return (
                                    <button
                                        key={c.country_id}
                                        type="button"
                                        className={`location-country-chip ${isSelected ? 'location-country-chip--selected' : ''}`}
                                        onClick={() => handleCountryToggle(c.country_id, c.country_name)}
                                    >
                                        <span className="location-country-chip__label">{c.country_name}</span>
                                        {isSelected && <span className="location-country-chip__check">✓</span>}
                                    </button>
                                );
                            })
                        )}
                    </div>

                    <div className="location-sites-cards">
                        {selectedCountryIds.length === 0 ? (
                            <div className="location-sites-empty">
                                <span className="location-sites-empty__icon">📍</span>
                                <p>Select countries above to see and choose sites.</p>
                            </div>
                        ) : (
                            <div className={`location-sites-cards-inner location-sites-cards-inner--multi-${selectedCountryIds.length > 1}`}>
                                {selectedCountryIds.map(countryId => {
                                    const block = locationsByCountry[countryId];
                                    const locs = block?.locations ?? [];
                                    const name = block?.countryName ?? countries.find(c => c.country_id === countryId)?.country_name ?? `Country ${countryId}`;
                                    const isExpanded = expandedCountryIds.has(countryId);
                                    const selectedInCountry = (formData.location_ids || []).filter((lid) => {
                                        const n = parseInt(lid, 10);
                                        return locs.some((l) => getLocationRowId(l) === n);
                                    }).length;
                                    return (
                                        <div
                                            key={countryId}
                                            className={`location-sites-card ${!isExpanded ? 'location-sites-card--collapsed' : ''}`}
                                        >
                                            <button
                                                type="button"
                                                className="location-sites-card__header"
                                                onClick={() => setExpandedCountryIds(prev => {
                                                    const next = new Set(prev);
                                                    if (next.has(countryId)) next.delete(countryId);
                                                    else next.add(countryId);
                                                    return next;
                                                })}
                                                aria-expanded={isExpanded}
                                            >
                                                <span className="location-sites-card__title">{name}</span>
                                                <span className="location-sites-card__header-right">
                                                    <span className="location-sites-card__badge">
                                                        {selectedInCountry}/{locs.length} selected
                                                    </span>
                                                    <span className="location-sites-card__chevron" aria-hidden>
                                                        {isExpanded ? '▼' : '▶'}
                                                    </span>
                                                </span>
                                            </button>
                                            <div className="location-sites-card__list">
                                                {locs.length === 0 ? (
                                                    <div className="location-sites-card__empty">Loading… or no sites</div>
                                                ) : (
                                                    locs.map((site, idx) => {
                                                        const siteId = getLocationRowId(site);
                                                        const isSiteSelected = (formData.location_ids || []).some(
                                                            (lid) => Number(lid) === siteId
                                                        );
                                                        return (
                                                            <button
                                                                key={Number.isFinite(siteId) ? siteId : `site-row-${idx}`}
                                                                type="button"
                                                                className={`location-site-tile ${isSiteSelected ? 'location-site-tile--selected' : ''}`}
                                                                onClick={(e) => {
                                                                    e.stopPropagation();
                                                                    handleCheckboxChange('location_ids', 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>

                    <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>

                <div className="form-actions">
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={() => {
                            setSelectedCountryIds([]);
                            setExpandedCountryIds(new Set());
                            setLocationsByCountry({});
                            setFormData({
                                form_type_id: '',
                                title: '',
                                description: '',
                                question_ids: [],
                                location_ids: []
                            });
                        }}
                    >
                        Reset
                    </button>
                    <button
                        type="submit"
                        className="btn btn-primary"
                        disabled={loading}
                    >
                        {loading ? 'Creating...' : 'Create Form'}
                    </button>
                </div>
            </form>

            {/* New Question Modal – portaled to document.body so it centers on viewport */}
            {showNewQuestionModal && createPortal(
                <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>Add New Question</h2>
                        </div>
                        <div className="modal-body">
                            <div className="form-group">
                                <label className="form-label">Question text <span className="required" aria-hidden>*</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 className="required" aria-hidden>*</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 || type.type_name || type.name || `Type ${type.question_type_id}`}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            {questionTypeNeedsOptions(newQuestion.question_type_id) && (
                                <div className="form-group question-options-group">
                                    <label className="form-label">Options <span className="required" aria-hidden>*</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 to Form'}
                            </button>
                        </div>
                    </div>
                </div>,
                document.body
            )}
        </div>
        </>
    );
};

export default CreateForm;
