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

export const UnitSummaryStaffView = ({ baseUrl, displayName, referenceId, studentId, unitId, }: {
  baseUrl: string;
  displayName: string;
  referenceId: string;
  studentId: number;
  unitId: number;
}) =>
{
  const [summaryData, setSummaryData] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasError, setHasError] = useState<boolean>(false);

  useEffect(() =>
  {
    setLoading(true);
    const params = new URLSearchParams();
    params.set("id", studentId.toString());
    params.set("unit", unitId.toString());
    fetch(`${baseUrl}students/${studentId}/UnitSummary?${params}`, {
      method: "GET",
      headers: {
        "X-Requested-With": "XMLHttpRequest",
        "Content-Type": "application/json",
      },
    })
      .then((resp) => resp.json())
      .then((respJSON) =>
      {
        if (respJSON?.status === "error")
        {
          console.log(respJSON.message);
          setHasError(true);
        } else
        {
          setSummaryData(respJSON);
        }
        setLoading(false);
      })
      .catch((error) =>
      {
        console.error(error);
        setHasError(true);
        setLoading(false);
      });
  }, [baseUrl, studentId, unitId]);

  const isEmptyData = !summaryData || Object.keys(summaryData).length === 0;

  if (loading)
  {
    return (
      <Box display="flex" justifyContent="center" p={4}>
        <CircularProgress />
      </Box>
    );
  }

  if (isEmptyData)
  {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100%', marginTop: '1em' }}>
        <Typography
          color="error"
          variant="h6"
          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.6em 1.5em 0.6em 3em",
            borderRadius: "0.25em",
            fontSize: "1em",
          }}
        >
          No qualification data is available for the student.
        </Typography>
      </Box>
    );
  }
  if (hasError)
  {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100%', marginTop: '1em' }}>
        <Typography
          color="error"
          variant="h6"
          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.6em 1.5em 0.6em 3em",
            borderRadius: "0.25em",
            fontSize: "1em",
          }}
        >
          Failed to load qualification data
        </Typography>
      </Box>
    );
  }


  return (
    <Box sx={{ padding: 2 }}>
      <Typography variant="h3" gutterBottom>
        Progress Tracker Summary - {summaryData.unit} Details for {displayName}
      </Typography>
      <Grid container spacing={2}>
        {/* Left Vertical Panel */}
        <Grid item xs={12} md={3}>
          <Paper sx={{ padding: 2, height: "100%" }}>
            <Typography
              component="div"
              sx={{
                color: "var(--green)",
                fontWeight: 500,
                fontSize: "1.25rem",
                lineHeight: 1.6,
              }}
            >
              Criteria Summary
            </Typography>
            <Typography>Number of Criteria: {summaryData.criteriaCount}</Typography>
            <Typography>Number of Criteria Met: {summaryData.criteriaMet}</Typography>
            <Typography>Number of Criteria Not Met: {summaryData.criteriaNotMet}</Typography>
            <Typography>Target Grade: {summaryData.TargetGrade}</Typography>
          </Paper>
        </Grid>

        {/* Right Section: Overview & Statistics */}
        <Grid item xs={12} md={9}>
          <Grid container spacing={2}>
            {/* Overview */}
            <Grid item xs={6}>
              <Paper sx={{ padding: 2 }}>
                <Typography
                  component="div"
                  sx={{
                    color: "var(--green)",
                    fontWeight: 500,
                    fontSize: "1.25rem",
                    lineHeight: 1.6,
                  }}
                >
                  Overview
                </Typography>
                <Typography>Module: {summaryData.module}</Typography>
                <Typography>Unit: {summaryData.unit}</Typography>
                <Typography>Assignments: {summaryData.assignmentCount}</Typography>
              </Paper>
            </Grid>

            {/* Statistics */}
            <Grid item xs={6}>
              <Paper sx={{ padding: 2 }}>
                {
              /* TODO pt-grading: These statistics are hardcoded to Pass/Merit/Distinction/Fail
                      but should be dynamic based on the actual grade schemes used.
                      This requires backend changes to calculate statistics dynamically. */}
                <Typography variant="div" sx={{ color: "var(--green)", fontWeight: 500, fontSize: "1.25rem", lineHeight: 1.6 }}>Statistics</Typography>
                <Box sx={{ backgroundColor: '#067A40', padding: 1, marginBottom: 1, color: '#fff', fontFamily: 'Roboto, Helvetica, Arial, sans-serif' }}>
                  Distinction Total: {summaryData.distinctionTotal}
                </Box>
                <Box sx={{ backgroundColor: 'var(--purple)', padding: 1, marginBottom: 1, color: '#fff', fontFamily: 'Roboto, Helvetica, Arial, sans-serif' }}>
                  Merit Total: {summaryData.meritTotal}
                </Box>
                <Box sx={{ backgroundColor: 'var(--yellow)', padding: 1, marginBottom: 1, fontFamily: 'Roboto, Helvetica, Arial, sans-serif' }}>
                  Pass Total: {summaryData.passTotal}
                </Box>
                <Box sx={{ backgroundColor: 'var(--red)', padding: 1, marginBottom: 1, color: '#fff', fontFamily: 'Roboto, Helvetica, Arial, sans-serif' }}>
                  Fail Total: {summaryData.failTotal}
                </Box>
              </Paper>
            </Grid>

            {/* Result Summary */}
            <Grid item xs={12}>
              <Paper sx={{ padding: 2 }}>
                <Typography
                  component="div"
                  sx={{
                    color: "var(--green)",
                    fontWeight: 500,
                    fontSize: "1.25rem",
                    lineHeight: 1.6,
                  }}
                >
                  Result Summary
                </Typography>
                <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                  <Typography>
                    Total Points for {summaryData.unit}: {summaryData.totalPoints}
                  </Typography>
                </Box>
              </Paper>
            </Grid>

            {/* Assignments Table */}
            <Grid item xs={12} sx={{ height: "400px", overflow: "hidden" }}>
              <Paper sx={{ width: "100%", padding: 2 }}>
                <Typography
                  component="div"
                  sx={{
                    color: "var(--green)",
                    fontWeight: 500,
                    fontSize: "1.25rem",
                    lineHeight: 1.6,
                  }}
                >
                  Assignments
                </Typography>
                <TableContainer
                  component={Paper}
                  sx={{ mb: 2, maxHeight: 300, overflow: "auto" }}
                >
                  <Table stickyHeader>
                    <TableHead>
                      <TableRow>
                        <TableCell>Grade</TableCell>
                        <TableCell>Points</TableCell>
                        <TableCell>Assignment</TableCell>
                        <TableCell>P1</TableCell>
                        <TableCell>P2</TableCell>
                        <TableCell>P3</TableCell>
                        <TableCell>P4</TableCell>
                        <TableCell>P5</TableCell>
                        <TableCell>D1</TableCell>
                        <TableCell>D2</TableCell>
                        <TableCell>D3</TableCell>
                        <TableCell>D4</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {summaryData.assignments &&
                        summaryData.assignments.map((assignment: any) => (
                          <TableRow key={assignment.id}>
                            <TableCell>{assignment.grade}</TableCell>
                            <TableCell sx={{ textAlign: "center" }}>{assignment.points}</TableCell>
                            <TableCell>{assignment.assignment}</TableCell>
                            <TableCell>{assignment.p1}</TableCell>
                            <TableCell>{assignment.p2}</TableCell>
                            <TableCell>{assignment.p3}</TableCell>
                            <TableCell>{assignment.p4}</TableCell>
                            <TableCell>{assignment.p5}</TableCell>
                            <TableCell>{assignment.d1}</TableCell>
                            <TableCell>{assignment.d2}</TableCell>
                            <TableCell>{assignment.d3}</TableCell>
                            <TableCell>{assignment.d4}</TableCell>
                          </TableRow>
                        ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Paper>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
};
