import React, { useContext, useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import Select from "react-select"
import {
    FaPlus,
    FaTrash,
    FaRegCircle,
    FaListUl,
    FaFont,
    FaAlignLeft,
    FaCalendarAlt
} from 'react-icons/fa';
import './InspectionForm.css';
import axios from 'axios';
import { ConfigContext } from '../../Context/ConfigContext';
import Swal from 'sweetalert2';
import { NavLink, useNavigate, useParams } from 'react-router-dom';
import PageTitle from '../../Components/PageTitle';


const questionTypes = [
    { id: 'short-answer', name: 'Short answer', icon: <FaFont /> },
    { id: 'paragraph', name: 'Paragraph', icon: <FaAlignLeft /> },
    { id: 'multiple-choice', name: 'Single choice', icon: <FaRegCircle /> },
    { id: 'checkbox', name: 'Checkboxes', icon: <FaListUl /> },
    { id: 'date', name: 'Date', icon: <FaCalendarAlt /> }, // ✅ NEW
];

const InspectionForm = () => {
    const { apiHeaderJson, apiURL } = useContext(ConfigContext);
    const [formTitle, setFormTitle] = useState('');
    const [formDescription, setFormDescription] = useState('');
    const [questions, setQuestions] = useState([]);
    const [previewMode, setPreviewMode] = useState(false);
    const [activeQuestion, setActiveQuestion] = useState(null);
    const [selectedSubmittal, setSelectedSubmittal] = useState(null);
    const [sidebarExpanded, setSidebarExpanded] = useState(false);
    const [loadingList, setLoadingList] = useState(false);
    const [category_rows, setCategoryRows] = useState([]);
    const [profile_category_id, setprofile_category_id] = useState();
    const [selectedOptions, setSelectedOptions] = useState(null);
    const [formHeader, setFormHeader] = useState({})
    const navigate = useNavigate();
    const { inspection_id } = useParams();
    const [hasFetched, setHasFetched] = useState(false);

    const addQuestion = (type) => {
        const newQuestion = {
            id: uuidv4(),
            type,
            question: '',
            required: false,
            inspection_question_consultant_only: false,
            options:
                type === 'multiple-choice' || type === 'checkbox'
                    ? [{ id: uuidv4(), value: 'Option 1' }]
                    : [] // ✅ date will naturally fall here
        };
        setQuestions([...questions, newQuestion]);
        setActiveQuestion(newQuestion.id);
    };

    const submittalOptions = [
        { value: "Sub-contractor pre-qualification", label: "Sub-contractor pre-qualification" },
        { value: "Material & product data", label: "Material & product data" },
        { value: "Method statement", label: "Method statement" },
        { value: "Design calculation", label: "Design calculation" },
        { value: "Request for information", label: "Request for information" },
        { value: "Testing and commissioning", label: "Testing and commissioning" },
        { value: "Inspection request", label: "Inspection request" },
    ];


    const toggleQuestionVisibility = (id) => {
        setQuestions(questions.map(q =>
            q.id === id ? { ...q, enabled: !q.enabled } : q
        ));
    };


    const removeQuestion = (id) => {
        setQuestions(questions.filter(q => q.id !== id));
    };

    const updateQuestion = (id, field, value) => {
        setQuestions(questions.map(q =>
            q.id === id ? { ...q, [field]: value } : q
        ));
    };

    const addOption = (questionId) => {
        setQuestions(questions.map(q =>
            q.id === questionId
                ? { ...q, options: [...q.options, { id: uuidv4(), value: '' }] }
                : q
        ));
    };

    // const GetInfo = async () => {
    //     try {
    //         setLoadingList(true)
    //         const headers = apiHeaderJson
    //         const response = await axios.get(`${apiURL}api/inspections/GetInspectionsQuestions`, { params: { inspection_id } })
    //         const { data, success } = response.data;
    //         if (success === true) {
    //             setFormHeader(data?.inspection)
    //             setQuestions(data?.questions)
    //             setLoadingList(false)
    //         }

    //     } catch (error) {
    //         console.log(error);

    //     }
    //     finally {
    //         setLoadingList(false)
    //     }
    // }





    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) {
                const normalizedAndSortedQuestions = (data?.questions || []).map(q => ({
                    ...q,
                    id: q.id || uuidv4(),
                    options: (q.options || []).map(o => ({
                        ...o,
                        id: o.id || uuidv4(),
                    })),
                }))
                    .sort((a, b) => a.question_id - b.question_id);

                setFormHeader(data?.inspection);
                setQuestions(normalizedAndSortedQuestions);
                setSelectedSubmittal(data?.inspection?.type_of_submittal)
            }
        } catch (error) {
            console.log(error);
        } finally {
            setLoadingList(false);
        }
    };


    const removeOption = (questionId, optionId) => {
        setQuestions(questions.map(q =>
            q.id === questionId
                ? { ...q, options: q.options.filter(o => o.id !== optionId) }
                : q
        ));
    };

    const updateOption = (questionId, optionId, value) => {
        setQuestions(questions.map(q =>
            q.id === questionId
                ? {
                    ...q,
                    options: q.options.map(o =>
                        o.id === optionId ? { ...o, value } : o
                    )
                }
                : q
        ));
    };

    const renderQuestionInput = (question) => {
        switch (question.type) {
            case 'short-answer':
                return (
                    <input
                        type="text"
                        className="form-control google-input"
                        placeholder="Short answer text"
                        disabled
                    />
                );
            case 'paragraph':
                return (
                    <textarea
                        className="form-control google-input"
                        placeholder="Long answer text"
                        rows={3}
                        disabled
                    />
                );
            case 'multiple-choice':
            case 'checkbox':
                return (
                    <div className="options-container">
                        {question.options.map((option, idx) => (
                            <div key={option.id} className="option-item d-flex align-items-center mb-2">
                                {question.type === 'multiple-choice' ? (
                                    <div className="radio-container me-2"></div>
                                ) : (
                                    <div className="checkbox-container me-2"></div>
                                )}
                                <input
                                    type="text"
                                    className="form-control google-option-input"
                                    value={option.value}
                                    onChange={(e) => updateOption(question.id, option.id, e.target.value)}
                                    placeholder={`Option ${idx + 1}`}
                                />
                                {question.options.length > 1 && (
                                    <button
                                        className="btn btn-link text-danger ms-2"
                                        onClick={() => removeOption(question.id, option.id)}
                                    >
                                        <FaTrash />
                                    </button>
                                )}
                            </div>
                        ))}
                        <div className="d-flex align-items-center mt-2">
                            {question.type === 'multiple-choice' ? (
                                <div className="radio-container me-2"></div>
                            ) : (
                                <div className="checkbox-container me-2"></div>
                            )}
                            <button
                                className="btn btn-link text-primary add-option-btn"
                                onClick={() => addOption(question.id)}
                            >
                                Add option
                            </button>
                        </div>
                    </div>
                );
            case 'date':
                return (
                    <input
                        type="date"
                        className="form-control google-input"
                        disabled
                    />
                );
            default:
                return null;
        }
    };

    const renderPreviewQuestion = (question) => {
        switch (question.type) {
            case 'short-answer':
                return (
                    <input
                        type="text"
                        className="form-control google-input"
                        placeholder="Your answer"
                    />
                );
            case 'paragraph':
                return (
                    <textarea
                        className="form-control google-input"
                        placeholder="Your answer"
                        rows={3}
                    />
                );
            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.id}`}
                                    id={`option-${option.id}`}
                                />
                                <label className="form-check-label" htmlFor={`option-${option.id}`}>
                                    {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"
                                    name={`question-${question.id}`}
                                    id={`option-${option.id}`}
                                />
                                <label className="form-check-label" htmlFor={`option-${option.id}`}>
                                    {option.value || "Option"}
                                </label>
                            </div>
                        ))}
                    </div>
                );
            case 'date':
                return (
                    <input
                        type="date"
                        className="form-control google-input"
                    />
                );
            default:
                return null;
        }
    };

    const validateForm = () => {

        // Check if there are no questions
        if (questions.length === 0) {
            Swal.fire({
                icon: "error",
                title: "Please add at least one question",
                showConfirmButton: true,
            });
            return false;
        }

        // Validate each question
        for (const question of questions) {
            // Check if question text is empty
            if (!question.question.trim()) {
                Swal.fire({
                    icon: "error",
                    title: `Question ${questions.indexOf(question) + 1} is empty`,
                    text: "Please provide a question text",
                    showConfirmButton: true,
                });
                return false;
            }

            // Check if multiple-choice or checkbox questions have at least one option
            if ((question.type === 'multiple-choice' || question.type === 'checkbox') &&
                question.options.length === 0) {
                Swal.fire({
                    icon: "error",
                    title: `Question "${question.question}" has no options`,
                    text: "Please add at least one option for multiple-choice or checkbox questions",
                    showConfirmButton: true,
                });
                return false;
            }

            // Check if options have text
            if (question.options) {
                for (const option of question.options) {
                    if (!option.value.trim()) {
                        Swal.fire({
                            icon: "error",
                            title: `Empty option in question "${question.question}"`,
                            text: "Please provide text for all options",
                            showConfirmButton: true,
                        });
                        return false;
                    }
                }
            }
        }

        return true;
    };

    const handleSelect = (selectedOption, selected) => {
        setprofile_category_id(selectedOption ? selectedOption.value : null);
        setSelectedOptions(selected.value);
        setSelectedOptions(selected || []);
    };

    const GetConsultantCategories = async () => {
        const headers = apiHeaderJson;
        try {
            const response = await axios.get(`${apiURL}api/profile-categories`, {
                params: { pc_profile_type: 2 },
                headers,
            })
            const { data, success } = response.data;
            if (success) {
                setCategoryRows(
                    data.map((row) => ({
                        value: row.profile_category_id,
                        label: row.pc_category_title,
                    }))
                );
            }
        } catch (error) {
            console.log(error);
        }
    };

    // const handleSubmit = async () => {
    //     if (!validateForm()) {
    //         return;
    //     }
    //     const headers = apiHeaderJson;
    //     const payload = {
    //         title: formTitle,
    //         description: formDescription,
    //         consultant_category_id: profile_category_id,
    //         questions: questions.map(q => ({
    //             type: q.type,
    //             question: q.question,
    //             required: q.required,
    //             inspection_question_consultant_only: q.inspection_question_consultant_only,
    //             options: q.options || []
    //         }))
    //     };

    //     try {
    //         const response = await axios.post(`${apiURL}api/inspections/Create`, payload, { headers });

    //         const { message, success } = response.data;

    //         if (success === true) {
    //             await Swal.fire({
    //                 icon: "success",
    //                 title: message,
    //                 showConfirmButton: false,
    //                 timer: 1500,
    //             });
    //             navigate("/InspectionFormList");
    //         } else {
    //             await Swal.fire({
    //                 icon: "error",
    //                 title: message,
    //                 showConfirmButton: false,
    //                 timer: 1500,
    //             });
    //         }
    //     } catch (error) {
    //         console.error('Error submitting form:', error);
    //         await Swal.fire({
    //             icon: "error",
    //             title: "An error occurred while submitting the form.",
    //             text: error.message,
    //             showConfirmButton: true,
    //         });
    //     }
    // };

    // useEffect(() => {
    //     GetConsultantCategories()
    //     if (inspection_id != null) GetInfo();
    // }, [inspection_id])

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

    //     const headers = apiHeaderJson;

    //     try {
    //         if (!inspection_id) {
    //             // 🔷 CREATE new form
    //             const payload = {
    //                 title: formTitle,
    //                 description: formDescription,
    //                 consultant_category_id: profile_category_id,
    //                 questions: questions.map(q => ({
    //                     type: q.type,
    //                     question: q.question,
    //                     required: q.required,
    //                     inspection_question_consultant_only: q.inspection_question_consultant_only,
    //                     options: q.options || []
    //                 }))
    //             };

    //             const response = await axios.post(`${apiURL}api/inspections/Create`, payload, { headers });
    //             const { message, success } = response.data;

    //             if (success) {
    //                 await Swal.fire({
    //                     icon: "success",
    //                     title: message,
    //                     showConfirmButton: false,
    //                     timer: 1500,
    //                 });
    //                 navigate("/InspectionFormList");
    //             } else {
    //                 await Swal.fire({
    //                     icon: "error",
    //                     title: message || "Failed to create form",
    //                     text: response.data?.errors?.title?.join(", ") || "",
    //                     showConfirmButton: true,
    //                 });
    //             }
    //         } else {
    //             // 🔷 UPDATE existing form
    //             // Optionally update formHeader here if API exists
    //             // Otherwise just update each question
    //             await Promise.all(
    //                 questions.map(q => {
    //                     const params = new URLSearchParams({
    //                         inspection_question_id: q.id,
    //                         question: q.question,
    //                         type: q.type,
    //                         required: q.required,
    //                     });
    //                     return axios.post(
    //                         `${apiURL}api/inspections/question/update?${params.toString()}`,
    //                         null,
    //                         { headers }
    //                     );
    //                 })
    //             );

    //             await Swal.fire({
    //                 icon: "success",
    //                 title: "Form updated successfully!",
    //                 showConfirmButton: false,
    //                 timer: 1500,
    //             });
    //             navigate("/InspectionFormList");
    //         }
    //     } catch (error) {
    //         console.error('Error submitting form:', error);
    //         await Swal.fire({
    //             icon: "error",
    //             title: "An error occurred while submitting the form.",
    //             text: error.response?.data?.message || error.message,
    //             showConfirmButton: true,
    //         });
    //     }
    // };



    const handleSubmit = async () => {
        if (!validateForm()) {
            return;
        }
        const headers = apiHeaderJson;
        const payload = {
            title: formTitle,
            description: formDescription,
            consultant_category_id: profile_category_id,
            type_of_submittal: selectedSubmittal,
            questions: questions.map(q => ({
                type: q.type,
                question: q.question,
                required: q.required,
                inspection_question_consultant_only: q.inspection_question_consultant_only,
                options: q.options || []
            }))
        };

        try {
            const response = await axios.post(`${apiURL}api/inspections/Create`, payload, { headers });

            const { message, success } = response.data;

            if (success === true) {
                await Swal.fire({
                    icon: "success",
                    title: message,
                    showConfirmButton: false,
                    timer: 1500,
                });
                navigate("/InspectionFormList");
            } else {
                await Swal.fire({
                    icon: "error",
                    title: message,
                    showConfirmButton: false,
                    timer: 1500,
                });
            }
        } catch (error) {
            console.error('Error submitting form:', error);
            await Swal.fire({
                icon: "error",
                title: "An error occurred while submitting the form.",
                text: error.message,
                showConfirmButton: true,
            });
        }
    };

    const handleUpdate = async () => {
        if (!validateForm()) {
            return;
        }
        const newQuestions = questions.map(question => ({
            ...question,
            inspection_question_id: question.question_id
        }));

        const payload = {
            title: formHeader?.inspection_title,
            description: formHeader?.inspection_description,
            consultant_category_id: formHeader?.consultant_category_id,
            type_of_submittal: selectedSubmittal,
            inspection_id: inspection_id,
            questions: newQuestions.map(q => ({
                inspection_question_id: q.inspection_question_id === undefined ? null : q.inspection_question_id,
                type: q.type,
                question: q.question,
                required: q.required,
                inspection_question_consultant_only: q.inspection_question_consultant_only,
                options: q.options?.map(option => ({
                    ...option,
                    inspection_option_id: (option.id === undefined || isNaN(option.id))
                        ? null
                        : Number(option.id)
                })) || []
            }))
        };
        const headers = apiHeaderJson;

        try {
            const response = await axios.post(`${apiURL}api/inspections/update`, payload, { headers });

            const { message, success } = response.data;

            if (success === true) {
                await Swal.fire({
                    icon: "success",
                    title: message,
                    showConfirmButton: false,
                    timer: 1500,
                });
                navigate("/InspectionFormList");
            } else {
                await Swal.fire({
                    icon: "error",
                    title: message,
                    showConfirmButton: false,
                    timer: 1500,
                });
            }
        } catch (error) {
            console.error('Error submitting form:', error);
            await Swal.fire({
                icon: "error",
                title: "An error occurred while submitting the form.",
                text: error.message,
                showConfirmButton: true,
            });
        }
    };


    useEffect(() => {
        window.scrollTo(0, 0);
        GetConsultantCategories();
        if (inspection_id != null && !hasFetched) {
            GetInfo();
            setHasFetched(true);
        }
    }, [inspection_id, hasFetched]);

    return (
        <div className="main-content">
            <div className="page-content">
                <div className="container-fluid">
                    <br />
                    <PageTitle title={`Inspection Form `} primary={`Home`} />
                    <div className="row">

                        <div className="col-md-12">
                            <div className='card'>
                                <div
                                    className='card-header align-items-center d-flex'
                                    style={{
                                        background: "#000000",
                                    }}>
                                    <h4 className='card-title mb-0 flex-grow-1 text-white'>Inspection Form </h4>

                                    <div className='avatar-xs  flex-shrink-0'>
                                        <NavLink
                                            to={'/InspectionFormList'}
                                            className='avatar-title bg-white rounded-circle fs-4'
                                            style={{
                                                color: "#184c8f",
                                            }}>
                                            <i className='las la-list'></i>
                                        </NavLink>
                                    </div>
                                </div>


                                <div className="google-form-container">
                                    {!previewMode ? (
                                        <div className='form-builder-wrapper'>
                                            <div className="form-builder">
                                                <div className="form-header">
                                                    {inspection_id ? (
                                                        <div className="form-title-container">
                                                            <input
                                                                type="text"
                                                                className="form-title-input"
                                                                value={formHeader?.inspection_title || ''}
                                                                onChange={(e) =>
                                                                    setFormHeader({ ...formHeader, inspection_title: e.target.value })
                                                                }
                                                                placeholder="Form title"
                                                            />
                                                            <input
                                                                type="text"
                                                                className="form-description-input"
                                                                value={formHeader?.inspection_description || ''}
                                                                onChange={(e) =>
                                                                    setFormHeader({ ...formHeader, inspection_description: e.target.value })
                                                                }
                                                                placeholder="Form description"
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="form-title-container">
                                                            <input
                                                                type="text"
                                                                className="form-title-input"
                                                                value={formTitle}
                                                                onChange={(e) => setFormTitle(e.target.value)}
                                                                placeholder="Form title"
                                                            />
                                                            <input
                                                                type="text"
                                                                className="form-description-input"
                                                                value={formDescription}
                                                                onChange={(e) => setFormDescription(e.target.value)}
                                                                placeholder="Form description"
                                                            />
                                                        </div>
                                                    )}


                                                </div>

                                                <div className="questions-list">
                                                    {questions.map((question) => (
                                                        <div
                                                            key={question.id}
                                                            className={`question-card ${activeQuestion === question.id ? 'active' : ''}`}
                                                            onClick={() => setActiveQuestion(question.id)}
                                                        >
                                                            <div className="question-content">
                                                                <div className="question-header d-flex align-items-center gap-2">
                                                                    {/* <div className="form-check me-2">
                                                                        <input
                                                                            type="checkbox"
                                                                            className="form-check-input"
                                                                            id={`enable-question-${question.id}`}
                                                                            checked={question.enabled}
                                                                            onChange={(e) => {
                                                                                e.stopPropagation();
                                                                                toggleQuestionVisibility(question.id);
                                                                            }}
                                                                        />
                                                                    </div> */}


                                                                    <input
                                                                        type="text"
                                                                        className="question-input"
                                                                        value={question.question}
                                                                        onChange={(e) => updateQuestion(question.id, 'question', e.target.value)}
                                                                        placeholder="Question"
                                                                    />

                                                                    <select
                                                                        className="question-type-select"
                                                                        value={question.type}
                                                                        onChange={(e) => updateQuestion(question.id, 'type', e.target.value)}
                                                                    >
                                                                        {questionTypes.map(type => (
                                                                            <option key={type.id} value={type.id}>
                                                                                {type.name}
                                                                            </option>
                                                                        ))}
                                                                    </select>
                                                                </div>

                                                                {renderQuestionInput(question)}
                                                            </div>

                                                            <div className="question-footer d-flex gap-3 align-items-center">
                                                                <div className="form-check">
                                                                    <input
                                                                        type="checkbox"
                                                                        className="form-check-input"
                                                                        id={`required-${question.id}`}
                                                                        checked={question.required}
                                                                        onChange={(e) => updateQuestion(question.id, 'required', e.target.checked)}
                                                                    />
                                                                    <label className="form-check-label" htmlFor={`required-${question.id}`}>
                                                                        Required
                                                                    </label>
                                                                </div>

                                                                {/* <div className="form-check">
                                                                    <input
                                                                        type="checkbox"
                                                                        className="form-check-input"
                                                                        id={`enable-question-${question.id}`}
                                                                        checked={question.enabled}
                                                                        onChange={(e) => {
                                                                            e.stopPropagation();
                                                                            toggleQuestionVisibility(question.id);
                                                                        }}
                                                                    />
                                                                    <label className="form-check-label" htmlFor={`enable-question-${question.id}`}>
                                                                        Consultant Only
                                                                    </label>
                                                                </div> */}

                                                                <div className="form-check">
                                                                    <input
                                                                        type="checkbox"
                                                                        className="form-check-input"
                                                                        id={`consultant-only-${question.id}`}
                                                                        checked={question.inspection_question_consultant_only}
                                                                        onChange={(e) => updateQuestion(question.id, 'inspection_question_consultant_only', e.target.checked)}
                                                                    />
                                                                    <label className="form-check-label" htmlFor={`consultant-only-${question.id}`}>
                                                                        Consultant Only
                                                                    </label>
                                                                </div>

                                                                <button
                                                                    className="btn btn-link text-danger delete-btn ms-auto"
                                                                    onClick={(e) => {
                                                                        e.stopPropagation();
                                                                        removeQuestion(question.id);
                                                                    }}
                                                                >
                                                                    <FaTrash />
                                                                </button>
                                                            </div>

                                                        </div>
                                                    ))}
                                                </div>


                                                <div className="add-question-section">
                                                    <div className="question-types">
                                                        {questionTypes.map(type => (
                                                            <button
                                                                key={type.id}
                                                                className="add-question-btn"
                                                                onClick={() => addQuestion(type.id)}
                                                            >
                                                                {type.icon}
                                                                <span>{type.name}</span>
                                                            </button>
                                                        ))}
                                                    </div>
                                                </div>



                                                {/* Form Actions */}
                                                <div className="form-actions d-flex flex-wrap align-items-center justify-content-between gap-2">

                                                    {/* React Select Dropdown */}
                                                    <div style={{ minWidth: '250px' }}>
                                                        <Select
                                                            options={submittalOptions}
                                                            value={submittalOptions.find(option => option.value === selectedSubmittal)}
                                                            onChange={(selected) => setSelectedSubmittal(selected.value)}
                                                            placeholder="Select Type of Submittal"
                                                        />
                                                    </div>

                                                    {/* Buttons Group */}
                                                    <div className="d-flex gap-2 flex-wrap ms-auto">
                                                        {
                                                            inspection_id &&
                                                            <button
                                                                className="btn btn-warning btn-label waves-effect right waves-light float-right"
                                                                onClick={() => navigate(-1)}
                                                            >
                                                                Go Back <i className='ri-arrow-go-back-line ms-2 label-icon align-middle fs-16 ' />
                                                            </button>
                                                        }

                                                        <button
                                                            className="btn btn-info btn-label waves-effect right waves-light float-right"
                                                            onClick={() => setPreviewMode(true)}
                                                        >
                                                            Preview <i className='ri-eye-line label-icon align-middle fs-16 ' />
                                                        </button>

                                                        <button
                                                            className="btn btn-dark btn-label waves-effect right waves-light float-right"
                                                            type='button'
                                                            onClick={() => inspection_id ? handleUpdate() : handleSubmit()}
                                                            disabled={Object.keys(formHeader).length === 0 && (!formTitle || questions.length === 0)}
                                                        >
                                                            {inspection_id ? "Update" : "Save"} <i className='ri-save-line label-icon align-middle fs-16 ' />
                                                        </button>
                                                    </div>
                                                </div>

                                            </div>

                                            <div className="question-types-sidebar right-sidebar">
                                                <div className="sidebar-header">
                                                    <div
                                                        className="question-type-icon expand-toggle"
                                                        onClick={() => setSidebarExpanded(!sidebarExpanded)}
                                                    >
                                                        <i className="ri-add-circle-line"></i>
                                                        <span className="tooltip-text">{sidebarExpanded ? 'Collapse' : 'Add Questions'}</span>
                                                    </div>
                                                </div>
                                                {sidebarExpanded && (
                                                    <div className="question-types-list">
                                                        {questionTypes.map(type => (
                                                            <div
                                                                key={type.id}
                                                                className="question-type-icon"
                                                                onClick={() => addQuestion(type.id)}
                                                            >
                                                                {type.icon}
                                                                <span className="tooltip-text">{type.name}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="form-preview">
                                            {/* Preview Header */}
                                            {
                                                inspection_id ? <div className="preview-header">
                                                    <h1 className="preview-title">{formHeader.inspection_title || 'Untitled form'}</h1>
                                                    <p className="preview-description">{formHeader.inspection_description}</p>

                                                </div>
                                                    : <div className="preview-header">
                                                        <h1 className="preview-title">{formTitle || 'Untitled form'}</h1>
                                                        {formDescription && <p className="preview-description">{formDescription}</p>}

                                                    </div>
                                            }





                                            {/* Preview Questions */}
                                            <div className="preview-questions">
                                                {questions.map((question, index) => (
                                                    <div key={question.id} className="preview-question">
                                                        <div className="preview-question-header">
                                                            <label>
                                                                {question.question || "Question"} {question.required && <span className="required-star">*</span>}
                                                            </label>
                                                        </div>
                                                        {renderPreviewQuestion(question)}
                                                    </div>
                                                ))}

                                                {questions.length === 0 && (
                                                    <div className="empty-form-message">
                                                        This form has no questions yet
                                                    </div>
                                                )}
                                                <div className='d-flex justify-content-end'>
                                                    <button
                                                        className=" btn btn-info btn-label waves-effect right waves-light float-right "
                                                        onClick={() => setPreviewMode(false)}
                                                    >
                                                        <i className=' ri-arrow-go-back-line label-icon align-middle fs-16 ' /> Back to Editor
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div >
    );
};

export default InspectionForm;

