// ViewInspection.jsx

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

const ViewInspection = () => {
    const { project_inspection_id } = useParams();
    const { apiHeaderJson, apiURL } = useContext(ConfigContext);
    const [questions, setQuestions] = useState([]);
    const [loadingList, setLoadingList] = useState(true);
    const [formHeader, setFormHeader] = useState({});
    const [responses, setResponses] = useState({});
    const [projectInfo, setProjectInfo] = useState({});

    const navigate = useNavigate();

    const renderPreviewAnswer = (question) => {
        if (!question.answers || question.answers.length === 0) {
            return <div className="text-muted">No answer provided</div>;
        }

        const answers = question.answers.map((answer, index) => (
            <div key={index} className="vi-answer-item">
                {answer.value || "No answer provided"}
            </div>
        ));

        if (question.type === 'checkbox') {
            const uniqueAnswers = Array.from(new Set(question.answers.map(a => a.inspection_option_id)))
                .map(id => question.answers.find(a => a.inspection_option_id === id));

            return (
                <div className="vi-answer">
                    <div className="vi-answer-item">
                        <ul className="d-flex flex-row m-0  p-3 pt-0">
                            {uniqueAnswers.map((answer, index) => (
                                <li key={index} className={index !== 0 ? 'ms-4' : ''}>
                                    {answer.value || "No option selected"}
                                </li>
                            ))}
                        </ul>
                    </div>
                </div>


            );
        }

        return <div className="vi-answer">{answers}</div>;
    };

    const GetInfo = async () => {
        try {
            setLoadingList(true);
            const response = await axios.get(`${apiURL}api/inspections/GetSubmittedInspectionsQuestions`, {
                params: { project_inspection_id },
                headers: apiHeaderJson
            });

            const { data, success } = response.data;
            if (success === true) {
                setFormHeader(data?.inspection);
                setQuestions(data?.questions);
                setProjectInfo(data?.inspection);
                const initialResponses = {};
                data?.questions.forEach(question => {
                    if (question.answers && question.answers.length > 0) {
                        if (question.type === 'checkbox') {
                            initialResponses[question.question_id] = Array.from(
                                new Set(question.answers.map(a => a.inspection_option_id))
                            );
                        } else if (question.type === 'multiple-choice') {
                            initialResponses[question.question_id] = question.answers[0].inspection_option_id;
                        } else {
                            initialResponses[question.question_id] = question.answers[0].value;
                        }
                    }
                });
                setResponses(initialResponses);
            }
        } catch (error) {
            console.log(error);
            Swal.fire({
                icon: "error",
                title: "Failed to load inspection data",
                text: error.message,
                showConfirmButton: true,
            });
        } finally {
            setLoadingList(false);
        }
    };

    useEffect(() => {
        project_inspection_id && GetInfo();
    }, [project_inspection_id]);

    return loadingList ? <ContentLoader /> : (
        <div className='d-flex justify-content-center  bg-white'>

            <div className="vi-container p-2 shadow-none border">
                <div className="vi-preview shadow-none printable-area">


                    <div className="vi-participant-section">
                        <div className="vi-logo">
                            <img
                                src="/assets/images/new_logo.png"
                                alt="Company Logo"
                                onError={(e) => { e.target.style.display = 'none'; }}
                            />
                        </div>
                        {/* <div className='line' style={{
                            width: "1px",
                            backgroundColor: "lightgray",
                            height: "125px",
                            margin: "0 40px"
                        }} /> */}
                        <div className='vi-participant'>
                            <p style={{ marginBlock: "0px" }}>{projectInfo?.project_title}</p>
                            <h6 style={{ color: "lightgray" }}>Project</h6>
                            <div className="row">
                                <div className="col-12">
                                    <div className="row mb-1" >
                                        <div className="col-6"><p style={{ marginBlock: "0px" }}>{DateFormaterMonth(projectInfo?.project_start_date)}</p></div>
                                        <div className="col-6"><p style={{ marginBlock: "0px" }}>{DateFormaterMonth(projectInfo?.project_end_date)}</p></div>
                                        <div className="col-6" style={{ color: "lightgray" }}>Start Date</div>
                                        <div className="col-6" style={{ color: "lightgray" }}>End Date</div>
                                    </div>
                                    <div className="row mb-1" >
                                        <div className="col-12"><p style={{ marginBlock: "0px" }}>{projectInfo?.project_address}</p></div>
                                        <div className="col-12" style={{ color: "lightgray" }}>Location </div>

                                    </div>

                                </div>
                            </div>

                        </div>
                        <div className="vi-participant " style={{ marginLeft: '100px' }}>
                            <p style={{ marginBlock: "0px" }}>{projectInfo?.contractor_name}</p>
                            <h6 style={{ color: "lightgray" }}>Contractor</h6>
                            <p style={{ marginBlock: "0px" }}>{projectInfo?.consultant_name}</p>
                            <h6 style={{ color: "lightgray" }}>Consultant</h6>
                            <p style={{ marginBlock: "0px" }}>{projectInfo?.project_inspection_id}</p>
                            <h6 style={{ color: "lightgray" }}>Project Inspection Id</h6>
                        </div>
                    </div>

                    <div className="vi-header">

                        <div className="vi-header-info">
                            <div className='d-flex justify-content-end align-items-center gap-2 mx-3'>
                                <span style={{ color: "lightgray" }}>Inspection Date:</span>
                                {DateFormaterMonth(projectInfo?.inspection_date)}
                            </div>
                            <h4 className="vi-title text-center">{formHeader?.inspection_title || 'Untitled form'}</h4>
                            <div className="vi-meta ">

                            </div>
                        </div>
                    </div>

                    {/* {formHeader?.inspection_description && (
                        <div className="vi-description">
                            <p>{formHeader.inspection_description}</p>
                        </div>
                    )} */}

                    <div className="vi-questions">
                        {questions.map((question, index) => (
                            <div key={question.question_id} className="vi-question" >
                                <div className="vi-question-header">
                                    <label style={{ marginBottom: "0px", fontWeight: "500" }}>
                                        {index + 1}. {question.question || "Question"}
                                        {question.required && <span className="required-star">*</span>}
                                    </label>
                                </div>
                                {renderPreviewAnswer(question)}
                            </div>
                        ))}
                    </div>

                    {/* <div className="vi-signatures">
                        {["Contractor Representative", "Consultant Representative", "Inspector"].map((role, i) => (
                            <div key={i} className="vi-signature-box">
                                <div className="vi-signature-line"></div>
                                <p>{role} Signature</p>
                            </div>
                        ))}
                    </div> */}

                    <div className="vi-actions no-print mt-4">
                        <button
                            className="btn btn-success float-end"
                            onClick={() => window.print()}
                        >
                            Print <i className="ri-printer-line ms-2" />
                        </button>
                        <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>
    );
};

export default ViewInspection;
