import React, { useEffect } from 'react';
import { useParams, useSearchParams, useNavigate } from 'react-router-dom';
import SampleTracker from '../components/SampleTracker';
import ResultGrid from '../components/ResultGrid';

interface ResultsViewProps {
    onPgroupChange?: (pgroup: string) => void; // Callback to notify about pgroup changes
    currentPgroup: string; // Currently selected pgroup
}

const ResultsView: React.FC<ResultsViewProps> = ({ onPgroupChange, currentPgroup }) => {
    const { beamtimeId } = useParams();
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();

    // Get the active pgroup for the experiment from the query params.
    const activePgroup = searchParams.get("pgroup") ?? ''; // Default to an empty string if missing

    // Redirect if the selected pgroup does not match the beamtime's pgroup
    useEffect(() => {
        if (!currentPgroup || currentPgroup !== activePgroup) {
            console.warn(
                `Redirecting to BeamtimeOverview because selected pgroup (${currentPgroup || "undefined"}) does not match beamtime's pgroup (${activePgroup})`
            );
            navigate('/beamtime-overview'); // Redirect to BeamtimeOverview
        }
    }, [currentPgroup, activePgroup, navigate]);

    // Notify parent about the selected pgroup (if needed)
    useEffect(() => {
        // Synchronize the pgroup when the component loads
        if (onPgroupChange && activePgroup !== currentPgroup) {
            onPgroupChange(activePgroup); // Update the selected pgroup
        }
    }, [onPgroupChange, activePgroup, currentPgroup]);


    return (
        <div>
            <h1>Results Page</h1>
            <h2>Results for Beamtime ID: {beamtimeId}</h2>

            {/* Use the beamtimeId to filter or query specific results */}
            <SampleTracker activePgroup={activePgroup} beamtimeId={beamtimeId} />
            <ResultGrid activePgroup={activePgroup} beamtimeId={beamtimeId} />
        </div>
    );
};

export default ResultsView;