import React, {useMemo, useState, useEffect} from "react";
import {
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Paper,
    Select,
    MenuItem,
    TextField,
    CircularProgress,
    Box,
    Tooltip,
    Typography,
    TableSortLabel,
    Button,
    Fade,
    Grow, Card, CardContent, CardHeader,
} from "@mui/material";
import {CriterionCycleBox, CriterionState} from "./CriterionCycleBox";
import {TransitionGroup, CSSTransition} from 'react-transition-group';
import {KeyValueTable} from "./KeyValueTable";
import {MarkData} from "../../models/ProgressTrackerModels";

export interface Student
{
    id: number;
    fullName: string;
    targetGrade: string | null;
    reference?: string;
    callouts?: string[];
    pronouns?: string;
    links?: { rel: string; href: string; type: string; title?: string }[];
}

export interface PartGuiConfig
{
    gradeCol: "VISIBLE" | "EDITABLE" | "HIDDEN";
    scoreCol: "VISIBLE" | "EDITABLE" | "HIDDEN";
    unitCriteria: "VISIBLE" | "EDITABLE" | "HIDDEN";
    cellSummaryResultMetric?: "grade" | "score";
}


// New interface for part info
export interface Part
{
    id: number;
    name: string;
    ref: string;
    guiConfig: PartGuiConfig;
}

export interface PTMarkScreenProps
{
    trackerId: number;
    partId: number;
    students: Student[];
    partGuiConfig: PartGuiConfig;
    initialMarks: { [studentId: number]: MarkData };
    loading?: boolean;
    onSave?: (marks: { [studentId: number]: MarkData }) => Promise<{ success: boolean; message: string }>;
    saveStatus?: 'idle' | 'saving' | 'saved' | 'error';
    // New props for summary view
    isSummaryView?: boolean;
    parts?: Part[];
    partMarks?: { [partId: number]: { [studentId: number]: MarkData } };
    onPartHeaderClick?: (partId: number) => void;

    // Lifted state from parent component
    onMarkChange?: (studentId: number, field: keyof MarkData, value: any) => void;
    onCriterionChange?: (studentId: number, criterionName: string, value: CriterionState | null) => void;
    onCriterionHeaderClick?: (criterionName: string) => void;
    onSortRequest?: (field: keyof Student | 'score' | 'grade') => void;
    sortBy?: keyof Student | 'score' | 'grade' | null;
    sortDirection?: 'asc' | 'desc';
    manuallyModifiedCriteria?: { [studentId: number]: { [criterionName: string]: boolean } };
    hasChanges?: boolean;    // Reload functionality
    onReload?: () => Promise<void>;

    // Grade-related functions
    getGradeOptionsForPart?: (partId: number) => Array<{ value: string; label: string }>;
    getGradeDisplayName?: (gradeRef: string, partId: number) => string;
}

export const PTMarkScreen = ({
                                 trackerId,
                                 partId,
                                 students,
                                 partGuiConfig,
                                 initialMarks,
                                 loading = false,
                                 onSave,
                                 saveStatus = 'idle',
                                 // New props with defaults
                                 isSummaryView = false,
                                 parts = [],
                                 partMarks = {},
                                 onPartHeaderClick,
                                 // Lifted state props with defaults
                                 onMarkChange,
                                 onCriterionChange,
                                 onCriterionHeaderClick,
                                 onSortRequest,
                                 sortBy = null,
                                 sortDirection = 'asc',
                                 manuallyModifiedCriteria = {},
                                 hasChanges = false,
                                 // Reload functionality
                                 onReload,
                                 // Grade-related functions
                                 getGradeOptionsForPart,
                                 getGradeDisplayName
                             }: PTMarkScreenProps) => {
    console.log('partMarks', partMarks);
    // Animation state for transition effects
    const [viewKey, setViewKey] = useState<string>(`${isSummaryView}-${partId}`);
    const [transitionIn, setTransitionIn] = useState(true);

    // Reload state
    const [isReloading, setIsReloading] = useState(false);

    // Update view key when key view properties change
    useEffect(() => {
        const newViewKey = `${isSummaryView}-${partId}`;
        if (viewKey !== newViewKey) {
            // Start exit animation
            setTransitionIn(false);

            // After animation completes, update content and start entrance animation
            const timer = setTimeout(() => {
                setViewKey(newViewKey);
                setTransitionIn(true);
            }, 300); // Match this timing with CSS transition duration

            return () => clearTimeout(timer);
        }
    }, [isSummaryView, partId, viewKey]);

    // Get all unique criterion names across all students
    const criteriaNames = useMemo(() => {
        if (!initialMarks || Object.keys(initialMarks).length === 0) return [];

        const allCriteriaNames = new Set<string>();

        Object.values(initialMarks).forEach(mark => {
            if (mark.criteria) {
                Object.keys(mark.criteria).forEach(name => allCriteriaNames.add(name));
            }
        });

        // Define priority order for criteria types (P, M, D)
        const criteriaTypeOrder: { [key: string]: number } = {
            'P': 1,
            'M': 2,
            'D': 3
        };

        // Sort criteria names (P1, P2, M1, M2, D1, D2, etc.)
        return Array.from(allCriteriaNames).sort((a, b) => {
            // Extract letter and number
            const letterA = a.match(/[A-Za-z]+/)?.[0] || '';
            const letterB = b.match(/[A-Za-z]+/)?.[0] || '';

            const numberA = parseInt(a.match(/\d+/)?.[0] || '0', 10);
            const numberB = parseInt(b.match(/\d+/)?.[0] || '0', 10);

            // First sort by criteria type priority (P, M, D)
            const priorityA = criteriaTypeOrder[letterA] || 999;
            const priorityB = criteriaTypeOrder[letterB] || 999;

            if (priorityA !== priorityB) return priorityA - priorityB;

            // Then sort by number
            return numberA - numberB;
        });
    }, [initialMarks]);

    // Handler functions that now delegate to props when provided
    const handleMarkChange = (studentId: number, field: keyof MarkData, value: any) => {
        console.log("PTMarkScreen handleMarkChange called", {studentId, field, value});
        if (onMarkChange) {
            onMarkChange(studentId, field, value);
        }
    };

    const handleCriterionChange = (studentId: number, criterionName: string, value: CriterionState | null) => {
        console.log("PTMarkScreen handleCriterionChange called", {studentId, criterionName, value});
        if (onCriterionChange) {
            onCriterionChange(studentId, criterionName, value);
        }
    };

    const handleCriterionHeaderClick = (criterionName: string) => {
        if (onCriterionHeaderClick) {
            onCriterionHeaderClick(criterionName);
        }
    };

    const handleSortRequest = (field: keyof Student | 'score' | 'grade') => {
        if (onSortRequest) {
            onSortRequest(field);
        }
    };

    const handlePartHeaderClick = (partId: number) => {
        if (onPartHeaderClick) {
            onPartHeaderClick(partId);
        }
    };

    // Get the sorted list of students
    const sortedStudents = useMemo(() => {
        if (!sortBy || !students.length) return students;

        return [...students].sort((a, b) => {
            const direction = sortDirection === 'asc' ? 1 : -1;

            // Sort by different fields based on sortBy
            if (sortBy === 'fullName') {
                return direction * a.fullName.localeCompare(b.fullName);
            }

            if (sortBy === 'targetGrade') {
                // Handle null values
                if (a.targetGrade === null && b.targetGrade === null) return 0;
                if (a.targetGrade === null) return direction * 1;
                if (b.targetGrade === null) return direction * -1;

                return direction * a.targetGrade.localeCompare(b.targetGrade);
            }

            if (sortBy === 'score') {
                const scoreA = initialMarks[a.id]?.score || 0;
                const scoreB = initialMarks[b.id]?.score || 0;
                return direction * (scoreA - scoreB);
            }

            if (sortBy === 'grade') {
                const gradeA = initialMarks[a.id]?.grade || '';
                const gradeB = initialMarks[b.id]?.grade || '';
                return direction * gradeA.localeCompare(gradeB);
            }

            return 0;
        });
    }, [students, initialMarks, sortBy, sortDirection]);

    // Check if all target grades are null, empty or "N/A" to determine if the column should be shown
    const showTargetGradeColumn = useMemo(() => {
        if (!students.length) return false;

        return students.some(student => {
            const grade = student.targetGrade;
            return grade !== null && grade !== "" && grade !== "N/A";
        });
    }, [students]);    // Handle save button click - properly fixed
    const handleSave = async () => {
        console.log("Save button clicked in PTMarkScreen");
        if (onSave) {
            console.log("Calling onSave handler with marks:", initialMarks);
            try {
                // Call the onSave prop passing the current marks
                const result = await onSave(initialMarks);
                console.log("Save result received:", result);

                // If save was successful, trigger reload after showing success message briefly
                if (result.success && onReload) {
                    // Wait a moment to show the success message
                    setTimeout(async () => {
                        try {
                            setIsReloading(true);
                            await onReload();
                            console.log("Data reloaded successfully after save");
                        } catch (error) {
                            console.error("Error reloading data after save:", error);
                        } finally {
                            setIsReloading(false);
                        }
                    }, 1000); // Show success for 1 second before reloading
                }

                return result;
            } catch (error) {
                console.error("Error in PTMarkScreen handleSave:", error);
                throw error; // Re-throw so parent can handle it
            }
        } else {
            console.warn("No onSave handler provided to PTMarkScreen");
        }
    };
    if (loading || isReloading) {
        return (
            <Box sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                minHeight: '200px',
                gap: 2
            }}>
                <CircularProgress/>
                {isReloading && (
                    <Typography variant="body2" color="text.secondary">
                        Reloading latest data...
                    </Typography>
                )}
            </Box>
        );
    }


    // todo pt-future: Simplify this object. This is way too complicated. Consider splitting up Summary/Detail views.

    return (
        <div style={{width: 'max-content'}}>
            <Fade in={transitionIn} timeout={300} key={viewKey}>
                <div className="pt-mark-screen">
                    {/*  Create a details grid showing top-level details about this specific part type, where applicable.
                     E.g. if this part type supports scoring, show max score. If it is a unit type, show the required GLH and required pass/merit/distinction/lowerpass criteria.
                     If it has a gradeset, show the gradeset name.
                   */}
                    {!isSummaryView && (
                        <div className="part-details mb-4">
                            {/* todo pt Implement as below */}
                            {/*<Card>*/}
                            {/*    /!* Todo pt-future: Improve this. *!/*/}
                            {/*    <CardHeader title="Overview" className="pb-1 pt-3"*/}
                            {/*                slotProps={{title: {fontSize: '1.2rem'}}}/>*/}
                            {/*    <CardContent className="pb-1 pt-1">*/}
                            {/*        <KeyValueTable data={{*/}
                            {/*            "Reference": "ABC/653/MAT",*/}
                            {/*            "GLH": "1080",*/}
                            {/*            "Awarding Body": "Pearson",*/}
                            {/*        }}/>*/}
                            {/*    </CardContent>*/}
                            {/*</Card>*/}
                        </div>

                    )} <Grow in={transitionIn} timeout={350} style={{transformOrigin: 'center top'}}>
                    <Box sx={{position: 'relative'}}>
                        {/* Reload overlay */}
                        {isReloading && (
                            <Box
                                sx={{
                                    position: 'absolute',
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    backgroundColor: 'rgba(255, 255, 255, 0.8)',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    zIndex: 1000,
                                    borderRadius: '4px',
                                    gap: 1
                                }}
                            >
                                <CircularProgress size={32}/>
                                <Typography variant="body2" color="text.secondary">
                                    Reloading latest data...
                                </Typography>
                            </Box>
                        )}

                        <TableContainer
                            component={Paper}
                            sx={{
                                width: 'max-content',
                                maxWidth: '95%',
                                overflow: 'auto',
                                maxHeight: '30rem',
                                transition: 'all 0.3s ease-in-out'
                            }}
                            className="pt-marking-table"
                        >
                            <Table size="small" sx={{tableLayout: "auto"}}>
                                <TableHead>
                                    <TableRow>
                                        <TableCell
                                            className="text-start"
                                            sortDirection={sortBy === 'fullName' ? sortDirection : false}
                                        >
                                            <TableSortLabel
                                                active={sortBy === 'fullName'}
                                                direction={sortBy === 'fullName' ? sortDirection : 'asc'}
                                                onClick={() => handleSortRequest('fullName')}
                                            >
                                                Student Name
                                            </TableSortLabel>
                                        </TableCell>

                                        {/* Target Grade column - only show if at least one student has a target grade */}
                                        {showTargetGradeColumn && (
                                            <TableCell
                                                align="center"
                                                sortDirection={sortBy === 'targetGrade' ? sortDirection : false}
                                            >
                                                <TableSortLabel
                                                    active={sortBy === 'targetGrade'}
                                                    direction={sortBy === 'targetGrade' ? sortDirection : 'asc'}
                                                    onClick={() => handleSortRequest('targetGrade')}
                                                >
                                                    Target Grade
                                                </TableSortLabel>
                                            </TableCell>
                                        )}

                                        {/* Summary View: Part Columns */}
                                        {isSummaryView && parts.map(part => (
                                            <TableCell
                                                key={`part-${part.id}`}
                                                align="center"
                                                sx={{
                                                    p: 1,
                                                    minWidth: '80px',
                                                    fontWeight: 'bold',
                                                    cursor: 'pointer',
                                                    border: '1px solid rgba(224, 224, 224, 1)',
                                                    borderBottom: '2px solid rgba(25, 118, 210, 0.5)',
                                                    transition: 'all 0.2s ease',
                                                    '&:hover': {
                                                        backgroundColor: 'rgba(25, 118, 210, 0.08)',
                                                        boxShadow: '0px 2px 5px rgba(0, 0, 0, 0.1)',
                                                    },
                                                }}
                                                onClick={() => handlePartHeaderClick(part.id)}
                                            >
                                                <Tooltip title={`Click to view details for ${part.ref}`}>
                                                    <Box>
                                                        <Typography
                                                            variant="subtitle2"
                                                            noWrap
                                                            sx={{
                                                                display: 'flex',
                                                                alignItems: 'center',
                                                                justifyContent: 'center',
                                                                color: 'var(--green)',
                                                                textDecoration: 'underline',
                                                                fontWeight: 'medium'
                                                            }}
                                                        >
                                                            {part.name}
                                                        </Typography>
                                                        <Typography variant="caption" color="text.secondary"
                                                                    sx={{display: 'block'}}>
                                                            {part.ref}
                                                        </Typography>
                                                    </Box>
                                                </Tooltip>
                                            </TableCell>
                                        ))}

                                        {/* Regular View: Criteria Columns */}
                                        {!isSummaryView && partGuiConfig.unitCriteria !== "HIDDEN" &&
                                            criteriaNames.map(name => (
                                                <TableCell
                                                    key={name}
                                                    align="center"
                                                    sx={{
                                                        p: 1,
                                                        minWidth: '50px',
                                                        maxWidth: '60px',
                                                        fontWeight: 'bold',
                                                        cursor: partGuiConfig.unitCriteria === "EDITABLE" ? 'pointer' : 'default',
                                                        '&:hover': partGuiConfig.unitCriteria === "EDITABLE" ? {
                                                            backgroundColor: 'rgba(0, 0, 0, 0.04)',
                                                        } : {},
                                                    }}
                                                    onClick={() => handleCriterionHeaderClick(name)}
                                                >
                                                    {/* TODO PT: Fix this: */}
                                                    {/*<Tooltip title={`Click to cycle all ${name} values`}>*/}
                                                    <Tooltip title="">
                                                        <span>{name}</span>
                                                    </Tooltip>
                                                </TableCell>
                                            ))
                                        }

                                        {/* Regular View: Score/Grade Columns */}
                                        {!isSummaryView && partGuiConfig.scoreCol !== "HIDDEN" && (
                                            <TableCell
                                                align="center"
                                                sortDirection={sortBy === 'score' ? sortDirection : false}
                                            >
                                                <TableSortLabel
                                                    active={sortBy === 'score'}
                                                    direction={sortBy === 'score' ? sortDirection : 'asc'}
                                                    onClick={() => handleSortRequest('score')}
                                                >
                                                    Score
                                                </TableSortLabel>
                                            </TableCell>
                                        )}

                                        {!isSummaryView && partGuiConfig.gradeCol !== "HIDDEN" && (
                                            <TableCell
                                                align="center"
                                                sortDirection={sortBy === 'grade' ? sortDirection : false}
                                            >
                                                <TableSortLabel
                                                    active={sortBy === 'grade'}
                                                    direction={sortBy === 'grade' ? sortDirection : 'asc'}
                                                    onClick={() => handleSortRequest('grade')}
                                                >
                                                    Grade
                                                </TableSortLabel>
                                            </TableCell>
                                        )}
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    {sortedStudents.map((student) => (
                                        <TableRow key={student.id}>
                                            <TableCell align="left" sx={{fontSize: '1.05rem'}}>
                                                {student.reference ? (
                                                    <mini-profile
                                                        name={student.fullName}
                                                        callout-csv={student.callouts?.join(',')}
                                                        pronouns={student.pronouns || ''}
                                                        reference={student.reference}
                                                        photo-url={`${window.location.origin}/public/photo/image/${student.id}-${student.reference}`}
                                                        profile-url={`${window.location.origin}/student/${student.reference}`}
                                                        show-name="true"
                                                    />
                                                ) : (
                                                    student.fullName
                                                )}
                                            </TableCell>

                                            {/* Target Grade cell - only show if at least one student has a target grade */}
                                            {showTargetGradeColumn && (
                                                <TableCell align="center">
                                                    {student.targetGrade ? (
                                                        <Box
                                                            sx={{
                                                                display: 'inline-block',
                                                                fontSize: '1.1rem',
                                                                padding: '2px 8px',
                                                                borderRadius: '4px',
                                                                backgroundColor: 'rgba(0, 0, 0, 0.01)',
                                                                border: '1px solid rgba(0, 0, 0, 0.08)',
                                                                minWidth: '35px',
                                                                color: 'text.primary',
                                                            }}
                                                        >
                                                            {student.targetGrade}
                                                        </Box>
                                                    ) : (
                                                        <Typography variant="body2"
                                                                    color="text.secondary">N/A</Typography>
                                                    )}
                                                </TableCell>
                                            )}

                                            {/* Summary View: Part Data Cells */}
                                            {isSummaryView && parts.map(part => {
                                                const studentPartData = partMarks[part.id]?.[student.id];
                                                // Determine whether to display grade or score based on configuration
                                                const displayMetric = part.guiConfig.cellSummaryResultMetric || "grade";
                                                const displayValue = displayMetric === "grade" ?
                                                    studentPartData?.grade :
                                                    studentPartData?.score !== undefined ? String(studentPartData.score) : null;

                                                return (
                                                    <TableCell key={`part-${part.id}-student-${student.id}`}
                                                               align="center">
                                                        {displayValue ? (
                                                            <Box
                                                                sx={{
                                                                    display: 'inline-block',
                                                                    fontSize: '1rem',
                                                                    padding: '2px 8px',
                                                                    borderRadius: '4px',
                                                                    backgroundColor: displayMetric === "grade" ? 'rgba(25, 118, 210, 0.08)' : 'rgba(25, 118, 210, 0.04)',
                                                                    border: '1px solid rgba(25, 118, 210, 0.2)',
                                                                    minWidth: '35px',
                                                                }}
                                                            >
                                                                {displayValue}
                                                            </Box>
                                                        ) : (
                                                            <Typography variant="body2"
                                                                        color="text.secondary">-</Typography>
                                                        )}
                                                    </TableCell>
                                                );
                                            })}

                                            {/* Regular View: Criteria Cells */}
                                            {!isSummaryView && partGuiConfig.unitCriteria !== "HIDDEN" &&
                                                criteriaNames.map(criterionName => (
                                                    <TableCell key={criterionName} align="center" sx={{p: 0.5}}>
                                                        <CriterionCycleBox
                                                            criterionName={criterionName}
                                                            value={initialMarks[student.id]?.criteria?.[criterionName] || null}
                                                            onChange={(newValue) => handleCriterionChange(student.id, criterionName, newValue)}
                                                            disabled={partGuiConfig.unitCriteria !== "EDITABLE"}
                                                            compact
                                                        />
                                                    </TableCell>
                                                ))
                                            } {/* Regular View: Score/Grade Cells */}
                                            {!isSummaryView && partGuiConfig.scoreCol !== "HIDDEN" && (
                                                <TableCell align="center">
                                                    {partGuiConfig.scoreCol === "EDITABLE" ? (
                                                        <TextField
                                                            type="number"
                                                            value={initialMarks[student.id]?.score || ""}
                                                            onChange={(e) =>
                                                                handleMarkChange(student.id, "score", parseInt(e.target.value, 10) || 0)
                                                            }
                                                            size="small" sx={{
                                                            width: '80px',
                                                            '& .MuiInputBase-input': {textAlign: 'center'}
                                                        }}
                                                            inputProps={{style: {textAlign: 'center'}}}/>
                                                    ) : (
                                                        // VISIBLE but not EDITABLE
                                                        <Box
                                                            sx={{
                                                                width: '80px',
                                                                minHeight: '32px',
                                                                margin: '0 auto',
                                                                display: 'flex',
                                                                alignItems: 'center',
                                                                justifyContent: 'center',
                                                                padding: '4px 8px',
                                                                border: '1px solid rgba(0, 0, 0, 0.23)',
                                                                borderRadius: '4px',
                                                                backgroundColor: 'rgba(0, 0, 0, 0.04)',
                                                                color: initialMarks[student.id]?.score ? 'text.primary' : 'text.secondary',
                                                                fontSize: '0.875rem',
                                                                fontStyle: initialMarks[student.id]?.score ? 'normal' : 'italic',
                                                                opacity: 0.7
                                                            }}
                                                        >
                                                            {initialMarks[student.id]?.score ?? "Unset"}
                                                        </Box>
                                                    )}
                                                </TableCell>
                                            )} {!isSummaryView && partGuiConfig.gradeCol !== "HIDDEN" && (
                                            <TableCell align="center">
                                                {partGuiConfig.gradeCol === "EDITABLE" ? (
                                                    <Select
                                                        value={initialMarks[student.id]?.grade || ""}
                                                        onChange={(e) => handleMarkChange(student.id, "grades", e.target.value)}
                                                        size="small"
                                                        sx={{
                                                            width: '120px',
                                                            textAlign: 'center'
                                                        }}
                                                    >
                                                        {getGradeOptionsForPart ?
                                                            getGradeOptionsForPart(partId).map((option) => (
                                                                <MenuItem key={option.value} value={option.value}>
                                                                    {option.label}
                                                                </MenuItem>
                                                            ))
                                                            :
                                                            // Fallback to hardcoded options if getGradeOptionsForPart is not provided
                                                            <>
                                                                <MenuItem value="">Select...</MenuItem>
                                                            </>
                                                        }
                                                    </Select>) : (
                                                    // VISIBLE but not EDITABLE
                                                    <Box
                                                        sx={{
                                                            width: '120px',
                                                            minHeight: '32px',
                                                            margin: '0 auto',
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            justifyContent: 'center',
                                                            padding: '4px 8px',
                                                            border: '1px solid rgba(0, 0, 0, 0.23)',
                                                            borderRadius: '4px',
                                                            backgroundColor: 'rgba(0, 0, 0, 0.04)',
                                                            color: initialMarks[student.id]?.grade ? 'text.primary' : 'text.secondary',
                                                            fontSize: '0.875rem',
                                                            fontStyle: initialMarks[student.id]?.grade ? 'normal' : 'italic',
                                                            opacity: 0.7
                                                        }}
                                                    >                                                        {initialMarks[student.id]?.grade ?
                                                            (getGradeDisplayName ?
                                                                getGradeDisplayName(initialMarks[student.id].grade, partId)
                                                                :
                                                                // Fallback to hardcoded grade mapping
                                                                (() => {
                                                                    const gradeMap: { [key: string]: string } = {

                                                                    };
                                                                    return gradeMap[initialMarks[student.id].grade] || initialMarks[student.id].grade;
                                                                })()
                                                            )
                                                            : "Unset"
                                                        }
                                                    </Box>
                                                )}
                                            </TableCell>
                                        )}
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </TableContainer>
                    </Box>
                </Grow>
                </div>
            </Fade>

            {/* Save button - only show if onSave is provided and there are editable fields - improved with debugging class */}
            {!isSummaryView && onSave && (
                partGuiConfig.gradeCol === "EDITABLE" ||
                partGuiConfig.scoreCol === "EDITABLE" ||
                partGuiConfig.unitCriteria === "EDITABLE"
            ) && (
                <Box sx={{mt: '1rem', display: 'flex', justifyContent: 'center'}}> <Button
                    variant="contained"
                    color={saveStatus === 'saved' ? "success" : "primary"}
                    onClick={handleSave}
                    disabled={saveStatus === 'saving' || isReloading || !hasChanges}
                    sx={{
                        minWidth: '12rem',
                        fontSize: '1.15rem',
                        textTransform: 'none'
                    }}
                    className="pt-save-button"
                >
                    {saveStatus === 'idle' && (hasChanges ? 'Save Changes' : 'No Changes')}
                    {saveStatus === 'saving' && 'Saving...'}
                    {saveStatus === 'saved' && !isReloading && '✓ Saved'}
                    {saveStatus === 'saved' && isReloading && 'Reloading...'}
                    {saveStatus === 'error' && 'Try Again'}
                </Button>
                </Box>
            )}
        </div>
    );
};
