import {
    Box,
    Typography,
    Paper,
    Table,
    TableHead,
    TableBody,
    TableRow,
    TableCell,
    TableContainer,
    CircularProgress,
    Alert
} from "@mui/material";
import React, {useEffect, useState} from "react";
import MermaidDiagram from "../../MermaidDiagram.js";

type RespData = {
    qualification: any;
    data: any
}

type ShowMessage = {
    message: string;
    severity: 'success' | 'error';
};

const QualificationDetails = ({baseUrl, qualificationId, trackerId, getMessageIcon}: {
    baseUrl: string,
    qualificationId: number | null,
    trackerId: number | null,
    getMessageIcon: any
}) => {
    const [loader, setLoader] = useState<boolean>(false);
    const [respData, setRespData] = useState<RespData | null>(null);
    const [hasUnits, setHasUnits] = useState<boolean>(false);

    const [showMessage, setShowMessage] = useState<ShowMessage>({'message': '', 'severity': 'success'});

    useEffect(() => {
        setLoader(true);
        let apiUrl = `${baseUrl}pt/qualifications/${qualificationId}/details`;
        if (trackerId) {
            apiUrl = `${baseUrl}pt/trackers/${trackerId}/details?qualificationId=${qualificationId}`;
        }

        fetch(apiUrl, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json'
            }
        })
            .then((resp) => {
                if(resp?.status === 200 && resp?.redirected) {
                    window.location.reload();
                    return null;
                }

                return resp.json();
            })
            .then((respJSON) => {
                if(respJSON === null) {
                    return;
                }

                if (respJSON?.status === 'error') {
                    console.log(respJSON.message);
                    return;
                }

                setRespData(respJSON);
                setHasUnits(respJSON.data?.some((row: any) => row.UnitName != null));
                setLoader(false);
            }).catch((error) => {
            setShowMessage({
                message: 'Failed to load qualification details',
                severity: 'error'
            });
            console.error(error);
        });
    }, []);

    return (
        <>
            <Box sx={{flexGrow: 1}}>
                {showMessage && showMessage.message && (
                    <Box sx={{textAlign: 'center', mb: 1}}>
                        <Alert
                            icon={getMessageIcon(showMessage.severity)}
                            variant="filled"
                            severity={showMessage.severity}
                            sx={{
                                display: 'inline-flex',  // fits content only
                                alignItems: 'center',    // vertically centers icon + text
                                px: 2,                   // padding X if you want more space
                                py: 1,                   // padding Y
                            }}
                        >
                            {showMessage.message}
                        </Alert>
                    </Box>
                )}
                {loader
                    ? <Box display="flex" justifyContent="center" p={2}>
                        <CircularProgress/>
                    </Box>
                    : (respData &&
                        <>
                            <Typography variant="h5" color="textSecondary">
                                {respData?.qualification?.part?.name}
                            </Typography>
                            <Typography variant="body1" component="div">
                                Type: {respData?.qualification?.type || 'None Recorded'}
                            </Typography>
                            <Typography variant="body1" component="div">
                                Reference: {respData?.qualification?.part?.reference || 'None Recorded'}
                            </Typography>
                            <Typography variant="body1" component="div">
                                Provider: {respData?.qualification?.awardingBody || 'None Recorded'}
                            </Typography>
                            <Typography variant="body1" component="div" sx={{mb: 1}}>
                                Module: {respData?.qualification?.modules || 'None Recorded'}
                            </Typography>

                            <TableContainer component={Paper} tabIndex={0}
                                            sx={{mb: 2, maxHeight: 200, overflow: "auto"}}>
                                <Table stickyHeader>
                                    <TableHead>
                                        <TableRow>
                                            {hasUnits && <TableCell>Unit</TableCell>}
                                            <TableCell>Assignment</TableCell>
                                            <TableCell>Criteria</TableCell>
                                        </TableRow>
                                    </TableHead>
                                    <TableBody>
                                        {respData.data.length > 0
                                            ? respData.data.map(
                                                (row: any, idx: number) => (
                                                    <TableRow key={idx}>
                                                        {hasUnits && <TableCell>{row.UnitName}</TableCell>}
                                                        <TableCell>
                                                            <Typography variant="body1">{row.AssignmentName}</Typography>
                                                            {row?.AssignmentRule && (
                                                                <Typography variant="body1" sx={{ color: 'text.secondary' }}>
                                                                    Rule: {row.AssignmentRule}
                                                                </Typography>
                                                            )}
                                                        </TableCell>
                                                        <TableCell>
                                                            {row.CriteriaNames?.split(',').map((criteria: string, cIdx: number) => (
                                                                <Typography key={cIdx} variant="body2" component="div">
                                                                    {criteria.trim()}
                                                                </Typography>
                                                            ))}
                                                        </TableCell>
                                                    </TableRow>
                                                ))
                                            : <TableRow>
                                                <TableCell colSpan={hasUnits ? 3 : 2}>
                                                    No records found.
                                                </TableCell>
                                            </TableRow>
                                        }
                                    </TableBody>
                                </Table>
                            </TableContainer>

                            {qualificationId && (
                                <MermaidDiagram
                                    src={`${baseUrl}pt/qualifications/${qualificationId}/diagram`}
                                    title="Qualification Structure"
                                />
                            )}
                        </>
                    )
                }
            </Box>
        </>
    );
}

export default QualificationDetails;
