import React, { useEffect, useState } from "react";
import { DataGrid, GridColDef, GridCellEditStopParams } from "@mui/x-data-grid";
import { DewarsService } from "../../openapi";

interface SampleSpreadsheetProps {
    dewarId: number; // Selected Dewar's ID
}

const SampleSpreadsheet: React.FC<SampleSpreadsheetProps> = ({ dewarId }) => {
    const [rows, setRows] = useState<any[]>([]); // Rows for the grid
    const [columns, setColumns] = useState<GridColDef[]>([]); // Columns for the grid

    // Fetch rows and columns related to the given Dewar ID
    useEffect(() => {
        if (!dewarId) {
            console.error("Invalid or missing Dewar ID");
            return;
        }

        const fetchSamples = async () => {
    try {
        const response = await DewarsService.getDewarSamplesDewarsDewarsDewarIdSamplesGet(dewarId);
        const dewarData = response; // Assume response is already in correct structure

        // Transform pucks and samples into rows for the grid
        const allRows = [];
        dewarData.pucks.forEach((puck: any) => {
            puck.samples.forEach((sample: any) => {
                allRows.push({
                    id: sample.id,
                    puckId: puck.id,
                    puckName: puck.name,
                    puckType: puck.type,
                    dewarName: dewarData.dewar.dewar_name,
                    position: sample.position,
                    crystalName: sample.sample_name,
                    proteinName: sample.proteinname,
                    priority: sample.priority,
                    comments: sample.comments,
                    directory: sample.directory,
                    oscillation: sample.oscillation,
                    aperture: sample.aperture,
                    exposure: sample.exposure,
                    totalRange: sample.totalrange,
                    transmission: sample.transmission,
                    dose: sample.dose,
                    targetResolution: sample.targetresolution,
                    datacollectiontype: sample.datacollectiontype,
                    processingpipeline: sample.processingpipeline,
                    spacegroupnumber: sample.spacegroupnumber,
                    cellparameters: sample.cellparameters,
                    rescutkey: sample.rescutkey,
                    //rescutvalues: sample.rescutvalues,
                    pdbid: sample.pdbid,
                    autoprocfull: sample.autoprocfull,
                    procfull: sample.procfull,
                    adpenabled: sample.adpenabled,
                    noano: sample.noano,
                    ffcscampaign: sample.ffcscampaign,
                });
            });
        });
        setRows(allRows);

        setColumns([
            { field: "dewarName", headerName: "Dewar Name", width: 150, editable: false },
            { field: "puckName", headerName: "Puck Name", width: 150 },
            { field: "puckType", headerName: "Puck Type", width: 150 },
            { field: "crystalName", headerName: "Crystal Name", width: 200, editable: true },
            { field: "proteinName", headerName: "Protein Name", width: 200, editable: true },
            { field: "position", headerName: "Position", width: 100, editable: true, type: "number" },
            { field: "priority", headerName: "Priority", width: 100, editable: true, type: "number" },
            { field: "comments", headerName: "Comments", width: 300, editable: true },
            { field: "directory", headerName: "Directory", width: 200 },
            { field: "oscillation", headerName: "Oscillation", width: 150, editable: true, type: "number" },
            { field: "aperture", headerName: "Aperture", width: 150, editable: true, type: "number" },
            { field: "exposure", headerName: "Exposure", width: 150, editable: true, type: "number" },
            { field: "totalRange", headerName: "Total Range", width: 150, editable: true, type: "number" },
            { field: "transmission", headerName: "Transmission", width: 150, editable: true, type: "number" },
            { field: "dose", headerName: "Dose", width: 150, editable: true, type: "number" },
            { field: "targetResolution", headerName: "Target Resolution", width: 200, editable: true, type: "number" },
            { field: "datacollectiontype", headerName: "Data Collection Type", width: 200 },
            { field: "processingpipeline", headerName: "Processing Pipeline", width: 200 },
            { field: "spacegroupnumber", headerName: "Space Group Number", width: 150, type: "number" },
            { field: "cellparameters", headerName: "Cell Parameters", width: 200 },
            { field: "rescutkey", headerName: "Rescut Key", width: 150 },
            { field: "pdbid", headerName: "PDB ID", width: 150 },
            { field: "autoprocfull", headerName: "Auto Proc Full", width: 150 },
            { field: "procfull", headerName: "Proc Full", width: 150 },
            { field: "adpenabled", headerName: "ADP Enabled", width: 150, editable: true, type: "boolean" },
            { field: "noano", headerName: "No Ano", width: 150, editable: true, type: "boolean" },
            { field: "ffcscampaign", headerName: "FFCS Campaign", width: 200 },
        ]);
    } catch (error) {
        console.error("Error fetching dewar samples:", error);
    }
};

        fetchSamples();
    }, [dewarId]);

    // Handle cell editing to persist changes to the backend
    const handleCellEditStop = async (params: GridCellEditStopParams) => {
        const { id, field, value } = params;
        try {
            // Example: Replace with a proper OpenAPI call if available
            await DewarsService.updateSampleData(id as number, { [field]: value }); // Assuming this exists
            console.log("Updated successfully");
        } catch (error) {
            console.error("Error saving data:", error);
        }
    };

    return (
        <div style={{ height: 500, width: "100%" }}>
            <DataGrid
                rows={rows}
                columns={columns}
                pageSize={10}
                onCellEditStop={handleCellEditStop}
            />
        </div>
    );
};

export default SampleSpreadsheet;