//frontend/src/features/dashboard/admin/ContactMessages.jsx
import { useState, useEffect, useCallback } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  Paper,
  Button,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Alert,
  Chip,
  Stack,
  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 { Inbox, Mail, RefreshCw, Trash2, User, MessageSquareText, Tag, Calendar } 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 classificationChip(label) {
  const v = (label || "normal").toLowerCase();
  if (v === "spam") {
    return { label: "Spam", sx: { bgcolor: "rgba(239, 68, 68, 0.12)", color: "rgb(185 28 28)", fontWeight: 700 } };
  }
  if (v === "promotion") {
    return { label: "Promotion", sx: { bgcolor: "rgba(245, 158, 11, 0.15)", color: "rgb(180 83 9)", fontWeight: 700 } };
  }
  return { label: "Normal", sx: { bgcolor: "rgba(16, 185, 129, 0.12)", color: "rgb(5 122 85)", fontWeight: 700 } };
}

const ContactMessages = () => {
  const { user } = useAuth();
  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [deleteId, setDeleteId] = useState(null);
  const [deleting, setDeleting] = useState(false);
  const location = useLocation();

  const fetchMessages = useCallback(async () => {
    if (!user?.token || user?.role !== "admin") return;
    setLoading(true);
    setError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.get(`${API_BASE}/api/contact`, config);
      setMessages(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.response?.data?.message || "Failed to load contact messages.");
    } finally {
      setLoading(false);
    }
  }, [user?.token, user?.role]);

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

  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/contact/${deleteId}`, config);
      setMessages((prev) => prev.filter((msg) => msg._id !== deleteId));
      setDeleteId(null);
    } catch (err) {
      setError(err.response?.data?.message || "Failed to delete message.");
    } finally {
      setDeleting(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 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 = "Contact messages - 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>
    );
  }

  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" },
                    }}
                  >
                    <Inbox size={32} strokeWidth={1.75} className="text-indigo-600 shrink-0" aria-hidden />
                    Contact messages
                  </Typography>
                  <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                    Submissions from the public contact form. Review and remove spam if needed.
                  </Typography>
                </Box>
                <Button
                  variant="outlined"
                  disabled={loading}
                  onClick={() => fetchMessages()}
                  startIcon={loading ? <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
                </Button>
              </Stack>

              <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
                <Chip
                  label={`${messages.length} message${messages.length === 1 ? "" : "s"}`}
                  sx={{ fontWeight: 600, bgcolor: "rgba(79, 70, 229, 0.1)", color: "rgb(79 70 229)" }}
                />
              </Stack>

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

              <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,
                  }}
                >
                  <Mail size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Inbox
                  </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>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <User size={14} className="text-slate-500" />
                            <span>Name</span>
                          </Stack>
                        </TableCell>
                        <TableCell>Email</TableCell>
                        <TableCell>Message</TableCell>
                        <TableCell>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <Tag size={14} className="text-slate-500" />
                            <span>Type</span>
                          </Stack>
                        </TableCell>
                        <TableCell>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <Calendar size={14} className="text-slate-500" />
                            <span>Received</span>
                          </Stack>
                        </TableCell>
                        <TableCell align="right">Actions</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {loading ? (
                        [1, 2, 3, 4, 5].map((i) => (
                          <TableRow key={i}>
                            <TableCell colSpan={6}>
                              <Skeleton variant="rounded" height={40} sx={{ borderRadius: 1 }} />
                            </TableCell>
                          </TableRow>
                        ))
                      ) : messages.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={6} sx={{ py: 8, textAlign: "center" }}>
                            <MessageSquareText size={40} strokeWidth={1.5} className="mx-auto text-slate-300" />
                            <Typography sx={{ mt: 2, color: "rgb(100 116 139)", fontWeight: 500 }}>
                              No messages yet.
                            </Typography>
                          </TableCell>
                        </TableRow>
                      ) : (
                        messages.map((msg) => {
                          const chip = classificationChip(msg.classification);
                          const preview = (msg.message || "").slice(0, 120) + ((msg.message || "").length > 120 ? "…" : "");
                          return (
                            <TableRow
                              key={msg._id}
                              hover
                              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)">
                                  {msg.name || "—"}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                <Typography variant="body2" color="rgb(71 85 105)" sx={{ wordBreak: "break-word" }}>
                                  {msg.email || "—"}
                                </Typography>
                              </TableCell>
                              <TableCell sx={{ maxWidth: 360 }}>
                                <Tooltip title={msg.message || ""} placement="top" enterDelay={400}>
                                  <Typography variant="body2" color="rgb(71 85 105)" sx={{ lineHeight: 1.5 }}>
                                    {preview || "—"}
                                  </Typography>
                                </Tooltip>
                              </TableCell>
                              <TableCell>
                                <Chip size="small" label={chip.label} sx={{ ...chip.sx, border: "none" }} />
                              </TableCell>
                              <TableCell>
                                <Typography variant="body2" color="rgb(71 85 105)">
                                  {msg.createdAt ? new Date(msg.createdAt).toLocaleString() : "—"}
                                </Typography>
                              </TableCell>
                              <TableCell align="right">
                                <Tooltip title="Delete message">
                                  <IconButton
                                    size="small"
                                    color="error"
                                    onClick={() => setDeleteId(msg._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"
                                  >
                                    <Trash2 size={18} strokeWidth={2} />
                                  </IconButton>
                                </Tooltip>
                              </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 message?</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 ContactMessages;
