import { useState, useEffect } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  Grid,
  Card,
  CardContent,
  IconButton,
  Button,
  Modal,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  Paper,
  Chip,
  Skeleton,
  InputAdornment,
} from "@mui/material";
import { Link, useParams } from "react-router-dom";
import TeacherSidebar from "../../../components/TeacherSidebar/index";
import TeacherHeader from "../../../components/TeacherHeader/index";
import axios from "axios";
import {
  Pencil,
  Trash2,
  Eye,
  BookOpen,
  FileText,
  Video,
  Link as LinkLucide,
  Calendar,
  FolderOpen,
  Save,
  LibraryBig,
} from "lucide-react";

const COVER_BANNER_HEIGHT = 240;

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:5000";

const CLASS_COVER_PLACEHOLDER =
  "data:image/svg+xml," +
  encodeURIComponent(
    '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="300"><rect fill="#e5e7eb" width="100%" height="100%"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#64748b" font-family="system-ui,sans-serif" font-size="16">Class cover</text></svg>'
  );

const fieldSx = {
  "& .MuiOutlinedInput-root": {
    borderRadius: 2,
    bgcolor: "#f8fafc",
    "&:hover fieldset": { borderColor: "rgba(79, 70, 229, 0.35)" },
    "&.Mui-focused fieldset": { borderColor: "rgb(79 70 229)", borderWidth: "1.5px" },
  },
  "& .MuiInputLabel-root.Mui-focused": { color: "rgb(79 70 229)" },
};

const selectSx = {
  borderRadius: 2,
  bgcolor: "#f8fafc",
  "& fieldset": { borderColor: "rgba(15, 23, 42, 0.12)" },
  "&:hover fieldset": { borderColor: "rgba(79, 70, 229, 0.35)" },
  "&.Mui-focused fieldset": { borderColor: "rgb(79 70 229)", borderWidth: "1.5px" },
};

const typeChipColor = (type) => {
  const t = (type || "").toLowerCase();
  if (t === "pdf") return { bg: "rgba(59, 130, 246, 0.12)", color: "rgb(29 78 216)" };
  if (t === "video") return { bg: "rgba(139, 92, 246, 0.12)", color: "rgb(109 40 217)" };
  if (t === "link") return { bg: "rgba(16, 185, 129, 0.12)", color: "rgb(5 122 85)" };
  return { bg: "rgba(100, 116, 139, 0.12)", color: "rgb(71 85 105)" };
};

const ClassMaterials = () => {
  const { classId } = useParams();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [materials, setMaterials] = useState([]);
  const [classData, setClassData] = useState(null);
  const [classes, setClasses] = useState([]);
  const [pageLoading, setPageLoading] = useState(true);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [openEditModal, setOpenEditModal] = useState(false);
  const [selectedMaterial, setSelectedMaterial] = useState(null);
  const [editForm, setEditForm] = useState({
    title: "",
    lessonName: "",
    type: "",
    content: "",
    uploadDate: "",
    classId: "",
    file: null,
  });
  const [openDeleteConfirmModal, setOpenDeleteConfirmModal] = useState(false);
  const [materialIdToDelete, setMaterialIdToDelete] = useState(null);

  const toggleSidebar = () => setIsSidebarCollapsed(!isSidebarCollapsed);

  useEffect(() => {
    const handleResize = () => {
      const mobileView = window.innerWidth <= 768;
      setIsMobile(mobileView);
      setIsSidebarCollapsed(mobileView);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      setPageLoading(true);
      setError(null);
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };

        const { data: classesData } = await axios.get(`${API_BASE}/api/teacher/classes`, config);
        setClasses(classesData);

        const { data: classDataRes } = await axios.get(`${API_BASE}/api/teacher/classes/${classId}`, config);
        setClassData(classDataRes);

        const { data: materialsData } = await axios.get(`${API_BASE}/api/teacher/materials`, config);
        const classMaterials = materialsData.filter((mat) => mat.classId._id.toString() === classId);
        setMaterials(classMaterials);
      } catch (err) {
        setError(err.response?.data?.message || "Failed to load class or materials.");
      } finally {
        setPageLoading(false);
      }
    };
    if (classId) fetchData();
  }, [classId]);

  const handleEditMaterial = (material) => {
    setSelectedMaterial(material);
    setEditForm({
      title: material.title,
      lessonName: material.lessonName,
      type: material.type,
      content: material.content,
      uploadDate: material.uploadDate ? new Date(material.uploadDate).toISOString().split("T")[0] : "",
      classId: material.classId._id,
      file: null,
    });
    setOpenEditModal(true);
  };

  const handleUpdateMaterial = async (e) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);

    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    const config = {
      headers: { Authorization: `Bearer ${userInfo.token}`, "Content-Type": "multipart/form-data" },
    };

    const formData = new FormData();
    formData.append("title", editForm.title);
    formData.append("lessonName", editForm.lessonName);
    formData.append("type", editForm.type);
    formData.append("uploadDate", editForm.uploadDate);
    formData.append("classId", editForm.classId);

    if (editForm.type === "link") {
      formData.append("content", editForm.content);
    } else if (editForm.file) {
      formData.append("file", editForm.file);
    } else {
      formData.append("content", selectedMaterial.content);
    }

    try {
      const { data } = await axios.put(`${API_BASE}/api/teacher/materials/${selectedMaterial._id}`, formData, config);
      setSuccess("Material updated.");
      setMaterials((prev) => prev.map((mat) => (mat._id === data._id ? data : mat)));
      setOpenEditModal(false);
    } catch (err) {
      setError(err.response?.data?.message || "Failed to update material.");
    }
  };

  const handleDeleteMaterial = async () => {
    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
      await axios.delete(`${API_BASE}/api/teacher/materials/${materialIdToDelete}`, config);
      setSuccess("Material deleted.");
      setMaterials((prev) => prev.filter((mat) => mat._id !== materialIdToDelete));
      setOpenDeleteConfirmModal(false);
      setMaterialIdToDelete(null);
    } catch (err) {
      setError(err.response?.data?.message || "Failed to delete material.");
      setOpenDeleteConfirmModal(false);
      setMaterialIdToDelete(null);
    }
  };

  const handleOpenDeleteConfirm = (materialId) => {
    setMaterialIdToDelete(materialId);
    setOpenDeleteConfirmModal(true);
  };

  const handleCloseDeleteConfirm = () => {
    setOpenDeleteConfirmModal(false);
    setMaterialIdToDelete(null);
  };

  const barOffset = isSidebarCollapsed
    ? "ml-[60px] w-[calc(100%-60px)]"
    : "ml-[18%] w-[calc(100%-18%)] md:ml-[250px] md:w-[calc(100%-250px)]";

  useEffect(() => {
    const subject = classData?.subject;
    document.title = subject ? `${subject} materials - Teacher - EduConnect` : "Class materials - Teacher - EduConnect";
  }, [classData]);

  const viewHref = (material) =>
    material.type === "link" ? material.content : `${API_BASE}${material.content}`;

  const modalPaperSx = {
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    width: { xs: "92%", sm: 560 },
    maxWidth: 600,
    maxHeight: "90vh",
    overflowY: "auto",
    borderRadius: 3,
    border: "1px solid rgba(15, 23, 42, 0.08)",
    boxShadow: "0 25px 50px -12px rgba(15, 23, 42, 0.25)",
    p: { xs: 2, sm: 3 },
  };

  return (
    <div className="min-h-screen bg-slate-50">
      <TeacherHeader isSidebarCollapsed={isSidebarCollapsed} toggleSidebar={toggleSidebar} isMobile={isMobile} />

      <div className="flex min-h-screen">
        <div
          className={`fixed left-0 top-0 z-50 h-full border-r border-slate-200/90 bg-white transition-all duration-300 ${
            isSidebarCollapsed ? "w-[60px]" : "w-[18%] md:w-[250px]"
          }`}
        >
          <TeacherSidebar isCollapsed={isSidebarCollapsed} toggleSidebar={toggleSidebar} />
        </div>

        <div
          className={`flex-1 transition-all duration-300 ${isSidebarCollapsed ? "ml-[60px]" : "ml-[18%] md:ml-[250px]"}`}
        >
          <div
            className={`fixed left-0 top-0 z-30 mt-[50px] border-b border-slate-200/80 bg-white/95 px-4 py-3 shadow-sm backdrop-blur-sm transition-all duration-300 md:px-6 ${barOffset}`}
          >
            <Breadcrumbs aria-label="breadcrumb" separator="›" sx={{ "& .MuiBreadcrumbs-separator": { color: "rgb(148 163 184)" } }}>
              <MuiLink component={Link} to="/teacher/dashboard" underline="hover" sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}>
                Dashboard
              </MuiLink>
              <MuiLink component={Link} to="/teacher/classses/view-all" underline="hover" sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}>
                Classes
              </MuiLink>
              <Typography sx={{ color: "rgb(15 23 42)", fontWeight: 600, fontSize: "0.875rem" }}>
                {classData?.subject ? `${classData.subject} · Materials` : "Materials"}
              </Typography>
            </Breadcrumbs>
          </div>

          <div className="mt-[104px] h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <Box sx={{ maxWidth: 1200, mx: "auto" }}>
              {pageLoading ? (
                <>
                  <Skeleton variant="rounded" height={220} sx={{ borderRadius: 3, mb: 3 }} animation="wave" />
                  <Skeleton variant="text" width="40%" height={40} animation="wave" />
                  <Grid container spacing={2} sx={{ mt: 1 }}>
                    {[1, 2, 3].map((i) => (
                      <Grid item xs={12} md={6} lg={4} key={i}>
                        <Skeleton variant="rounded" height={180} sx={{ borderRadius: 3 }} animation="wave" />
                      </Grid>
                    ))}
                  </Grid>
                </>
              ) : (
                <>
                  <Box
                    sx={{
                      mb: 3,
                      borderRadius: 3,
                      overflow: "hidden",
                      border: "1px solid rgba(15, 23, 42, 0.08)",
                      boxShadow: "0 4px 20px rgba(15, 23, 42, 0.06)",
                    }}
                  >
                    <img
                      src={classData?.coverPhoto ? `${API_BASE}${classData.coverPhoto}` : CLASS_COVER_PLACEHOLDER}
                      alt={classData ? `${classData.subject} cover` : "Class cover"}
                      style={{ width: "100%", height: COVER_BANNER_HEIGHT, objectFit: "cover", display: "block" }}
                    />
                  </Box>
                  <Box sx={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 2, mb: 3 }}>
                    <Typography
                      variant="h4"
                      sx={{
                        fontWeight: 700,
                        letterSpacing: "-0.02em",
                        color: "rgb(15 23 42)",
                        display: "flex",
                        alignItems: "center",
                        gap: 1.5,
                        fontSize: { xs: "1.35rem", md: "1.75rem" },
                      }}
                    >
                      <LibraryBig size={30} strokeWidth={1.75} className="text-indigo-600 shrink-0" />
                      {classData ? `Materials · ${classData.subject}` : "Class materials"}
                    </Typography>
                    <Button
                      component={Link}
                      to="/teacher/classes/uploadmaterials"
                      variant="contained"
                      disableElevation
                      size="medium"
                      sx={{
                        ml: { xs: 0, sm: "auto" },
                        textTransform: "none",
                        fontWeight: 600,
                        borderRadius: 2,
                        bgcolor: "rgb(79 70 229)",
                        "&:hover": { bgcolor: "rgb(67 56 202)" },
                      }}
                    >
                      Upload materials
                    </Button>
                  </Box>

                  {(error || success) && (
                    <Alert
                      severity={error ? "error" : "success"}
                      onClose={() => {
                        setError(null);
                        setSuccess(null);
                      }}
                      sx={{ mb: 2, borderRadius: 2 }}
                    >
                      {error || success}
                    </Alert>
                  )}

                  {materials.length === 0 ? (
                    <Paper
                      elevation={0}
                      sx={{
                        py: 6,
                        px: 3,
                        textAlign: "center",
                        borderRadius: 3,
                        border: "1px dashed rgba(148, 163, 184, 0.7)",
                        bgcolor: "#fff",
                      }}
                    >
                      <BookOpen size={48} strokeWidth={1.25} className="mx-auto mb-2 text-slate-300" />
                      <Typography sx={{ fontWeight: 700, color: "rgb(15 23 42)", mb: 1 }}>No materials yet</Typography>
                      <Typography sx={{ color: "rgb(100 116 139)", mb: 2, maxWidth: 400, mx: "auto" }}>
                        Upload PDFs, videos, or links so students can access them from this class.
                      </Typography>
                      <Button component={Link} to="/teacher/classes/uploadmaterials" variant="outlined" sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2 }}>
                        Go to upload
                      </Button>
                    </Paper>
                  ) : (
                    <Grid container spacing={2.5}>
                      {materials.map((material) => {
                        const chip = typeChipColor(material.type);
                        return (
                          <Grid item xs={12} sm={6} lg={4} key={material._id}>
                            <Card
                              elevation={0}
                              sx={{
                                height: "100%",
                                borderRadius: 3,
                                border: "1px solid rgba(15, 23, 42, 0.08)",
                                boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                                transition: "box-shadow 0.2s ease, transform 0.2s ease",
                                "&:hover": {
                                  boxShadow: "0 8px 24px rgba(15, 23, 42, 0.08)",
                                },
                              }}
                            >
                              <CardContent sx={{ p: 2.5, "&:last-child": { pb: 2.5 } }}>
                                <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)", mb: 1, fontSize: "1.05rem" }}>
                                  {material.title}
                                </Typography>
                                <Typography variant="body2" sx={{ color: "rgb(100 116 139)", mb: 1.5 }}>
                                  Lesson: {material.lessonName}
                                </Typography>
                                <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1, mb: 1.5 }}>
                                  <Chip
                                    label={(material.type || "").toUpperCase()}
                                    size="small"
                                    sx={{ fontWeight: 700, fontSize: "0.7rem", bgcolor: chip.bg, color: chip.color }}
                                  />
                                  <Typography variant="caption" sx={{ color: "rgb(148 163 184)", alignSelf: "center" }}>
                                    {material.uploadDate ? new Date(material.uploadDate).toLocaleDateString() : "—"}
                                  </Typography>
                                </Box>
                                <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1, mt: 2 }}>
                                  <Button
                                    component="a"
                                    href={viewHref(material)}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    variant="outlined"
                                    size="small"
                                    startIcon={<Eye size={16} strokeWidth={1.75} />}
                                    sx={{
                                      textTransform: "none",
                                      fontWeight: 600,
                                      borderRadius: 2,
                                      borderWidth: 1.5,
                                      borderColor: "rgba(79, 70, 229, 0.35)",
                                      color: "rgb(79 70 229)",
                                    }}
                                  >
                                    View
                                  </Button>
                                  <IconButton
                                    onClick={() => handleEditMaterial(material)}
                                    aria-label="Edit material"
                                    sx={{
                                      color: "rgb(79 70 229)",
                                      bgcolor: "rgba(79, 70, 229, 0.08)",
                                      "&:hover": { bgcolor: "rgba(79, 70, 229, 0.15)" },
                                    }}
                                  >
                                    <Pencil size={18} strokeWidth={1.75} />
                                  </IconButton>
                                  <IconButton
                                    onClick={() => handleOpenDeleteConfirm(material._id)}
                                    aria-label="Delete material"
                                    sx={{
                                      color: "rgb(239 68 68)",
                                      bgcolor: "rgba(239, 68, 68, 0.08)",
                                      "&:hover": { bgcolor: "rgba(239, 68, 68, 0.15)" },
                                    }}
                                  >
                                    <Trash2 size={18} strokeWidth={1.75} />
                                  </IconButton>
                                </Box>
                              </CardContent>
                            </Card>
                          </Grid>
                        );
                      })}
                    </Grid>
                  )}
                </>
              )}
            </Box>
          </div>
        </div>
      </div>

      <Modal open={openEditModal} onClose={() => setOpenEditModal(false)}>
        <Paper sx={modalPaperSx}>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
            <Pencil size={22} strokeWidth={1.75} className="text-indigo-600" />
            <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
              Edit material
            </Typography>
          </Box>
          {(error || success) && (
            <Alert severity={error ? "error" : "success"} sx={{ mb: 2, borderRadius: 2 }}>
              {error || success}
            </Alert>
          )}
          <form onSubmit={handleUpdateMaterial}>
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <FormControl fullWidth size="small">
                  <InputLabel>Class</InputLabel>
                  <Select
                    value={editForm.classId}
                    onChange={(e) => setEditForm({ ...editForm, classId: e.target.value })}
                    label="Class"
                    required
                    sx={selectSx}
                  >
                    <MenuItem value="">Select class</MenuItem>
                    {classes.map((cls) => (
                      <MenuItem key={cls._id} value={cls._id}>
                        {cls.subject}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="Lesson name"
                  value={editForm.lessonName}
                  onChange={(e) => setEditForm({ ...editForm, lessonName: e.target.value })}
                  required
                  sx={fieldSx}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Video size={18} strokeWidth={1.75} className="text-slate-400" />
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="Material title"
                  value={editForm.title}
                  onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                  required
                  sx={fieldSx}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FileText size={18} strokeWidth={1.75} className="text-slate-400" />
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormControl fullWidth size="small">
                  <InputLabel>Content type</InputLabel>
                  <Select
                    value={editForm.type}
                    onChange={(e) => setEditForm({ ...editForm, type: e.target.value })}
                    label="Content type"
                    required
                    sx={selectSx}
                  >
                    <MenuItem value="pdf">PDF</MenuItem>
                    <MenuItem value="video">Video</MenuItem>
                    <MenuItem value="link">External link</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  size="small"
                  label="Upload date"
                  type="date"
                  value={editForm.uploadDate}
                  onChange={(e) => setEditForm({ ...editForm, uploadDate: e.target.value })}
                  InputLabelProps={{ shrink: true }}
                  required
                  sx={fieldSx}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Calendar size={18} strokeWidth={1.75} className="text-slate-400" />
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>
              <Grid item xs={12}>
                {editForm.type === "link" ? (
                  <TextField
                    fullWidth
                    size="small"
                    label="Content URL"
                    value={editForm.content}
                    onChange={(e) => setEditForm({ ...editForm, content: e.target.value })}
                    required
                    sx={fieldSx}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <LinkLucide size={18} strokeWidth={1.75} className="text-slate-400" />
                        </InputAdornment>
                      ),
                    }}
                  />
                ) : (
                  <Paper
                    variant="outlined"
                    sx={{
                      p: 2,
                      borderRadius: 2,
                      borderStyle: "dashed",
                      borderColor: "rgba(148, 163, 184, 0.6)",
                      bgcolor: "rgb(248 250 252)",
                    }}
                  >
                    <Button variant="contained" component="label" disableElevation startIcon={<FolderOpen size={18} strokeWidth={1.75} />} sx={{ textTransform: "none", fontWeight: 600, bgcolor: "rgb(79 70 229)", mb: 1 }}>
                      Replace {editForm.type === "pdf" ? "PDF" : "video"}
                      <input
                        type="file"
                        hidden
                        accept={editForm.type === "pdf" ? ".pdf" : ".mp4"}
                        onChange={(e) => setEditForm({ ...editForm, file: e.target.files?.[0] || null })}
                      />
                    </Button>
                    <Typography variant="body2" sx={{ color: "rgb(100 116 139)" }}>
                      {editForm.file
                        ? `Selected: ${editForm.file.name}`
                        : `Current: ${selectedMaterial?.content?.split?.("/")?.pop?.() || "file"}`}
                    </Typography>
                  </Paper>
                )}
              </Grid>
              <Grid item xs={12}>
                <Button
                  type="submit"
                  variant="contained"
                  disableElevation
                  fullWidth
                  size="large"
                  startIcon={<Save size={20} strokeWidth={1.75} />}
                  sx={{
                    py: 1.25,
                    textTransform: "none",
                    fontWeight: 700,
                    borderRadius: 2,
                    bgcolor: "rgb(79 70 229)",
                    "&:hover": { bgcolor: "rgb(67 56 202)" },
                  }}
                >
                  Save changes
                </Button>
              </Grid>
            </Grid>
          </form>
        </Paper>
      </Modal>

      <Modal open={openDeleteConfirmModal} onClose={handleCloseDeleteConfirm}>
        <Paper sx={{ ...modalPaperSx, width: { xs: "90%", sm: 400 }, textAlign: "center" }}>
          <Trash2 size={40} strokeWidth={1.25} className="mx-auto mb-2 text-red-500 opacity-90" />
          <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)", mb: 1 }}>
            Delete this material?
          </Typography>
          <Typography variant="body2" sx={{ mb: 3, color: "rgb(100 116 139)" }}>
            Students will lose access. This cannot be undone.
          </Typography>
          <Box sx={{ display: "flex", justifyContent: "center", gap: 1.5, flexWrap: "wrap" }}>
            <Button variant="contained" color="error" disableElevation onClick={handleDeleteMaterial} sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2, px: 2.5 }}>
              Delete
            </Button>
            <Button variant="outlined" onClick={handleCloseDeleteConfirm} sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2, px: 2.5 }}>
              Cancel
            </Button>
          </Box>
        </Paper>
      </Modal>
    </div>
  );
};

export default ClassMaterials;
