import React, { useEffect, useState } from 'react';
import { DataGridPremium, GridColDef } from '@mui/x-data-grid-premium';
import { useNavigate } from 'react-router-dom'; // For navigation
import { BeamtimesService } from '../../openapi';
import { Chip, Typography } from '@mui/material';

interface BeamtimeRecord {
    id: number;
    start_date: string;
    end_date: string;
    shift: string;
    beamline: string;
    local_contact: string;
    pgroups: string;
}

interface BeamtimeOverviewProps {
    activePgroup: string;
    onPgroupChange: (pgroup: string) => void; // Add callback to update the selected pgroup
}

const BeamtimeOverview: React.FC<BeamtimeOverviewProps> = ({ activePgroup, onPgroupChange }) => {
    const [rows, setRows] = useState<BeamtimeRecord[]>([]);
    const [isLoading, setIsLoading] = useState(false);

    // For navigation
    const navigate = useNavigate();

    const renderPgroupChips = (pgroups: string, activePgroup: string) => {
        // Safely handle pgroups as an array
        const pgroupsArray = pgroups.split(",").map((pgroup: string) => pgroup.trim());

        if (!pgroupsArray.length) {
            return <Typography variant="body2">No associated pgroups</Typography>;
        }

        return pgroupsArray.map((pgroup: string) => (
            <Chip
                key={pgroup}
                label={pgroup}
                color={pgroup === activePgroup ? "primary" : "default"} // Highlight active pgroups
                sx={{
                    margin: 0.5,
                    backgroundColor: pgroup === activePgroup ? '#19d238' : '#b0b0b0',
                    color: pgroup === activePgroup ? 'white' : 'black',
                    fontWeight: 'bold',
                    borderRadius: '8px',
                    height: '20px',
                    fontSize: '12px',
                    boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.2)',
                    mr: 1,
                    mb: 1,
                }}
            />
        ));
    };

    // Fetch beamtime records from the backend
    const fetchBeamtimeRecords = async () => {
        try {
            setIsLoading(true);
            const records = await BeamtimesService.getMyBeamtimesProtectedBeamtimesMyBeamtimesGet(activePgroup);

            const mappedRecords: BeamtimeRecord[] = records.map((record: any) => ({
                id: record.id,
                start_date: record.start_date || 'N/A',
                end_date: record.end_date || 'N/A',
                shift: record.shift || 'N/A',
                beamline: record.beamline || 'N/A',
                local_contact: `${record.local_contact.firstname || "N/A"} ${record.local_contact.lastname || "N/A"}`,
                pgroups: record.pgroups || '',
            }));

            setRows(mappedRecords);
        } catch (error) {
            console.error('Failed to fetch beamtime records:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchBeamtimeRecords();
    }, [activePgroup]);

    // Define table columns, including the "View Results" button
    const columns: GridColDef<BeamtimeRecord>[] = [
        { field: 'start_date', headerName: 'Start Date', flex: 1 },
        { field: 'end_date', headerName: 'End Date', flex: 1 },
        { field: 'shift', headerName: "Shift", flex: 1 },
        { field: 'beamline', headerName: 'Beamline', flex: 1 },
        { field: 'local_contact', headerName: 'Local Contact', flex: 1 },
        {
            field: 'pgroups',
            headerName: 'Pgroups',
            flex: 2, // Slightly wider column for chips
            renderCell: (params) => renderPgroupChips(params.row.pgroups, activePgroup),
        },
        {
            field: 'viewResults',
            headerName: 'Actions',
            flex: 1,
            renderCell: (params) => (
                <button
                    onClick={() => handleViewResults(params.row.id, params.row.pgroups)}
                    style={{
                        padding: '6px 12px',
                        backgroundColor: '#1976d2',
                        color: '#fff',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: 'pointer',
                    }}
                >
                    View Results
                </button>
            ),
        },
    ];

    // Navigate to the ResultsView page for the selected beamtime
    const handleViewResults = (beamtimeId: number, pgroups: string) => {
        const pgroupArray = pgroups.split(',').map((pgroup) => pgroup.trim());
        const firstPgroup = pgroupArray[0] || ''; // Choose the first pgroup (or fallback to empty string)

        // Ensure onPgroupChange is invoked correctly
        onPgroupChange(firstPgroup);

        // Navigate directly to the Results page with the correct pgroup in the query
        navigate(`/results/${beamtimeId}?pgroup=${firstPgroup}`);
    };

    return (
        <div style={{ height: 400, width: '100%' }}>
            <h2>Beamtime Overview</h2>
            <DataGridPremium
                rows={rows}
                columns={columns}
                loading={isLoading}
                disableRowSelectionOnClick
            />
        </div>
    );
};

export default BeamtimeOverview;