import { useState } from 'react';

function ConsentView({ error, loading, handleNewParticipant, handleResumeParticipant }) {
    const [resumeId, setResumeId] = useState('');
    return (
        <div className="container mt-5 mb-5">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <div className="card-header">
                            <h3 className="card-title">Sub-Concept User Study</h3>
                        </div>
                        <div className="card-body">
                            <div className="mb-4" style={{ minHeight: '300px', border: '1px solid #dee2e6', padding: '20px', backgroundColor: '#f8f9fa' }}>
                                <p>Before you decide to take part in this study it is important for you to understand why the research is being done and what it will involve. Please take time to read the following information carefully and discuss it with others if you wish. A member of the team can be contacted if there is anything that is not clear or if you would like more information. Take time to decide whether or not you wish to take part.</p>

                                <p><strong>Purpose of the study</strong></p>
                                <p>The purpose of this study is to evaluate a method for making machine learning models easier for humans to understand. The study investigates whether relationships between concepts discovered by the method match the relationships that people naturally understand, and whether the method can accurately label images.</p>

                                <p><strong>Do I have to take part?</strong></p>
                                <p>No. Taking part in this study is entirely voluntary, and if you choose not to take part, or decide to withdraw at any time, there will be no penalty or loss to you now or in the future. You can withdraw simply by closing your browser tab. Any responses you have already completed will still be saved, but you do not need to continue further.</p>

                                <p><strong>What do I have to do?</strong></p>
                                <p>If you decide to take part, you will complete the study entirely online. You will be shown up to 100 questions in total, but you do not need to complete all of them. Each question takes a few seconds to answer. You will be asked questions about the content of images, and the relationships between words. You may stop whenever you like, and any progress made up to that point will be saved automatically. If you decide to take part, you will be given more detailed instructions on the next screen.</p>

                                <p><strong>Will my taking part in this project be kept confidential?</strong></p>
                                <p>Yes. Your responses will be stored under a participant ID and will not be linked to your personal identity. For more general information about how X uses personal data, please see: <a href="X" target="_blank">X</a>.</p>

                                <p><strong>What will happen to the results of the research project?</strong></p>
                                <p>The results of this study will be analysed and may be presented at academic conferences or published in journals. Results will be reported in terms of groups of participants, and no individual will be identifiable in any report or publication. The data collected may also be used in future related research projects.</p>

                                <p><strong>Ethical review of the study</strong></p>
                                <p>The project has been approved by X.</p>

                                <p><strong>Contact for further information</strong></p>
                                <p>If you have any questions about the study or your participation, please contact: X (<a href="mailto:X">X</a>).</p>

                                <p><strong>We will stop collecting responses at 14:00 BST on Wednesday 24th September 2025.</strong></p>
                            </div>

                            {error && (
                                <div className="alert alert-danger" role="alert">
                                    {error}
                                </div>
                            )}

                            <div className="row align-items-stretch">
                                <div className="col-md-6 d-flex flex-column mt-3">
                                    <h5>New Participant</h5>
                                    <p>If you consent to participate in this study, click below to begin. If you do not want to participate, you can close this tab.</p>
                                    <button
                                        className="btn btn-success w-100 mt-auto"
                                        onClick={handleNewParticipant}
                                        disabled={loading}
                                    >
                                        {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'I Consent - Start Study'}
                                    </button>
                                </div>

                                <div className="col-md-6 d-flex flex-column mt-3">
                                    <h5>Returning Participant</h5>
                                    <p>If you <strong>already have a participant ID</strong> and wish to resume:</p>
                                    <div className="form-group mb-3">
                                        <input
                                            type="text"
                                            className="form-control"
                                            placeholder="Enter your participant ID"
                                            value={resumeId}
                                            onChange={(e) => setResumeId(e.target.value)}
                                            disabled={loading}
                                        />
                                    </div>
                                    <button
                                        className="btn btn-primary w-100 mt-auto"
                                        onClick={() => handleResumeParticipant(resumeId)}
                                        disabled={loading || !resumeId.trim()}
                                    >
                                        {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'Resume Study'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>);
}

function InstructionsView({ error, loading, onStart, participantId }) {
    return (
        <div className="container mt-5 mb-5">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <div className="card-header">
                            <h3 className="card-title">Instructions</h3>
                        </div>
                        <div className="card-body">
                            <div className="mb-4" style={{ minHeight: '300px', border: '1px solid #dee2e6', padding: '20px', backgroundColor: '#f8f9fa' }}>
                                <p>Thank you for agreeing to take part in our study.</p>

                                <p><strong>Your participant ID is: {participantId}</strong></p>
                                <p>Make a note of your participant ID. If you close this tab or encounter any problems, you will need it to resume the study. You can resume the study by opening the link again, and entering your participant ID.</p>

                                <p>You will be shown up to 100 questions in total. It should take you 10-15 minutes to answer all 100 questions. If you can, please answer all the questions. However, you can stop at any time by closing this tab, and any answers you have already entered will have been submitted.</p>

                                <p>You will be shown two types of questions, examples of which are shown below. In the first type, you will be asked about the relationship between two words, and in the second type you will be asked whether an image shows something. Some of the words in the questions are generated automatically, so if a question does not make sense or is ambiguous, please answer it as best you can or choose "Not sure".</p>

                                <p><strong>Example of the first question type:</strong></p>
                                <img
                                    src="eg1.png"
                                    alt="Example question"
                                    className="img-fluid mb-3"
                                    style={{ maxWidth: '100%' }}
                                />

                                <p><strong>Example of the second question type:</strong></p>
                                <img
                                    src="eg2.png"
                                    alt="Example question"
                                    className="img-fluid mb-3"
                                    style={{ maxWidth: '100%' }}
                                />

                                <p><strong>Contact for further information</strong></p>
                                <p>If you have any questions about the study or your participation, or you run into any issues, please contact: X (<a href="mailto:X">X</a>).</p>
                            </div>

                            {error && (
                                <div className="alert alert-danger" role="alert">
                                    {error}
                                </div>
                            )}

                            <button
                                className="btn btn-success w-100 mt-auto"
                                onClick={onStart}
                                disabled={loading}
                            >
                                {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'Begin'}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>);
}

function StudyView({ participantId, currentQuestion, loading, error, handleSubmitResponse }) {
    if (!currentQuestion) return null;

    const isSubConcept = currentQuestion.type === 'sub_concept';
    const isImage = currentQuestion.type === 'image';

    return (
        <div className="container mt-5">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <div className="card-header d-flex justify-content-between align-items-center">
                            <h4 className="mb-0">Question</h4>
                            <small className="text-muted">Participant ID: {participantId}, Question {currentQuestion.number_answered + 1} of 100</small>
                        </div>
                        <div className="card-body">
                            {error && (
                                <div className="alert alert-danger" role="alert">
                                    {error}
                                </div>
                            )}

                            {isSubConcept && (
                                <div>
                                    <h5 className="mb-4">Is "{currentQuestion.sub_concept}" an example of "{currentQuestion.parent_concept}"?</h5>
                                    <small className="text-muted">Some of the words in the question are generated automatically, so if it does not make sense or is ambiguous, please answer it as best you can or choose "Not sure". Ignore the plurality of the words.</small>
                                </div>
                            )}

                            {isImage && (
                                <div>
                                    <h5 className="mb-3">Does this image show "{currentQuestion.concept}"?</h5>
                                    <small className="text-muted">Some of the words in the question are generated automatically, so if it does not make sense or is ambiguous, please answer it as best you can or choose "Not sure". Ignore plurality: for example, if you are asked 'Does this image show "lions"?' and the image contains a single lion, you should answer "Yes".</small>
                                    <div className="text-center mt-3">
                                        <img
                                            src={`X/${currentQuestion.image_file}`}
                                            alt="Study image"
                                            className="img-fluid"
                                            style={{ maxHeight: '400px', maxWidth: '100%' }}
                                        />
                                    </div>
                                </div>
                            )}

                            <div className="d-flex justify-content-center gap-3 mb-3 mt-3">
                                <button
                                    className="btn btn-success btn-lg px-5"
                                    onClick={() => handleSubmitResponse(1)}
                                    disabled={loading}
                                >
                                    {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'Yes'}
                                </button>
                                <button
                                    className="btn btn-danger btn-lg px-5"
                                    onClick={() => handleSubmitResponse(0)}
                                    disabled={loading}
                                >
                                    {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'No'}
                                </button>
                                {currentQuestion.type === 'sub_concept' && (
                                    <button
                                        className="btn btn-primary btn-lg px-5"
                                        onClick={() => handleSubmitResponse(2)}
                                        disabled={loading}
                                    >
                                        {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'They are the same'}
                                    </button>)}
                                <button
                                    className="btn btn-secondary btn-lg px-5"
                                    onClick={() => handleSubmitResponse(100)}
                                    disabled={loading}
                                >
                                    {loading ? <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span> : 'Not sure'}
                                </button>
                            </div>
                            <small className="text-muted">If you have had enough, you can close this tab at any time. Any answers you have already provided have been submitted. If you want to come back later and answer more questions, make a note of your participant ID. You cannot change an answer once it has been submitted.</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

function CompletedView({ participantId }) {
    return (
        <div className="container mt-5">
            <div className="row justify-content-center">
                <div className="col-md-6">
                    <div className="card">
                        <div className="card-body text-center">
                            <h3 className="text-success mb-4">Study Completed!</h3>
                            <p className="lead">Thank you for participating in our research study.</p>
                            <p>Your participant ID was: <strong>{participantId}</strong></p>
                            <p>Your responses have been recorded successfully.</p>
                            <p>If you have any questions about the study or your participation, please contact: X (<a href="mailto:X">X</a>).</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>);
}

export default function UserStudy() {
    const [currentView, setCurrentView] = useState('consent'); // 'consent', 'instructions', 'study', 'completed'
    const [participantId, setParticipantId] = useState('');
    const [currentQuestion, setCurrentQuestion] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    const API_BASE = '/api';

    const handleNewParticipant = async () => {
        setLoading(true);
        setError('');

        try {
            const response = await fetch(`${API_BASE}/new-participant`);
            if (!response.ok) {
                throw new Error('Failed to register new participant');
            }

            const data = await response.json();
            setParticipantId(data.participant_id);
            setCurrentView('instructions');
        } catch (err) {
            setError('Failed to register as new participant. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    const handleResumeParticipant = async (resumeId) => {
        if (!resumeId.trim()) {
            setError('Please enter your participant ID');
            return;
        }

        setLoading(true);
        setError('');

        try {
            setParticipantId(resumeId.trim());
            const response = await fetch(`${API_BASE}/participant?participant=${encodeURIComponent(resumeId.trim())}`);

            if (response.status !== 200) {
                throw new Error('Could not validate participant ID');
            }

            const data = await response.json();
            if (data.complete) {
                setCurrentView('completed');
            } else {
                setCurrentView('instructions');
            }
        } catch (err) {
            setError('Failed to resume session. Please check your participant ID.');
            setParticipantId('');
        } finally {
            setLoading(false);
        }
    };

    const fetchQuestion = async () => {
        setLoading(true);
        setError('');
        try {
            const response = await fetch(`${API_BASE}/question?participant=${encodeURIComponent(participantId)}`);

            if (!response.ok) {
                throw new Error('Failed to fetch question');
            }
            const question = await response.json();

            if (!question.question_available) {
                setCurrentView('completed');
            } else {
                setCurrentQuestion(question);
                setCurrentView('study');
            }
        } catch (err) {
            setError('Failed to fetch next question. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    const handleSubmitResponse = async (response) => {
        setLoading(true);
        setError('');

        try {
            const submitResponse = await fetch(`${API_BASE}/submit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    participant_id: participantId,
                    question_type: currentQuestion.type,
                    question_id: currentQuestion.type === 'sub_concept' ? currentQuestion.sub_concept_id : currentQuestion.image_id,
                    response: response
                })
            });

            if (!submitResponse.ok) {
                throw new Error('Failed to submit response');
            }

            const question = await submitResponse.json();

            if (!question.question_available) {
                setCurrentView('completed');
            } else {
                setCurrentQuestion(question);
                setCurrentView('study');
            }
        } catch (err) {
            setError('Failed to submit response. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div>
            {currentView === 'consent' && <ConsentView error={error} loading={loading} handleNewParticipant={handleNewParticipant} handleResumeParticipant={handleResumeParticipant} />}
            {currentView === 'instructions' && <InstructionsView error={error} loading={loading} onStart={fetchQuestion} participantId={participantId} />}
            {currentView === 'study' && <StudyView participantId={participantId} currentQuestion={currentQuestion} loading={loading} error={error} handleSubmitResponse={handleSubmitResponse} />}
            {currentView === 'completed' && <CompletedView participantId={participantId} />}
        </div>
    );
};
