import React, {useEffect, useState} from "react";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import {
    TableContainer,
    Table,
    TableHead,
    TableBody,
    TableRow,
    TableCell,
    Paper,
    Box,
    Grid,
    Collapse,
    Typography,
    IconButton,
    Button,
    CircularProgress,
    Dialog, DialogActions, DialogContent, DialogTitle
} from "@mui/material";

//todo pt item to update the title so the font / styling matches CEDAR's usual styling
export const studentSummary = ({baseUrl, displayName, referenceId, studentId}: {
  baseUrl: string,
  displayName: string,
  referenceId: string,
  studentId: number
}) => {
  const [openStates, setOpenStates] = useState<Record<number, boolean>>({});
  const [qualificationData, setQualificationData] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [qualificationNames, setQualificationNames] = useState<string[]>([]);
  const [modules, setModules] = useState<string[]>([]);
  const [units, setUnits] = useState<string[]>([]);
  const [hasError, setHasError] = useState<boolean>(false);
  const [selectedAssignment, setSelectedAssignment] = useState(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedCriteria, setSelectedCriteria] = useState(null); // New state for selected criteria
  const [criteriaDialogOpen, setCriteriaDialogOpen] = useState(false); // New state for criteria dialog

  const handleDialogOpen = (assignment) => {
    setSelectedAssignment(assignment);
    setDialogOpen(true);
  };
  const handleDialogClose = () => {
    setDialogOpen(false);
    setSelectedAssignment(null);
  };

  const handleCriteriaDialogOpen = (criteria) => {
    setSelectedCriteria(criteria);
    setCriteriaDialogOpen(true);
  };
  const handleCriteriaDialogClose = () => {
    setCriteriaDialogOpen(false);
    setSelectedCriteria(null);
  };

  useEffect(() => {
    setLoading(true);
    fetch( `${baseUrl}student/${studentId}/summary`, {
      method: 'GET',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
      }
    })
    .then((resp) => resp.json())
      .then((respJSON) => {
        console.log(respJSON);
      if (respJSON?.status === 'error') {
        console.log(respJSON.message);
        return;
    }
  
    const formattedData = Object.entries(respJSON).map(([qualificationName, parts]: [string, any[]]) => {
      return parts.map((unit) => {
        const assessments = unit.children || [];

        let assignmentsCompleted = 0;
        let criteriaPassed = 0;

        const assignmentsDetails = assessments.map((a) => {
          const isCompleted = !!a.grade || !!a.score;
          if (isCompleted) assignmentsCompleted++;

          return {
            name: a.partName,
            grade: a.grade ?? "Incomplete",
            score: a.score ?? "N/A",
            completed: isCompleted
          };
        });

        const criteriaDetails = assessments.flatMap((a) =>
          a.children?.map((c) => {
            const isPassed = !!c.grade || !!c.score;
            if (isPassed) criteriaPassed++;

            return {
              name: c.partName || c.criteria || "Unnamed Criteria",
              grade: c.grade ?? "",
              score: c.score ?? "",
              passed: isPassed
            };
          }) || []
        );

        return {
          id: unit.id,
          module: unit.module,
          unit: unit.partName,
          name: qualificationName,
          totalAssignments: assessments.length,
          assignmentsCompleted,
          totalCriteria: criteriaDetails.length,
          criteriaPassed,
          assignmentsStatus: assignmentsDetails,
          criteriaStatus: criteriaDetails,
          grade: unit.grade ?? "", // Show unit grade if available
          points: unit.score ?? ""
        };
      });
    });

      setQualificationData(formattedData);
      setOpenStates({ 0: true });
      setLoading(false);

      const nameSet = new Set();
      const moduleSet = new Set();
      const unitSet = new Set();

      formattedData.flat().forEach((item) => {
        nameSet.add(item.name);
        moduleSet.add(item.module);
        unitSet.add(item.unit);
      });

      setQualificationNames(Array.from(nameSet));
      setModules(Array.from(moduleSet));
      setUnits(Array.from(unitSet));
    }).catch((error) => {
      console.error(error);
      setHasError(true); // set error flag to true
      setLoading(false); // also stop loading
    });
  }, []);

return (
  <Box sx={{ padding: 2 }}>

    {loading ? (
      <Box display="flex" justifyContent="center" py={4}>
        <CircularProgress />
      </Box>
    ) : hasError ? (
      <Box display="flex" justifyContent="center">
        <Typography variant="div" sx={{background: "url(../Static/Icons/ui/ux2/appbar-alert.png) 0px -3px no-repeat", backgroundSize: "contain", display:"inline-block", backgroundColor: "var(--red)", color: "#ffffff", padding: "0.9em 1.5em 0.9em 3em", borderRadius: "0.25em", fontSize: "1em"}}>
        Failed to load qualification data
          </Typography>
      </Box>
      ) : !qualificationData || qualificationData.length === 0 ? (
      <Box display="flex" justifyContent="center">
      <Typography variant="div" sx={{background: "url(../Static/Icons/ui/ux2/appbar-alert.png) 0px -3px no-repeat", backgroundSize: "contain", display:"inline-block", backgroundColor: "var(--red)", color: "#ffffff", padding: "0.9em 1.5em 0.9em 3em", borderRadius: "0.25em", fontSize: "1em"}}>
        No qualification data is available for the student
            </Typography>
      </Box>
    ) : (
      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: "300px 1fr",
          gap: 3,
          alignItems: "flex-start",
          "@media (max-width: 900px)": {
            display: "block",
          }
        }}
      >
        {/* Overview Panel */}
        <Paper sx={{ padding: 2 }}>
          <Typography variant="h4" sx={{ color: "#067a40" }}>
            Overview
          </Typography>

          {modules.length > 0 && (
            <>
              <Typography variant="h5">Modules</Typography>
              <ul style={{ fontFamily: 'Roboto, Helvetica, Arial, sans-serif', lineHeight: "22px" }}>
                {modules.map((module) => (
                  <li key={module}>{module}</li>
                ))}
              </ul>
            </>
          )}

          {qualificationNames.length > 0 && (
            <>
              <Typography variant="h5">Qualifications</Typography>
              <ul style={{ fontFamily: 'Roboto, Helvetica, Arial, sans-serif', lineHeight: "22px" }}>
                {qualificationNames.map((name) => (
                  <li key={name}>{name}</li>
                ))}
              </ul>
            </>
          )}

          {units.length > 0 && (
            <>
              <Typography variant="h5">Units</Typography>
              <ul style={{ fontFamily: 'Roboto, Helvetica, Arial, sans-serif', lineHeight: "22px" }}>
                {units.map((unit) => (
                  <li key={unit}>{unit}</li>
                ))}
              </ul>
            </>
          )}
        </Paper>

        {/* Qualifications Table */}
        <Box>
          {qualificationData.map((qualification, index) => {
            const qualificationName = qualification[0]?.name || `Qualification ${index + 1}`;
            const isOpen = openStates[index] || false;
            return (
              <Grid item xs={12} sx={{ mb: 2, pt: 2 }} key={qualificationName}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                  <Typography variant="h4" sx={{ color: "var(--green)" }}>
                    {qualificationName} Summary
                  </Typography>
                  <IconButton
                    onClick={() =>
                      setOpenStates((prev) => ({
                        ...prev,
                        [index]: !prev[index],
                      }))
                    }
                    size="small" title={isOpen ? "Collapse" : "Expand"}
                  >
                    {isOpen ? <ExpandLessIcon /> : <ExpandMoreIcon />}
                  </IconButton>
                </Box>
                <Collapse in={isOpen}>
                  <Paper sx={{width: "100%", mt: 1 }}>
                    <TableContainer component={Paper} sx={{ mb: 2, maxHeight: 300, overflow: "auto" }}>
                      <Table stickyHeader>
                        <TableHead>
                          <TableRow>
                            <TableCell>Module</TableCell>
                            <TableCell>Unit</TableCell>
                            <TableCell>Assignments</TableCell>
                            <TableCell>Criteria</TableCell>
                            <TableCell>Grade</TableCell>
                            <TableCell>Points</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {qualification.map((qual: any) => (
                            <TableRow key={qual.id}>
                              <TableCell>{qual.module}</TableCell>
                              <TableCell>
                                  {qual.unit ?? ""}
                              </TableCell>
                              <TableCell sx={{ textAlign: "center" }}>
                                  <span style={{ color: "var(--green)", cursor: "pointer" , textDecoration: "underline"}} onClick={() => handleDialogOpen(qual)}>
                                    {qual.totalAssignments ? `${qual.assignmentsCompleted}/${qual.totalAssignments}` : ""}
                                  </span>
                              </TableCell>
                              <TableCell sx={{ textAlign: "center" }}>
                                  <span style={{ color: "var(--green)", cursor: "pointer", textDecoration: "underline"}} onClick={() => handleCriteriaDialogOpen(qual)}>
                                    {qual.totalCriteria ? `${qual.criteriaPassed}/${qual.totalCriteria}` : ""}
                                  </span>
                              </TableCell>
                              <TableCell sx={{ textAlign: "center" }}>{qual.grade}</TableCell>
                              <TableCell sx = {{textAlign: "center"}}>{qual.points}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </Paper>
                </Collapse>
              </Grid>
            );
          })}
        </Box>
      </Box>
    )}

      <Dialog open={dialogOpen} onClose={handleDialogClose} maxWidth="sm">
        <DialogTitle sx={{ height: '40px', backgroundColor: "var(--green)", color: "white", fontSize: "16px", padding: "8px 16px" }}>
          Assignment Details
        </DialogTitle>
        <DialogContent sx={{ backgroundColor: "var(--ui-white)", padding: "8px 16px" }}>
          <Table sx={{marginTop: "10px"}}>
            <TableHead>
              <TableRow>
                <TableCell><strong>Assignment</strong></TableCell>
                <TableCell><strong>Status</strong></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {selectedAssignment?.assignmentsStatus?.map((assignment, idx) => (
                <TableRow key={idx}>
                  <TableCell>{assignment.name}</TableCell>
                  <TableCell sx={{ textAlign: "center" }}>{assignment.grade ? assignment.grade : "Incomplete"}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </DialogContent>
        <DialogActions sx={{ padding: "8px 16px" }}>
          <Button onClick={handleDialogClose} sx={{color:"var(--green)",backgroundColor:"var(--ui-white)",textTransform: "none",'&:hover': {backgroundColor: "var(--green)",color: "var(--ui-white)" }}}>
            Close
          </Button>
        </DialogActions>
      </Dialog>
    
      <Dialog open={criteriaDialogOpen} onClose={handleCriteriaDialogClose} maxWidth="sm">
        <DialogTitle sx={{ height: '40px', backgroundColor: "var(--green)", color: "white", fontSize: "16px", padding: "8px 16px" }}>
          Criteria Details
        </DialogTitle>
        <DialogContent sx={{ backgroundColor: "var(--ui-white)", padding: "8px 16px" }}>
        <Table sx={{marginTop: "10px"}}>
            <TableHead>
              <TableRow>
                <TableCell><strong>Criteria</strong></TableCell>
                <TableCell><strong>Grade</strong></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {selectedCriteria?.criteriaStatus?.map((criteria, idx) => (
                <TableRow key={idx}>
                  <TableCell>{criteria.name}</TableCell>
                  <TableCell sx={{ textAlign: "center" }}>{criteria.grade ? criteria.grade : ""}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </DialogContent>
        <DialogActions sx={{ padding: "8px 16px" }}>
          <Button onClick={handleCriteriaDialogClose} sx={{color: "var(--green)",backgroundColor:"var(--ui-white)",textTransform: "none",'&:hover': {backgroundColor: "var(--green)",color: "var(--ui-white)" }}}>
            Close
          </Button>
        </DialogActions>
      </Dialog>

  </Box>
);
}
