import React, { useContext, useEffect, useState } from 'react';
import './InspectionForm.css';
import axios from 'axios';
import { ConfigContext } from '../../Context/ConfigContext';
import { useNavigate, useParams } from 'react-router-dom';
import { ContentLoader } from '../../Components/Shimmer';

const ViewForm = () => {
    const { inspection_id } = useParams();
    const { apiHeaderJson, apiURL } = useContext(ConfigContext);
    const [questions, setQuestions] = useState([]);
    const [loadingList, setLoadingList] = useState(false);
    const [formHeader, setFormHeader] = useState({});
    const [selectedQuestion, setSelectedQuestion] = useState(null);
    const [editedQuestion, setEditedQuestion] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const navigate = useNavigate();

    const openEditModal = (question) => {
        setSelectedQuestion(question);
        setEditedQuestion(question.question);
        const modal = new window.bootstrap.Modal(document.getElementById('editModal'));
        modal.show();
    };

    const handleSave = async () => {
        if (!selectedQuestion) return;
        setIsSubmitting(true);
        try {
            await axios.post(
                `${apiURL}api/inspections/question/update`,
                {
                    inspection_question_id: selectedQuestion.question_id,
                    question: editedQuestion,
                    type: selectedQuestion.type,
                    required: selectedQuestion.required,
                },
                { headers: apiHeaderJson }
            );
            GetInfo();
            const modal = window.bootstrap.Modal.getInstance(document.getElementById('editModal'));
            modal.hide();
        } catch (err) {
            console.error(err);
        } finally {
            setIsSubmitting(false);
        }
    };

    const renderPreviewQuestion = (question) => {
        switch (question.type) {
            case 'short-answer':
                return <input type="text" className="form-control google-input" placeholder="Your answer" disabled />;
            case 'paragraph':
                return <textarea className="form-control google-input" placeholder="Your answer" rows={3} disabled />;
            case 'multiple-choice':
                return (
                    <div className="options-container">
                        {question.options.map(option => (
                            <div key={option.id} className="form-check mb-2">
                                <input className="form-check-input" type="radio" name={`question-${question.question_id}`} disabled />
                                <label className="form-check-label">{option.value || 'Option'}</label>
                            </div>
                        ))}
                    </div>
                );
            case 'checkbox':
                return (
                    <div className="options-container">
                        {question.options.map(option => (
                            <div key={option.id} className="form-check mb-2">
                                <input className="form-check-input" type="checkbox" disabled />
                                <label className="form-check-label">{option.value || 'Option'}</label>
                            </div>
                        ))}
                    </div>
                );
            default:
                return null;
        }
    };

    const GetInfo = async () => {
        try {
            setLoadingList(true);
            const headers = apiHeaderJson;
            const response = await axios.get(
                `${apiURL}api/inspections/GetInspectionsQuestions`,
                { params: { inspection_id }, headers }
            );
            const { data, success } = response.data;
            if (success === true) {
                setFormHeader(data?.inspection || {});
                const sortedQuestions = [...(data?.questions || [])].sort((a, b) => a.question_id - b.question_id);
                setQuestions(sortedQuestions);
            }
        } catch (error) {
            console.error(error);
        } finally {
            setLoadingList(false);
        }
    };

    useEffect(() => {
        if (inspection_id) GetInfo();
    }, [inspection_id]);

    return (
        <div className="main-content">
            <div className="page-content">
                {loadingList ? <ContentLoader /> : (
                    <div className="google-form-container">
                        <div className="form-preview">
                            <div className="preview-header">
                                <h1 className="preview-title">{formHeader?.inspection_title || 'Untitled Form'}</h1>
                                {formHeader?.inspection_description && <p className="preview-description">{formHeader.inspection_description}</p>}
                            </div>

                            <div className="preview-questions">
                                {questions.length > 0 ? questions.map((question) => (
                                    <div key={question.question_id} className="preview-question">
                                        <div className="preview-question-header mb-2 d-flex justify-content-between">
                                            <label>
                                                {question.question || 'Untitled Question'} {question.required && <span className="required-star">*</span>}
                                            </label>
                                            <button className="btn btn-sm btn-outline-primary" onClick={() => openEditModal(question)}>
                                                Edit
                                            </button>
                                        </div>
                                        {renderPreviewQuestion(question)}
                                    </div>
                                )) : <p>No questions found for this form.</p>}
                            </div>

                            <div className="form-actions mt-4">
                                <button className="btn btn-info float-end me-2" onClick={() => navigate(-1)}>
                                    Go Back <i className="ri-arrow-go-back-line ms-2" />
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* Modal */}
            <div id="editModal" className="modal fade" tabIndex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
                <div className="modal-dialog modal-lg">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h5 className="modal-title" id="editModalLabel">Edit Question</h5>
                            <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div className="modal-body">
                            <label className="form-label">Question</label>
                            <textarea
                                className="form-control mb-3"
                                value={editedQuestion}
                                onChange={(e) => setEditedQuestion(e.target.value)}
                            />
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-light" data-bs-dismiss="modal">Close</button>
                            <button type="button" className="btn btn-primary" onClick={handleSave} disabled={isSubmitting}>
                                {isSubmitting ? 'Saving...' : 'Save Changes'}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ViewForm;
