import React, {useEffect, useRef, useState} from "react";
import {
    Alert,
    Box,
    Button,
    CircularProgress, Divider,
    Paper,
    Stack,
    Table,
    TableBody, TableCell, TableHead,
    TableRow, TableSortLabel,
    Typography
} from "@mui/material";
import {useReactToPrint} from "react-to-print";
import getIconComponent from "../Common/CustomSortIcon";

declare global {
    interface Window {
        $: any; // jQuery
    }
}

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

type Program = {
    code: null | string,
    module: string,
    start: string,
    end: string,
    core: string,
    learningHours: null,
    otherHours: null
}

type StudentData = {
    institution: string;
    acYear: string;
    stuReference: string;
    stuName: string;
    stuTutGroup: string | null;
    stuAddress: string;
    stuPostcode: string;
    stuHomeNum: string;
    stuMobileNum: string;
    stuGender: string;
    stuEthnicity: string | null;
    stuReligion: string;
    stuDOB: string;
    stuYearOfEnrolment: string;
    ageDate: string;
    stuResidencyStatus: null | number,
    stuResidencyNotes: null | string,
    title: string,
    programme: Program[],
    stuAge: number | null,
    hours?: {
        plannedLearningHours: number,
        plannedOtherHours: number,
        totalHoursYear: number
    }
}

type RespData = {
    adminSignature: null | string;
    adminSignatureDate: null | string;
    id: number;
    objectedDate: null | number;
    objectionText: null | string;
    retractedDate: null | number;
    statementHtml: string;
    status: string;
    studentDataJson: StudentData;
    studentId: number;
    studentSignature: null | string;
    studentSignatureDate: null | string;
    tutorId: null | number;
    tutorSignature: null | string;
    tutorSignatureDate: null | string;
}

const AgreementView = ({baseUrl, getMessageIcon, ldaId, studentId}: {
    baseUrl: string,
    getMessageIcon: any,
    ldaId: number | null,
    studentId: number | null
}) => {
    const [loader, setLoader] = useState(true);
    const [respData, setRespData] = useState<RespData>();
    const [studentData, setStudentData] = useState<StudentData>();
    const [programs, setPrograms] = useState([]);
    const [sortBy, setSortBy] = useState('');
    const [sortDirection, setSortDirection] = useState<"asc" | "desc">('asc');
    const [studentSigImg, setStudentSigImg] = useState<string | null>(null);
    const [staffSigImg, setStaffSigImg] = useState<string | null>(null);
    const [adminSigImg, setAdminSigImg] = useState<string | null>(null);

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

    const printComponentRef = useRef<HTMLDivElement>(null);
    const reactToPrint = useReactToPrint({contentRef: printComponentRef});

    const convertBase30ToImage = (base30: string): Promise<string | null> => {
        return new Promise((resolve) => {
            const tempDiv = document.createElement('div');
            document.body.appendChild(tempDiv); // Attach to DOM so jSignature can render

            const $sig = window.$(tempDiv).jSignature();
            $sig.jSignature('setData', base30, 'base30');

            // Wait for rendering to complete
            setTimeout(() => {
                try {
                    const imageData = $sig.jSignature('getData', 'svgbase64');
                    if (
                        Array.isArray(imageData) &&
                        typeof imageData[0] === 'string' &&
                        typeof imageData[1] === 'string'
                    ) {
                        const mimeType = imageData[0]; // e.g. "image/png;base64"
                        const base64 = imageData[1];
                        const dataUrl = `data:${mimeType},${base64}`;
                        resolve(dataUrl);
                    } else {
                        console.warn('Unexpected imageData format:', imageData);
                        resolve(null);
                    }

                } catch (err) {
                    console.error('Error converting base30 to image:', err);
                    resolve(null);
                } finally {
                    document.body.removeChild(tempDiv); // Clean up
                }
            }, 100); // 100ms delay to allow rendering
        });
    };

    const handleSort = (column: string, direction: 'asc' | 'desc') => {
        if (column === sortBy) {
            direction = direction === 'asc' ? 'desc' : 'asc';
            setSortDirection(direction);
        } else {
            setSortBy(column);
            setSortDirection('asc');
        }

        const parseDDMMYYYY = (dateStr: string): number => {
            const [day, month, year] = dateStr.split('-').map(Number);
            return new Date(year, month - 1, day).getTime(); // month is 0-indexed
        };

        const sortedPrograms = [...programs].sort((a: any, b: any) => {
            const aValue = a[column];
            const bValue = b[column];

            if (aValue === null || bValue === null) return 0;

            if (typeof aValue === 'string' && typeof bValue === 'string') {

                if (['start', 'end'].includes(column)) {
                    const aDate = parseDDMMYYYY(aValue);
                    const bDate = parseDDMMYYYY(bValue);

                    // If both are valid dates
                    if (!isNaN(aDate) && !isNaN(bDate)) {
                        return direction === 'asc' ? aDate - bDate : bDate - aDate;
                    }
                }

                return direction === 'asc'
                    ? aValue.localeCompare(bValue)
                    : bValue.localeCompare(aValue);
            }

            return 0;
        });

        setPrograms(sortedPrograms);
    }

    useEffect(() => {
        if (!respData) return;

        const convertAll = async () => {
            if (respData.studentSignature) {
                const img = await convertBase30ToImage(respData.studentSignature);
                setStudentSigImg(img);
            }
            if (respData.tutorSignature) {
                const img = await convertBase30ToImage(respData.tutorSignature);
                setStaffSigImg(img);
            }
            if (respData.adminSignature) {
                const img = await convertBase30ToImage(respData.adminSignature);
                setAdminSigImg(img);
            }
        };

        convertAll();
    }, [respData]);

    useEffect(() => {
        let apiUrl = `${baseUrl}v1/lda/${ldaId}`;
        if (studentId) {
            apiUrl = `${baseUrl}v1/freshLda/${studentId}`;
        }
        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);
            setStudentData(respJSON?.studentDataJson);
            setPrograms(respJSON?.studentDataJson?.programme);
            setLoader(false);
        }).catch((error) => {
            setShowMessage({
                message: `Failed to load details`,
                severity: 'error'
            });
            setLoader(false);
            console.error(error);
        });
    }, []);

    return (
        <>
            {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>
                : <Box sx={{mx: 'auto', maxWidth: 900}}>
                    <Stack direction="row" justifyContent="space-between" mb={2}>
                        <Button variant="outlined" onClick={() => reactToPrint()}>Print</Button>
                    </Stack>

                    {studentData &&
                        <Box sx={{p: 2, maxWidth: '50em', margin: 'auto'}} ref={printComponentRef}>
                            <Typography variant="h3"
                                        sx={{
                                            fontWeight: 600,
                                            textAlign: "center",
                                            mb: 3,
                                            fontSize: '2.4em'
                                        }}>
                                {`${studentData?.institution} - ${studentData?.title} ${studentData?.acYear}`}
                            </Typography>

                            <Box>
                                <Box mb={3} display="flex" flexWrap="wrap" gap="1em">
                                    <Table size="small" sx={{flex: 1}}>
                                        <TableBody>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Student Reference</TableCell>
                                                <TableCell>{studentData?.stuReference}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Name</TableCell>
                                                <TableCell>{studentData?.stuName}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Tutor Group</TableCell>
                                                <TableCell>{studentData?.stuTutGroup}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Address</TableCell>
                                                <TableCell>{studentData?.stuAddress}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Postcode</TableCell>
                                                <TableCell>{studentData?.stuPostcode}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Home Phone</TableCell>
                                                <TableCell>{studentData?.stuHomeNum}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Mobile Phone</TableCell>
                                                <TableCell>{studentData?.stuMobileNum}</TableCell>
                                            </TableRow>
                                        </TableBody>
                                    </Table>
                                    <Table size="small" sx={{flex: 1}}>
                                        <TableBody>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Sex/Gender</TableCell>
                                                <TableCell>{studentData?.stuGender}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Ethnic Origin</TableCell>
                                                <TableCell>{studentData?.stuEthnicity}</TableCell>
                                            </TableRow>
                                            {studentData?.stuReligion &&
                                                <TableRow>
                                                    <TableCell sx={{fontWeight: 'bold'}}>Religion</TableCell>
                                                    <TableCell>{studentData.stuReligion}</TableCell>
                                                </TableRow>
                                            }
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Date of Birth</TableCell>
                                                <TableCell>{studentData?.stuDOB}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Age
                                                    on {studentData?.ageDate}</TableCell>
                                                <TableCell>{studentData?.stuAge}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Year of Enrolment</TableCell>
                                                <TableCell>{studentData?.stuYearOfEnrolment}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>UK Citizen & Resident 3
                                                    Years</TableCell>
                                                <TableCell>
                                                    {studentData?.stuResidencyStatus === 1
                                                    ? 'Yes'
                                                    : studentData?.stuResidencyStatus === 0
                                                        ? 'No'
                                                        : 'No Data'}
                                                </TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Residency Notes</TableCell>
                                                <TableCell>{studentData?.stuResidencyNotes || 'None Recorded'}</TableCell>
                                            </TableRow>
                                        </TableBody>
                                    </Table>
                                </Box>

                                <Typography variant="h4"
                                            sx={{
                                                mt: 3,
                                                fontSize: '1.8em'
                                            }}>
                                    {studentData?.acYear} Learner Programme
                                </Typography>
                                <Divider sx={{border: 'none', borderTop: '2px solid #000', margin: '16px 0'}}/>
                                <Box mt={1}>
                                    <Box mb={2}>
                                        <Table size="small">
                                            <TableHead>
                                                <TableRow>
                                                    <TableCell>
                                                        <TableSortLabel
                                                            active={sortBy === 'code'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('code', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'code', sortDirection)}
                                                        >
                                                            Code
                                                        </TableSortLabel>
                                                    </TableCell>
                                                    <TableCell width="35%">
                                                        <TableSortLabel
                                                            active={sortBy === 'module'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('module', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'module', sortDirection)}
                                                        >
                                                            Aims/Qualifications
                                                        </TableSortLabel>
                                                    </TableCell>
                                                    <TableCell>
                                                        <TableSortLabel
                                                            active={sortBy === 'start'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('start', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'start', sortDirection)}
                                                        >
                                                            Start
                                                        </TableSortLabel>
                                                    </TableCell>
                                                    <TableCell>
                                                        <TableSortLabel
                                                            active={sortBy === 'end'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('end', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'end', sortDirection)}
                                                        >
                                                            End
                                                        </TableSortLabel>
                                                    </TableCell>
                                                    <TableCell>
                                                        <TableSortLabel
                                                            active={sortBy === 'core'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('core', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'core', sortDirection)}
                                                        >
                                                            Core Aims
                                                        </TableSortLabel>
                                                    </TableCell>
                                                    <TableCell>
                                                        <TableSortLabel
                                                            active={sortBy === 'learningHours'}
                                                            direction={sortDirection}
                                                            onClick={() => handleSort('learningHours', sortDirection)}
                                                            IconComponent={getIconComponent(sortBy === 'learningHours', sortDirection)}
                                                        >
                                                            Programme Hours
                                                        </TableSortLabel>
                                                    </TableCell>
                                                </TableRow>
                                            </TableHead>
                                            <TableBody>
                                                {programs && programs.map((program: Program, idx: number) =>
                                                    <TableRow key={idx}>
                                                        <TableCell>{program?.code}</TableCell>
                                                        <TableCell>{program?.module}</TableCell>
                                                        <TableCell>{program?.start}</TableCell>
                                                        <TableCell>{program?.end}</TableCell>
                                                        <TableCell>{program?.core}</TableCell>
                                                        <TableCell>{program?.learningHours ?? 0}</TableCell>
                                                    </TableRow>
                                                )}
                                            </TableBody>
                                        </Table>
                                    </Box>

                                    <Table size="small" sx={{width: '70% !important', ml: 'auto'}}>
                                        <TableBody>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Planned Learning Hours</TableCell>
                                                <TableCell>{studentData?.hours?.plannedLearningHours}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Planned Employability, Enrichment
                                                    and Pastoral
                                                    Hours</TableCell>
                                                <TableCell>{studentData?.hours?.plannedOtherHours}</TableCell>
                                            </TableRow>
                                            <TableRow>
                                                <TableCell sx={{fontWeight: 'bold'}}>Total Hours for Year</TableCell>
                                                <TableCell>{studentData?.hours?.totalHoursYear}</TableCell>
                                            </TableRow>
                                        </TableBody>
                                    </Table>
                                </Box>

                                <Typography variant="h4"
                                            sx={{
                                                mt: 3,
                                                fontSize: '1.8em'
                                            }}
                                >Learner Statement</Typography>
                                <Divider sx={{border: 'none', borderTop: '2px solid #000', margin: '16px 0'}}/>

                                <Box dangerouslySetInnerHTML={{__html: respData?.statementHtml ?? ''}}/>

                                {respData?.objectionText && (
                                    <Box mt={1}>
                                        <Typography variant="h4"
                                                    sx={{
                                                        mt: 3,
                                                        fontSize: '1.8em'
                                                    }}
                                        >Objection</Typography>
                                        <Divider sx={{border: 'none', borderTop: '2px solid #000', margin: '16px 0'}}/>
                                        <Typography variant="body1">{respData.objectionText}</Typography>
                                    </Box>
                                )}

                                {(!respData?.objectionText || respData?.objectionText === '') && (
                                    <Box mt={1}>
                                        <Typography variant="h4"
                                                    sx={{
                                                        mt: 3,
                                                        fontSize: '1.8em'
                                                    }}
                                        >Signatures of Confirmation</Typography>
                                        <Divider sx={{border: 'none', borderTop: '2px solid #000', margin: '16px 0'}}/>
                                        {studentId || !studentSigImg ?
                                            <Typography variant="body1">Not signed by student yet</Typography> :
                                            <Box mt={1}>
                                                <Table>
                                                    <TableBody>
                                                        {studentSigImg && (
                                                            <>
                                                                <TableRow>
                                                                    <TableCell>Signed by Student</TableCell>
                                                                    <TableCell>{respData?.studentSignatureDate}</TableCell>
                                                                </TableRow>
                                                                <TableRow>
                                                                    <TableCell>Student Signature</TableCell>
                                                                    <TableCell>
                                                                        <img src={studentSigImg}
                                                                             alt="Student Signature"/>
                                                                    </TableCell>
                                                                </TableRow>
                                                            </>
                                                        )}
                                                        {staffSigImg && (
                                                            <>
                                                                <TableRow>
                                                                    <TableCell>Signed by Staff</TableCell>
                                                                    <TableCell>{respData?.tutorSignatureDate}</TableCell>
                                                                </TableRow>
                                                                <TableRow>
                                                                    <TableCell>Staff Signature</TableCell>
                                                                    <TableCell>
                                                                        <img src={staffSigImg} alt="Student Signature"/>
                                                                    </TableCell>
                                                                </TableRow>
                                                            </>
                                                        )}
                                                        {adminSigImg && (
                                                            <>
                                                                <TableRow>
                                                                    <TableCell>Signed by Admin</TableCell>
                                                                    <TableCell>{respData?.adminSignatureDate}</TableCell>
                                                                </TableRow>
                                                                <TableRow>
                                                                    <TableCell>Admin Signature</TableCell>
                                                                    <TableCell>
                                                                        <img src={adminSigImg} alt="Student Signature"/>
                                                                    </TableCell>
                                                                </TableRow>
                                                            </>
                                                        )}
                                                    </TableBody>
                                                </Table>
                                            </Box>
                                        }
                                    </Box>
                                )}
                            </Box>
                        </Box>
                    }
                </Box>
            }
        </>
    );
}

export default AgreementView;
