//frontend/src/features/dashboard/teacher/TeacherNotices.jsx
import { useState, useEffect } from "react";
import { Breadcrumbs, Link as MuiLink, Typography } from "@mui/material";
import { Link, useLocation } from "react-router-dom";
import StudentSidebar from "../../../components/TeacherSidebar/index";
import StudentHeader from "../../../components/TeacherHeader/index";

import axios from "axios";
import {
  Box,
  TextField,
  Button,
  Paper,
  Card,
  CardContent,
  CardActions,
  CircularProgress,
  Alert,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Divider,
  Chip,
  Skeleton,
  Stack,
  InputAdornment,
} from "@mui/material";
import useAuth from "../../../hooks/useAuth";
import {
  Megaphone,
  Type,
  AlignLeft,
  CalendarDays,
  Send,
  Pencil,
  Trash2,
  Inbox,
} from "lucide-react";

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

const fieldSx = {
  "& .MuiOutlinedInput-root": {
    borderRadius: 2,
    bgcolor: "#f8fafc",
    transition: "background-color 0.2s ease",
    "&:hover": { bgcolor: "#f1f5f9" },
    "&:hover fieldset": { borderColor: "rgba(79, 70, 229, 0.35)" },
    "&.Mui-focused": { bgcolor: "#fff" },
    "&.Mui-focused fieldset": { borderColor: "rgb(79 70 229)", borderWidth: "1.5px" },
  },
  "& .MuiInputLabel-root": {
    color: "rgb(100 116 139)",
    "&.Mui-focused": { color: "rgb(79 70 229)" },
  },
};

const selectSx = {
  borderRadius: 2,
  bgcolor: "#f8fafc",
  "&:hover": { bgcolor: "#f1f5f9" },
  "&.Mui-focused": { bgcolor: "#fff" },
  "& 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 TeacherNotices = () => {
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const { user } = useAuth();
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [date, setDate] = useState("");
  const [classId, setClassId] = useState("");
  const [classes, setClasses] = useState([]);
  const [notices, setNotices] = useState([]);
  const [error, setError] = useState(null);
  const [noticesLoading, setNoticesLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editNoticeId, setEditNoticeId] = 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(() => {
    if (!user?.token) return;

    const fetchClasses = async () => {
      try {
        const config = {
          headers: { Authorization: `Bearer ${user.token}` },
        };
        const { data } = await axios.get(`${API_BASE}/api/quiz/teacher/classes`, config);
        setClasses(data);
      } catch (err) {
        setError(err.response?.data?.message || "Error loading classes");
      }
    };

    const fetchNotices = async () => {
      setNoticesLoading(true);
      try {
        const config = {
          headers: { Authorization: `Bearer ${user.token}` },
        };
        const { data } = await axios.get(`${API_BASE}/api/auth/notices/teacher`, config);
        setNotices(data);
      } catch (err) {
        setError(err.response?.data?.message || "Error loading notices");
      } finally {
        setNoticesLoading(false);
      }
    };

    fetchClasses();
    fetchNotices();
  }, [user?.token]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setSaving(true);

    try {
      const config = {
        headers: { Authorization: `Bearer ${user.token}` },
      };
      if (editNoticeId) {
        const { data } = await axios.put(
          `${API_BASE}/api/auth/notices`,
          { noticeId: editNoticeId, title, description, date, classId },
          config
        );
        setNotices(notices.map((n) => (n._id === editNoticeId ? data.notice : n)));
        setEditNoticeId(null);
      } else {
        const { data } = await axios.post(
          `${API_BASE}/api/auth/notices`,
          { title, description, date, classId },
          config
        );
        setNotices([data.notice, ...notices]);
      }
      setTitle("");
      setDescription("");
      setDate("");
      setClassId("");
    } catch (err) {
      setError(err.response?.data?.message || "Error saving notice");
    } finally {
      setSaving(false);
    }
  };

  const handleEdit = (notice) => {
    setEditNoticeId(notice._id);
    setTitle(notice.title);
    setDescription(notice.description);
    setDate(notice.date ? notice.date.split("T")[0] : "");
    setClassId(notice.classId?._id ?? "");
  };

  const handleDelete = async (noticeId) => {
    setError(null);
    try {
      const config = {
        headers: { Authorization: `Bearer ${user.token}` },
      };
      await axios.delete(`${API_BASE}/api/auth/notices/${noticeId}`, config);
      setNotices(notices.filter((n) => n._id !== noticeId));
    } catch (err) {
      setError(err.response?.data?.message || "Error deleting notice");
    }
  };

  const pathnames = location.pathname.split("/").filter((x) => x);
  const formatSegment = (s) =>
    s
      .split("-")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");

  const breadcrumbItems = pathnames.map((value, index) => {
    const last = index === pathnames.length - 1;
    const to = `/${pathnames.slice(0, index + 1).join("/")}`;
    const displayName = formatSegment(value);

    return last ? (
      <Typography key={to} sx={{ color: "rgb(15 23 42)", fontWeight: 600, fontSize: "0.875rem" }}>
        {displayName}
      </Typography>
    ) : (
      <MuiLink
        key={to}
        component={Link}
        to={to}
        underline="hover"
        sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}
      >
        {displayName}
      </MuiLink>
    );
  });

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

  useEffect(() => {
    document.title = "Notices - Teacher - EduConnect";
  }, []);

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

      <div className="flex min-h-screen">
        <div
          className={`fixed left-0 top-0 z-50 h-full transition-all duration-300 ${
            isSidebarCollapsed ? "w-[60px]" : "w-[18%] md:w-[250px]"
          }`}
        >
          <StudentSidebar 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>
              {breadcrumbItems}
            </Breadcrumbs>
          </div>

          <div className="mt-[104px] h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <div className="mx-auto max-w-3xl">
              <Box sx={{ mb: 4 }}>
                <Typography
                  variant="h4"
                  sx={{
                    fontWeight: 700,
                    letterSpacing: "-0.02em",
                    color: "rgb(15 23 42)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1.5,
                    fontSize: { xs: "1.5rem", md: "1.875rem" },
                  }}
                >
                  <Megaphone size={32} strokeWidth={1.75} className="text-indigo-600" aria-hidden />
                  Notices & announcements
                </Typography>
                <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  Post updates for a class. Students see notices on their dashboard for the selected class.
                </Typography>
              </Box>

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

              <form onSubmit={handleSubmit}>
                <Paper
                  elevation={0}
                  sx={{
                    p: { xs: 2, md: 3 },
                    mb: 3,
                    borderRadius: 3,
                    border: "1px solid rgba(15, 23, 42, 0.08)",
                    boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
                    <Type size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Title
                    </Typography>
                  </Box>
                  <TextField
                    fullWidth
                    label="Notice title"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    variant="outlined"
                    required
                    sx={{ ...fieldSx, mb: 2 }}
                  />

                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
                    <AlignLeft size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Message
                    </Typography>
                  </Box>
                  <TextField
                    fullWidth
                    label="Description"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    variant="outlined"
                    multiline
                    rows={4}
                    required
                    sx={{ ...fieldSx, mb: 2 }}
                  />

                  <Stack direction={{ xs: "column", sm: "row" }} spacing={2} sx={{ mb: 2 }}>
                    <TextField
                      fullWidth
                      label="Event / display date"
                      type="date"
                      value={date}
                      onChange={(e) => setDate(e.target.value)}
                      variant="outlined"
                      InputLabelProps={{ shrink: true }}
                      required
                      sx={fieldSx}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <CalendarDays size={18} strokeWidth={1.75} className="text-slate-400" aria-hidden />
                          </InputAdornment>
                        ),
                      }}
                    />
                    <FormControl fullWidth variant="outlined" required>
                      <InputLabel id="notice-class-label">Class</InputLabel>
                      <Select
                        labelId="notice-class-label"
                        value={classId}
                        onChange={(e) => setClassId(e.target.value)}
                        label="Class"
                        sx={selectSx}
                      >
                        {classes.map((cls) => (
                          <MenuItem key={cls._id} value={cls._id}>
                            {cls.subject}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </Stack>

                  <Stack direction={{ xs: "column", sm: "row" }} spacing={1.5}>
                    <Button
                      type="submit"
                      variant="contained"
                      disabled={saving}
                      startIcon={
                        saving ? (
                          <CircularProgress size={18} color="inherit" />
                        ) : (
                          <Send size={18} strokeWidth={2} aria-hidden />
                        )
                      }
                      sx={{
                        py: 1.25,
                        textTransform: "none",
                        fontWeight: 600,
                        borderRadius: 2,
                        bgcolor: "rgb(79 70 229)",
                        boxShadow: "0 1px 2px rgba(79, 70, 229, 0.25)",
                        "&:hover": { bgcolor: "rgb(67 56 202)" },
                      }}
                    >
                      {editNoticeId ? "Update notice" : "Publish notice"}
                    </Button>
                    {editNoticeId && (
                      <Button
                        variant="outlined"
                        onClick={() => {
                          setEditNoticeId(null);
                          setTitle("");
                          setDescription("");
                          setDate("");
                          setClassId("");
                        }}
                        sx={{
                          py: 1.25,
                          textTransform: "none",
                          fontWeight: 600,
                          borderRadius: 2,
                          borderColor: "rgba(15, 23, 42, 0.2)",
                          color: "rgb(71 85 105)",
                        }}
                      >
                        Cancel edit
                      </Button>
                    )}
                  </Stack>
                </Paper>
              </form>

              <Divider sx={{ my: 3, borderColor: "rgba(15, 23, 42, 0.08)" }} />

              <Typography
                variant="h6"
                sx={{ fontWeight: 700, color: "rgb(15 23 42)", mb: 2, letterSpacing: "-0.01em" }}
              >
                Published notices
              </Typography>

              {noticesLoading ? (
                <Stack spacing={2}>
                  {[1, 2, 3].map((i) => (
                    <Paper
                      key={i}
                      elevation={0}
                      sx={{
                        p: 2,
                        borderRadius: 3,
                        border: "1px solid rgba(15, 23, 42, 0.08)",
                      }}
                    >
                      <Skeleton variant="text" width="55%" height={28} />
                      <Skeleton variant="text" width="35%" height={20} sx={{ mt: 1 }} />
                      <Skeleton variant="rounded" height={72} sx={{ mt: 2, borderRadius: 2 }} />
                    </Paper>
                  ))}
                </Stack>
              ) : notices.length > 0 ? (
                <Stack spacing={2}>
                  {notices.map((notice) => (
                    <Card
                      key={notice._id}
                      elevation={0}
                      sx={{
                        borderRadius: 3,
                        border: "1px solid rgba(15, 23, 42, 0.08)",
                        boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                        overflow: "visible",
                      }}
                    >
                      <CardContent sx={{ pb: 1 }}>
                        <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                          {notice.title}
                        </Typography>
                        <Stack direction="row" flexWrap="wrap" gap={1} sx={{ mt: 1.25, mb: 1 }}>
                          <Chip
                            size="small"
                            label={notice.classId?.subject ?? "Class unavailable"}
                            sx={{
                              bgcolor: "rgba(79, 70, 229, 0.08)",
                              color: "rgb(79 70 229)",
                              fontWeight: 600,
                              border: "none",
                            }}
                          />
                          <Chip
                            size="small"
                            variant="outlined"
                            label={new Date(notice.date).toLocaleDateString()}
                            sx={{ borderColor: "rgba(15, 23, 42, 0.12)", fontWeight: 500 }}
                          />
                        </Stack>
                        <Typography variant="body2" sx={{ color: "rgb(51 65 85)", lineHeight: 1.65, mt: 0.5 }}>
                          {notice.description}
                        </Typography>
                        <Typography variant="caption" sx={{ display: "block", mt: 1.5, color: "rgb(148 163 184)" }}>
                          Published {notice.createdAt ? new Date(notice.createdAt).toLocaleString() : "—"}
                        </Typography>
                      </CardContent>
                      <CardActions sx={{ px: 2, pb: 2, pt: 0, gap: 1 }}>
                        <Button
                          variant="contained"
                          size="small"
                          onClick={() => handleEdit(notice)}
                          startIcon={<Pencil size={16} strokeWidth={2} aria-hidden />}
                          sx={{
                            textTransform: "none",
                            fontWeight: 600,
                            borderRadius: 2,
                            bgcolor: "rgb(79 70 229)",
                            "&:hover": { bgcolor: "rgb(67 56 202)" },
                          }}
                        >
                          Edit
                        </Button>
                        <Button
                          variant="outlined"
                          color="error"
                          size="small"
                          onClick={() => handleDelete(notice._id)}
                          startIcon={<Trash2 size={16} strokeWidth={2} aria-hidden />}
                          sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2 }}
                        >
                          Delete
                        </Button>
                      </CardActions>
                    </Card>
                  ))}
                </Stack>
              ) : (
                <Paper
                  elevation={0}
                  sx={{
                    p: 4,
                    textAlign: "center",
                    borderRadius: 3,
                    border: "1px dashed rgba(15, 23, 42, 0.12)",
                    bgcolor: "rgba(248, 250, 252, 0.8)",
                  }}
                >
                  <Inbox size={40} strokeWidth={1.5} className="mx-auto text-slate-300" aria-hidden />
                  <Typography sx={{ mt: 2, color: "rgb(100 116 139)", fontWeight: 500 }}>
                    No notices yet. Publish your first announcement above.
                  </Typography>
                </Paper>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TeacherNotices;
