import React, { useEffect, useRef, useState } from 'react';
import {
    Accordion,
    AccordionSummary,
    AccordionDetails,
    Typography,
    Grid,
    Modal,
    Box
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import './SampleImage.css';

interface RunDetailsProps {
    run: ExperimentParameters;
    basePath: string;
    onHeightChange?: (height: number) => void; // Callback to notify the parent about height changes
}

const RunDetails: React.FC<RunDetailsProps> = ({ run, onHeightChange, basePath }) => {
    const containerRef = useRef<HTMLDivElement | null>(null); // Ref to track component height
    const [currentHeight, setCurrentHeight] = useState<number>(0);
    const [modalOpen, setModalOpen] = useState<boolean>(false); // For modal state
    const [selectedImage, setSelectedImage] = useState<string | null>(null); // Tracks the selected image for the modal

    const { beamline_parameters, images } = run;
    const { synchrotron, beamline, detector } = beamline_parameters;

    // Calculate and notify the parent about height changes
    const updateHeight = () => {
        if (containerRef.current) {
            const newHeight = containerRef.current.offsetHeight;
            if (newHeight !== currentHeight) {
                setCurrentHeight(newHeight);
                if (onHeightChange) {
                    onHeightChange(newHeight);
                }
            }
        }
    };

    useEffect(() => {
        updateHeight(); // Update height on initial render
    }, []);

    useEffect(() => {
        // Update height whenever the component content changes
        const observer = new ResizeObserver(updateHeight);
        if (containerRef.current) {
            observer.observe(containerRef.current);
        }
        return () => {
            observer.disconnect();
        };
    }, [containerRef]);

    const handleImageClick = (imagePath: string) => {
        setSelectedImage(imagePath);
        setModalOpen(true); // Open the modal when the image is clicked
    };

    const closeModal = () => {
        setSelectedImage(null); // Clear the current image
        setModalOpen(false);
    };


    return (
        <div
            className="details-panel" // Add the class here
            ref={containerRef} // Attach the ref to the main container
            style={{
                display: 'flex',
                gap: '16px',
                padding: '16px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                alignItems: 'flex-start',
            }}
        >

        {/* Main Details Section */}
            <div style={{ flexGrow: 1 }}>
                <Typography variant="h6" gutterBottom>
                    Run {run.run_number} Details
                </Typography>
                <Typography variant="subtitle1" gutterBottom>
                    Beamline: {beamline} | Synchrotron: {synchrotron}
                </Typography>

                {/* Detector Details Accordion */}
                <Accordion>
                    <AccordionSummary
                        expandIcon={<ExpandMoreIcon />}
                        aria-controls="detector-content"
                        id="detector-header"
                    >
                        <Typography>
                            <strong>Detector Details</strong>
                        </Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                        <Typography>Manufacturer: {detector?.manufacturer || 'N/A'}</Typography>
                        <Typography>Model: {detector?.model || 'N/A'}</Typography>
                        <Typography>Type: {detector?.type || 'N/A'}</Typography>
                        <Typography>
                            Beam Center (px): x: {detector?.beamCenterX_px || 'N/A'}, y: {detector?.beamCenterY_px || 'N/A'}
                        </Typography>
                    </AccordionDetails>
                </Accordion>

                {/* Beamline Details Accordion */}
                <Accordion>
                    <AccordionSummary
                        expandIcon={<ExpandMoreIcon />}
                        aria-controls="beamline-content"
                        id="beamline-header"
                    >
                        <Typography>
                            <strong>Beamline Details</strong>
                        </Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                        <Typography>Synchrotron: {beamline_parameters?.synchrotron || 'N/A'}</Typography>
                        <Typography>Ring mode: {beamline_parameters?.ringMode || 'N/A'}</Typography>
                        <Typography>Ring current: {beamline_parameters?.ringCurrent_A || 'N/A'}</Typography>
                        <Typography>Beamline: {beamline_parameters?.beamline || 'N/A'}</Typography>
                        <Typography>Undulator: {beamline_parameters?.undulator || 'N/A'}</Typography>
                        <Typography>Undulator gap: {beamline_parameters?.undulatorgap_mm || 'N/A'}</Typography>
                        <Typography>Focusing optic: {beamline_parameters?.focusingOptic || 'N/A'}</Typography>
                        <Typography>Monochromator: {beamline_parameters?.monochromator || 'N/A'}</Typography>
                    </AccordionDetails>
                </Accordion>

                {/* Beam Characteristics Accordion */}
                <Accordion>
                    <AccordionSummary
                        expandIcon={<ExpandMoreIcon />}
                        aria-controls="beam-content"
                        id="beam-header"
                    >
                        <Typography>
                            <strong>Beam Characteristics</strong>
                        </Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                        <Typography>Wavelength: {beamline_parameters?.wavelength || 'N/A'}</Typography>
                        <Typography>Energy: {beamline_parameters?.energy || 'N/A'}</Typography>
                        <Typography>Transmission: {beamline_parameters?.transmission || 'N/A'}</Typography>
                        <Typography>
                            Beam focus (µm): vertical: {beamline_parameters?.beamSizeHeight || 'N/A'}, horizontal:{' '}
                            {beamline_parameters?.beamSizeWidth || 'N/A'}
                        </Typography>
                        <Typography>Flux at sample (ph/s): {beamline_parameters?.beamlineFluxAtSample_ph_s || 'N/A'}</Typography>
                    </AccordionDetails>
                </Accordion>
            </div>

            {/* Image Section */}
            <div style={{ width: '900px' }}>
                <Typography variant="h6" gutterBottom>
                    Associated Images
                </Typography>
                {images && images.length > 0 ? (
                    <Grid container spacing={1}>
                        {images.map((img) => (
                            <Grid item xs={4} key={img.id}>
                                <div
                                    className="image-container"
                                    onClick={() => handleImageClick(`${basePath || ''}${img.filepath}`)} // Open modal with image
                                    style={{
                                        cursor: 'pointer',
                                    }}
                                >
                                    <img
                                        src={`${basePath || ''}${img.filepath}`} // Ensure basePath
                                        alt={img.comment || 'Image'}
                                        className="zoom-image"
                                        style={{
                                            width: '100%', // Ensure the image takes the full width of its container
                                            maxWidth: '100%', // Prevent any overflow
                                            borderRadius: '4px',
                                        }}
                                    />
                                </div>
                            </Grid>
                        ))}
                    </Grid>
                ) : (
                    <Typography variant="body2" color="textSecondary">
                        No images available.
                    </Typography>
                )}
            </div>

            {/* Modal for Zoomed Image */}
            <Modal open={modalOpen} onClose={closeModal}>
                <Box
                    style={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        backgroundColor: '#fff',
                        boxShadow: 24,
                        padding: 16,
                        maxHeight: '90%',
                        overflow: 'auto',
                    }}
                >
                    {selectedImage && (
                        <img
                            src={selectedImage}
                            alt="Zoomed"
                            style={{
                                maxWidth: '100%',
                                height: 'auto',
                                borderRadius: '4px',
                            }}
                        />
                    )}
                </Box>
            </Modal>
        </div>
    );
};

export default RunDetails;