// frontend/src/features/dashboard/admin/AdminNotices.jsx
import { useState, useEffect, useCallback } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  Paper,
  Button,
  CircularProgress,
  TextField,
  Alert,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Skeleton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
} from "@mui/material";
import { Link, useLocation } from "react-router-dom";
import AdminSidebar from "../../../components/AdminSidebar/index";
import AdminHeader from "../../../components/AdminHeader/index";
import axios from "axios";
import useAuth from "../../../hooks/useAuth";
import {
  Megaphone,
  RefreshCw,
  Calendar,
  Users,
  Pencil,
  Trash2,
  ScrollText,
  Send,
} from "lucide-react";

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

const paperCardSx = {
  borderRadius: 3,
  border: "1px solid rgba(15, 23, 42, 0.08)",
  boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
  overflow: "hidden",
};

function recipientChip(value) {
  const v = value || "";
  if (v === "teachers") {
    return { label: "Teachers", sx: { bgcolor: "rgba(79, 70, 229, 0.12)", color: "rgb(67 56 202)", fontWeight: 700 } };
  }
  if (v === "institutes") {
    return { label: "Institutes", sx: { bgcolor: "rgba(147, 51, 234, 0.12)", color: "rgb(107 33 168)", fontWeight: 700 } };
  }
  if (v === "teachers_and_institutes") {
    return { label: "Teachers & institutes", sx: { bgcolor: "rgba(13, 148, 136, 0.12)", color: "rgb(15 118 110)", fontWeight: 700 } };
  }
  return {
    label: v.replace(/_/g, " ") || "—",
    sx: { bgcolor: "rgba(100, 116, 139, 0.12)", color: "rgb(71 85 105)", fontWeight: 600 },
  };
}

const AdminNotices = () => {
  const { user } = useAuth();
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [date, setDate] = useState("");
  const [recipients, setRecipients] = useState("");
  const [notices, setNotices] = useState([]);
  const [error, setError] = useState(null);
  const [listLoading, setListLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editNoticeId, setEditNoticeId] = useState(null);
  const [deleteId, setDeleteId] = useState(null);
  const [deleting, setDeleting] = useState(false);
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  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);
  }, []);

  const fetchNotices = useCallback(async () => {
    if (!user?.token || user?.role !== "admin") return;
    setListLoading(true);
    setError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.get(`${API_BASE}/api/auth/admin/notices`, config);
      setNotices(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.response?.data?.message || "Error loading notices.");
    } finally {
      setListLoading(false);
    }
  }, [user?.token, user?.role]);

  useEffect(() => {
    fetchNotices();
  }, [fetchNotices]);

  const resetForm = () => {
    setEditNoticeId(null);
    setTitle("");
    setDescription("");
    setDate("");
    setRecipients("");
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!user?.token) return;
    setError(null);
    setSaving(true);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      if (editNoticeId) {
        const { data } = await axios.put(
          `${API_BASE}/api/auth/admin/notices`,
          { noticeId: editNoticeId, title, description, date, recipients },
          config
        );
        setNotices((prev) => prev.map((n) => (n._id === editNoticeId ? data.notice : n)));
        resetForm();
      } else {
        const { data } = await axios.post(
          `${API_BASE}/api/auth/admin/notices`,
          { title, description, date, recipients },
          config
        );
        setNotices((prev) => [data.notice, ...prev]);
        resetForm();
      }
    } catch (err) {
      setError(err.response?.data?.message || "Error saving notice.");
    } finally {
      setSaving(false);
    }
  };

  const handleEdit = (notice) => {
    setEditNoticeId(notice?._id || null);
    setTitle(notice?.title || "");
    setDescription(notice?.description || "");
    const d = notice?.date;
    setDate(typeof d === "string" && d.includes("T") ? d.split("T")[0] : d || "");
    setRecipients(notice?.recipients || "");
  };

  const handleConfirmDelete = async () => {
    if (!deleteId || !user?.token) return;
    setDeleting(true);
    setError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      await axios.delete(`${API_BASE}/api/auth/admin/notices/${deleteId}`, config);
      setNotices((prev) => prev.filter((n) => n._id !== deleteId));
      if (editNoticeId === deleteId) resetForm();
      setDeleteId(null);
    } catch (err) {
      setError(err.response?.data?.message || "Error deleting notice.");
    } finally {
      setDeleting(false);
    }
  };

  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 - Admin - EduConnect";
  }, []);

  const isAdmin = user?.role === "admin";

  if (!isAdmin) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-slate-50 p-6">
        <Alert severity="warning" sx={{ maxWidth: 420, borderRadius: 2 }}>
          You don&apos;t have access to this page.
        </Alert>
      </div>
    );
  }

  const fieldSx = {
    "& .MuiOutlinedInput-root": { borderRadius: 2 },
  };

  return (
    <div className="min-h-screen bg-slate-50">
      <AdminHeader
        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]"
          }`}
        >
          <AdminSidebar 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="/admin/dashboard"
                underline="hover"
                sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}
              >
                Dashboard
              </MuiLink>
              {breadcrumbItems}
            </Breadcrumbs>
          </div>

          <div className="mt-[104px] min-h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <div className="mx-auto max-w-6xl">
              <Stack
                direction={{ xs: "column", sm: "row" }}
                spacing={2}
                justifyContent="space-between"
                alignItems={{ sm: "flex-start" }}
                sx={{ mb: 3 }}
              >
                <Box>
                  <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 shrink-0" aria-hidden />
                    Notices & announcements
                  </Typography>
                  <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                    Publish updates for teachers and institutes. They will see these in their dashboards.
                  </Typography>
                </Box>
                <Button
                  variant="outlined"
                  disabled={listLoading}
                  onClick={() => fetchNotices()}
                  startIcon={listLoading ? <CircularProgress size={18} /> : <RefreshCw size={18} strokeWidth={2} />}
                  sx={{
                    textTransform: "none",
                    fontWeight: 600,
                    borderRadius: 2,
                    borderColor: "rgba(15, 23, 42, 0.14)",
                    color: "rgb(71 85 105)",
                    alignSelf: { xs: "stretch", sm: "center" },
                  }}
                >
                  Refresh list
                </Button>
              </Stack>

              <Stack direction="row" spacing={1} sx={{ mb: 2, flexWrap: "wrap" }}>
                <Chip
                  label={`${notices.length} published`}
                  sx={{ fontWeight: 600, bgcolor: "rgba(79, 70, 229, 0.1)", color: "rgb(79 70 229)" }}
                />
                {editNoticeId && (
                  <Chip label="Editing" color="warning" sx={{ fontWeight: 600 }} onDelete={resetForm} />
                )}
              </Stack>

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

              <Paper elevation={0} sx={{ ...paperCardSx, mb: 3 }}>
                <Box
                  sx={{
                    px: 2,
                    py: 1.5,
                    borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                    bgcolor: "rgba(248, 250, 252, 0.9)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                  }}
                >
                  <Send size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    {editNoticeId ? "Edit notice" : "Compose notice"}
                  </Typography>
                </Box>
                <Box sx={{ p: { xs: 2, md: 3 } }}>
                  <form onSubmit={handleSubmit}>
                    <Stack spacing={2.5}>
                      <TextField
                        fullWidth
                        label="Title"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        required
                        sx={fieldSx}
                      />
                      <TextField
                        fullWidth
                        label="Description"
                        value={description}
                        onChange={(e) => setDescription(e.target.value)}
                        multiline
                        rows={4}
                        required
                        sx={fieldSx}
                      />
                      <TextField
                        fullWidth
                        label="Date"
                        type="date"
                        value={date}
                        onChange={(e) => setDate(e.target.value)}
                        InputLabelProps={{ shrink: true }}
                        required
                        sx={fieldSx}
                      />
                      <FormControl fullWidth required sx={fieldSx}>
                        <InputLabel>Recipients</InputLabel>
                        <Select
                          value={recipients}
                          onChange={(e) => setRecipients(e.target.value)}
                          label="Recipients"
                          sx={{ borderRadius: 2 }}
                        >
                          <MenuItem value="teachers">Teachers</MenuItem>
                          <MenuItem value="institutes">Institutes</MenuItem>
                          <MenuItem value="teachers_and_institutes">Teachers & institutes</MenuItem>
                        </Select>
                      </FormControl>
                      <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} />
                          }
                          sx={{
                            textTransform: "none",
                            fontWeight: 600,
                            borderRadius: 2,
                            py: 1.25,
                            bgcolor: "rgb(79 70 229)",
                            "&:hover": { bgcolor: "rgb(67 56 202)" },
                            flex: { sm: "0 0 auto" },
                          }}
                        >
                          {editNoticeId ? "Update notice" : "Publish notice"}
                        </Button>
                        {editNoticeId && (
                          <Button
                            variant="outlined"
                            onClick={resetForm}
                            disabled={saving}
                            sx={{
                              textTransform: "none",
                              fontWeight: 600,
                              borderRadius: 2,
                              py: 1.25,
                              borderColor: "rgba(15, 23, 42, 0.2)",
                              color: "rgb(71 85 105)",
                            }}
                          >
                            Cancel edit
                          </Button>
                        )}
                      </Stack>
                    </Stack>
                  </form>
                </Box>
              </Paper>

              <Paper elevation={0} sx={paperCardSx}>
                <Box
                  sx={{
                    px: 2,
                    py: 1.5,
                    borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                    bgcolor: "rgba(248, 250, 252, 0.9)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                  }}
                >
                  <ScrollText size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Published notices
                  </Typography>
                </Box>
                <TableContainer sx={{ overflowX: "auto" }}>
                  <Table size="small" sx={{ minWidth: 720 }}>
                    <TableHead>
                      <TableRow
                        sx={{
                          bgcolor: "rgba(79, 70, 229, 0.06)",
                          "& th": {
                            fontWeight: 700,
                            fontSize: "0.75rem",
                            textTransform: "uppercase",
                            letterSpacing: "0.05em",
                            color: "rgb(15 23 42)",
                            borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                          },
                        }}
                      >
                        <TableCell>Title</TableCell>
                        <TableCell>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <Users size={14} className="text-slate-500" />
                            <span>Recipients</span>
                          </Stack>
                        </TableCell>
                        <TableCell>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <Calendar size={14} className="text-slate-500" />
                            <span>Event date</span>
                          </Stack>
                        </TableCell>
                        <TableCell>Description</TableCell>
                        <TableCell>Published</TableCell>
                        <TableCell align="right">Actions</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {listLoading ? (
                        [1, 2, 3, 4, 5].map((i) => (
                          <TableRow key={i}>
                            <TableCell colSpan={6}>
                              <Skeleton variant="rounded" height={44} sx={{ borderRadius: 1 }} />
                            </TableCell>
                          </TableRow>
                        ))
                      ) : notices.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={6} sx={{ py: 8, textAlign: "center" }}>
                            <Megaphone size={40} strokeWidth={1.5} className="mx-auto text-slate-300" />
                            <Typography sx={{ mt: 2, color: "rgb(100 116 139)", fontWeight: 500 }}>
                              No notices published yet.
                            </Typography>
                          </TableCell>
                        </TableRow>
                      ) : (
                        notices.map((notice) => {
                          const chip = recipientChip(notice?.recipients);
                          const desc = notice?.description || "";
                          const preview = desc.slice(0, 100) + (desc.length > 100 ? "…" : "");
                          return (
                            <TableRow
                              key={notice._id}
                              hover
                              selected={editNoticeId === notice._id}
                              sx={{
                                "&:nth-of-type(even)": { bgcolor: "rgba(248, 250, 252, 0.6)" },
                                "& td": { borderColor: "rgba(15, 23, 42, 0.06)", verticalAlign: "top" },
                              }}
                            >
                              <TableCell>
                                <Typography fontWeight={600} color="rgb(15 23 42)">
                                  {notice?.title || "—"}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Chip size="small" label={chip.label} sx={{ ...chip.sx, border: "none" }} />
                              </TableCell>
                              <TableCell>
                                <Typography variant="body2" color="rgb(71 85 105)">
                                  {notice?.date ? new Date(notice.date).toLocaleDateString() : "—"}
                                </Typography>
                              </TableCell>
                              <TableCell sx={{ maxWidth: 280 }}>
                                <Tooltip title={desc} placement="top" enterDelay={400}>
                                  <Typography variant="body2" color="rgb(71 85 105)" sx={{ lineHeight: 1.5 }}>
                                    {preview || "—"}
                                  </Typography>
                                </Tooltip>
                              </TableCell>
                              <TableCell>
                                <Typography variant="body2" color="rgb(71 85 105)">
                                  {notice?.createdAt ? new Date(notice.createdAt).toLocaleString() : "—"}
                                </Typography>
                              </TableCell>
                              <TableCell align="right">
                                <Stack direction="row" spacing={0.5} justifyContent="flex-end">
                                  <Tooltip title="Edit">
                                    <IconButton
                                      size="small"
                                      onClick={() => handleEdit(notice)}
                                      sx={{
                                        borderRadius: 2,
                                        border: "1px solid rgba(79, 70, 229, 0.35)",
                                        bgcolor: "rgba(238, 242, 255, 0.7)",
                                        color: "rgb(79 70 229)",
                                        "&:hover": { bgcolor: "rgba(224, 231, 255, 0.95)" },
                                      }}
                                      aria-label="Edit notice"
                                    >
                                      <Pencil size={18} strokeWidth={2} />
                                    </IconButton>
                                  </Tooltip>
                                  <Tooltip title="Delete">
                                    <IconButton
                                      size="small"
                                      color="error"
                                      onClick={() => setDeleteId(notice._id)}
                                      sx={{
                                        borderRadius: 2,
                                        border: "1px solid rgba(220, 38, 38, 0.35)",
                                        bgcolor: "rgba(254, 242, 242, 0.6)",
                                        "&:hover": { bgcolor: "rgba(254, 226, 226, 0.95)" },
                                      }}
                                      aria-label="Delete notice"
                                    >
                                      <Trash2 size={18} strokeWidth={2} />
                                    </IconButton>
                                  </Tooltip>
                                </Stack>
                              </TableCell>
                            </TableRow>
                          );
                        })
                      )}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Paper>
            </div>
          </div>
        </div>
      </div>

      <Dialog open={!!deleteId} onClose={() => !deleting && setDeleteId(null)} PaperProps={{ sx: { borderRadius: 3 } }}>
        <DialogTitle sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>Delete notice?</DialogTitle>
        <DialogContent>
          <Typography variant="body2" color="text.secondary">
            This cannot be undone.
          </Typography>
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2, gap: 1 }}>
          <Button onClick={() => setDeleteId(null)} disabled={deleting} sx={{ textTransform: "none", fontWeight: 600 }}>
            Cancel
          </Button>
          <Button
            variant="contained"
            color="error"
            disabled={deleting}
            onClick={handleConfirmDelete}
            startIcon={deleting ? <CircularProgress size={18} color="inherit" /> : <Trash2 size={18} />}
            sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2 }}
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default AdminNotices;
