import { useState, useEffect } from "react";
import { useLocation, Link } from "react-router-dom";
import axios from "axios";
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  Breadcrumbs,
  Link as MuiLink,
  CircularProgress,
  Alert,
  TextField,
  Fade,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  IconButton,
  Collapse,
  TablePagination,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Chip,
  Stack,
  Skeleton,
  InputAdornment,
  Tooltip,
} from "@mui/material";
import AdminSidebar from "../../../components/AdminSidebar/index";
import AdminHeader from "../../../components/AdminHeader/index";
import {
  Users,
  Filter,
  ChevronDown,
  ChevronUp,
  FileDown,
  FileText,
  Pencil,
  Ban,
  CheckCircle,
  Trash2,
  Mail,
  Phone,
  Calendar,
  Search,
} from "lucide-react";
import jsPDF from "jspdf";
import "jspdf-autotable";

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 paperCardSx = {
  borderRadius: 3,
  border: "1px solid rgba(15, 23, 42, 0.08)",
  boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
  overflow: "hidden",
};

/** Shared button styling — consistent, subdued surfaces and motion */
const btnTransition = "background-color 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease, color 0.18s ease";

const btnExportToolbar = {
  textTransform: "none",
  fontWeight: 600,
  fontSize: "0.8125rem",
  letterSpacing: "0.02em",
  borderRadius: "10px",
  minHeight: 40,
  px: 2.25,
  transition: btnTransition,
};

const btnRow = {
  textTransform: "none",
  fontWeight: 600,
  fontSize: "0.75rem",
  letterSpacing: "0.03em",
  borderRadius: "8px",
  minHeight: 32,
  px: 1.35,
  py: 0.5,
  transition: btnTransition,
  boxShadow: "none",
  "& .MuiButton-startIcon": { marginRight: "6px", "& svg": { width: 14, height: 14 } },
};

/** Row actions: one line, solid fills — black / green / blue / red */
const btnActionSolid = {
  ...btnRow,
  flexShrink: 0,
  color: "#fff",
  border: "none",
  boxShadow: "0 1px 4px rgba(0, 0, 0, 0.2)",
  "& .MuiButton-startIcon": {
    marginRight: "6px",
    color: "#fff",
    "& svg": { width: 14, height: 14, stroke: "#fff" },
  },
};

const btnDialog = {
  textTransform: "none",
  fontWeight: 600,
  fontSize: "0.875rem",
  letterSpacing: "0.02em",
  borderRadius: "10px",
  minHeight: 42,
  minWidth: 108,
  px: 2.5,
  transition: btnTransition,
};

const TeacherList = () => {
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [teachers, setTeachers] = useState([]);
  const [filteredTeachers, setFilteredTeachers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [confirmModalOpen, setConfirmModalOpen] = useState(false);
  const [filterPanelOpen, setFilterPanelOpen] = useState(true);
  const [confirmAction, setConfirmAction] = useState(null);
  const [confirmMessage, setConfirmMessage] = useState("");
  const [selectedTeacher, setSelectedTeacher] = useState(null);
  const [editFormData, setEditFormData] = useState({
    name: "",
    email: "",
    age: "",
    contactNumber: "",
  });
  const [editErrors, setEditErrors] = useState({});
  const [filter, setFilter] = useState({
    name: "",
    email: "",
    ageMin: "",
    ageMax: "",
    status: "all",
  });
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  const toggleSidebar = () => setIsSidebarCollapsed(!isSidebarCollapsed);
  const toggleFilterPanel = () => setFilterPanelOpen(!filterPanelOpen);

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

  useEffect(() => {
    const fetchTeachers = async () => {
      setLoading(true);
      setError(null);
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        const config = { headers: { Authorization: `Bearer ${userInfo?.token}` } };
        const { data } = await axios.get(`${API_BASE}/api/admin/teachers`, config);
        setTeachers(data);
        setFilteredTeachers(data);
      } catch (err) {
        setError(err.response?.data?.message || "Failed to fetch teachers. Please try again later.");
      } finally {
        setLoading(false);
      }
    };
    fetchTeachers();
  }, []);

  useEffect(() => {
    const applyFilters = () => {
      let filtered = [...teachers];

      if (filter.name) {
        filtered = filtered.filter((teacher) =>
          teacher.name.toLowerCase().includes(filter.name.toLowerCase())
        );
      }

      if (filter.email) {
        filtered = filtered.filter((teacher) =>
          teacher.email.toLowerCase().includes(filter.email.toLowerCase())
        );
      }

      if (filter.ageMin || filter.ageMax) {
        filtered = filtered.filter((teacher) => {
          const age = parseInt(teacher.age, 10) || 0;
          const min = parseInt(filter.ageMin, 10) || 0;
          const max = parseInt(filter.ageMax, 10) || Infinity;
          return age >= min && age <= max;
        });
      }

      if (filter.status !== "all") {
        filtered = filtered.filter((teacher) => teacher.subscriptionStatus === filter.status);
      }

      setFilteredTeachers(filtered);
      setPage(0);
    };

    applyFilters();
  }, [filter, teachers]);

  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilter((prev) => ({ ...prev, [name]: value }));
  };

  const handleBanTeacher = async (teacherId) => {
    setConfirmMessage("Are you sure you want to ban this teacher?");
    setConfirmAction(
      () => async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const config = { headers: { Authorization: `Bearer ${userInfo?.token}` } };
          await axios.put(`${API_BASE}/api/admin/teachers/${teacherId}/ban`, {}, config);
          setTeachers((prev) =>
            prev.map((teacher) =>
              teacher._id === teacherId ? { ...teacher, subscriptionStatus: "inactive" } : teacher
            )
          );
          setConfirmModalOpen(false);
        } catch (err) {
          setError(err.response?.data?.message || "Failed to ban teacher. Please try again later.");
          setConfirmModalOpen(false);
        }
      }
    );
    setConfirmModalOpen(true);
  };

  const handleUnbanTeacher = async (teacherId) => {
    setConfirmMessage("Are you sure you want to unban this teacher?");
    setConfirmAction(
      () => async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const config = { headers: { Authorization: `Bearer ${userInfo?.token}` } };
          await axios.put(`${API_BASE}/api/admin/teachers/${teacherId}/unban`, {}, config);
          setTeachers((prev) =>
            prev.map((teacher) =>
              teacher._id === teacherId ? { ...teacher, subscriptionStatus: "active" } : teacher
            )
          );
          setConfirmModalOpen(false);
        } catch (err) {
          setError(err.response?.data?.message || "Failed to unban teacher. Please try again later.");
          setConfirmModalOpen(false);
        }
      }
    );
    setConfirmModalOpen(true);
  };

  const handleRemoveTeacher = async (teacherId) => {
    setConfirmMessage("Remove this teacher? This cannot be undone.");
    setConfirmAction(
      () => async () => {
        try {
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const config = { headers: { Authorization: `Bearer ${userInfo?.token}` } };
          await axios.delete(`${API_BASE}/api/admin/teachers/${teacherId}`, config);
          setTeachers((prev) => prev.filter((teacher) => teacher._id !== teacherId));
          setConfirmModalOpen(false);
        } catch (err) {
          setError(err.response?.data?.message || "Failed to remove teacher. Please try again later.");
          setConfirmModalOpen(false);
        }
      }
    );
    setConfirmModalOpen(true);
  };

  const handleOpenEditModal = (teacher) => {
    setSelectedTeacher(teacher);
    setEditFormData({
      name: teacher.name,
      email: teacher.email,
      age: teacher.age || "",
      contactNumber: teacher.contactNumber || "",
    });
    setEditErrors({});
    setEditModalOpen(true);
  };

  const handleCloseEditModal = () => {
    setEditModalOpen(false);
    setSelectedTeacher(null);
    setEditFormData({ name: "", email: "", age: "", contactNumber: "" });
    setEditErrors({});
  };

  const handleEditFormChange = (e) => {
    const { name, value } = e.target;
    setEditFormData((prev) => ({ ...prev, [name]: value }));
    setEditErrors((prev) => ({ ...prev, [name]: "" }));
  };

  const validateEditForm = () => {
    const errors = {};
    if (!editFormData.name) errors.name = "Name is required";
    if (!editFormData.email) errors.email = "Email is required";
    else if (!/\S+@\S+\.\S+/.test(editFormData.email)) errors.email = "Email is invalid";
    if (editFormData.age && (isNaN(editFormData.age) || editFormData.age <= 0))
      errors.age = "Age must be a positive number";
    if (editFormData.contactNumber && !/^\+?\d{10,15}$/.test(editFormData.contactNumber))
      errors.contactNumber = "Contact number must be 10-15 digits";
    setEditErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleEditSubmit = async (e) => {
    e.preventDefault();
    if (!validateEditForm()) return;

    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      const config = { headers: { Authorization: `Bearer ${userInfo?.token}` } };
      const response = await axios.put(
        `${API_BASE}/api/admin/teachers/${selectedTeacher._id}`,
        editFormData,
        config
      );
      setTeachers((prev) =>
        prev.map((teacher) => (teacher._id === selectedTeacher._id ? response.data.teacher : teacher))
      );
      handleCloseEditModal();
    } catch (err) {
      setError(err.response?.data?.message || "Failed to update teacher. Please try again later.");
    }
  };

  const exportToCSV = () => {
    const headers = ["Name", "Email", "Age", "Contact Number", "Status", "Created At"];
    const rows = filteredTeachers.map((teacher) => [
      `"${teacher.name}"`,
      `"${teacher.email}"`,
      teacher.age || "N/A",
      teacher.contactNumber || "N/A",
      teacher.subscriptionStatus,
      new Date(teacher.createdAt).toLocaleDateString(),
    ]);

    const csvContent = [headers.join(","), ...rows.map((row) => row.join(","))].join("\n");

    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "teachers_list.csv";
    link.click();
  };

  const exportToPDF = () => {
    const doc = new jsPDF();
    doc.setFont("helvetica", "bold");
    doc.setFontSize(18);
    doc.text("Teachers List", 14, 20);
    doc.setFontSize(12);
    doc.setFont("helvetica", "normal");
    doc.text(`Generated on: ${new Date().toLocaleDateString()}`, 14, 30);
    doc.text(`Admin: ${JSON.parse(localStorage.getItem("userInfo"))?.name || "EduConnect Admin"}`, 14, 40);

    const tableData = filteredTeachers.map((teacher) => [
      teacher.name,
      teacher.email,
      teacher.age || "N/A",
      teacher.contactNumber || "N/A",
      teacher.subscriptionStatus.charAt(0).toUpperCase() + teacher.subscriptionStatus.slice(1),
      new Date(teacher.createdAt).toLocaleDateString(),
    ]);

    doc.autoTable({
      startY: 50,
      head: [["Name", "Email", "Age", "Contact Number", "Status", "Created At"]],
      body: tableData,
      theme: "striped",
      headStyles: { fillColor: [79, 70, 229] },
      styles: { fontSize: 9, cellPadding: 3 },
      margin: { top: 50 },
    });

    doc.save(`Teachers_List_${new Date().toLocaleDateString().replace(/\//g, "-")}.pdf`);
  };

  const handleChangePage = (_, newPage) => setPage(newPage);
  const handleChangeRowsPerPage = (e) => {
    setRowsPerPage(parseInt(e.target.value, 10));
    setPage(0);
  };

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

  const activeCount = teachers.filter((t) => t.subscriptionStatus === "active").length;
  const inactiveCount = teachers.filter((t) => t.subscriptionStatus === "inactive").length;

  const runConfirm = () => {
    if (typeof confirmAction === "function") confirmAction();
  };

  const paginatedRows = filteredTeachers.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage);

  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-7xl">
              <Stack direction={{ xs: "column", md: "row" }} spacing={2} justifyContent="space-between" 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" },
                    }}
                  >
                    <Users size={32} strokeWidth={1.75} className="text-indigo-600 shrink-0" aria-hidden />
                    Teachers
                  </Typography>
                  <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                    Manage accounts, subscription access, and exports.
                  </Typography>
                </Box>
                <Paper
                  elevation={0}
                  sx={{
                    display: "inline-flex",
                    flexWrap: "wrap",
                    gap: 1,
                    p: 0.75,
                    borderRadius: "12px",
                    border: "1px solid rgba(15, 23, 42, 0.08)",
                    bgcolor: "rgba(248, 250, 252, 0.95)",
                    boxShadow: "inset 0 1px 0 rgba(255,255,255,0.8)",
                  }}
                >
                  <Button
                    variant="outlined"
                    disableElevation
                    startIcon={<FileDown size={17} strokeWidth={2} />}
                    onClick={exportToCSV}
                    disabled={loading || filteredTeachers.length === 0}
                    sx={{
                      ...btnExportToolbar,
                      borderColor: "rgba(15, 23, 42, 0.14)",
                      color: "rgb(51 65 85)",
                      bgcolor: "#fff",
                      boxShadow: "0 1px 2px rgba(15, 23, 42, 0.05)",
                      "&:hover": {
                        borderColor: "rgba(79, 70, 229, 0.5)",
                        bgcolor: "rgba(79, 70, 229, 0.04)",
                        boxShadow: "0 2px 8px rgba(15, 23, 42, 0.08)",
                      },
                      "&:disabled": {
                        borderColor: "rgba(15, 23, 42, 0.08)",
                        color: "rgba(100, 116, 139, 0.6)",
                        bgcolor: "rgba(248, 250, 252, 0.8)",
                      },
                    }}
                  >
                    Export CSV
                  </Button>
                  <Button
                    variant="contained"
                    disableElevation
                    startIcon={<FileText size={17} strokeWidth={2} />}
                    onClick={exportToPDF}
                    disabled={loading || filteredTeachers.length === 0}
                    sx={{
                      ...btnExportToolbar,
                      bgcolor: "rgb(79 70 229)",
                      color: "#fff",
                      boxShadow: "0 2px 10px rgba(79, 70, 229, 0.38)",
                      "&:hover": {
                        bgcolor: "rgb(67 56 202)",
                        boxShadow: "0 4px 16px rgba(79, 70, 229, 0.45)",
                      },
                      "&:disabled": {
                        bgcolor: "rgba(79, 70, 229, 0.4)",
                        color: "rgba(255,255,255,0.85)",
                        boxShadow: "none",
                      },
                    }}
                  >
                    Export PDF
                  </Button>
                </Paper>
              </Stack>

              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mb: 3 }}>
                <Chip
                  label={`${teachers.length} total`}
                  sx={{ bgcolor: "rgba(15, 23, 42, 0.06)", fontWeight: 600, color: "rgb(15 23 42)" }}
                />
                <Chip
                  label={`${activeCount} active`}
                  sx={{ bgcolor: "rgba(16, 185, 129, 0.12)", fontWeight: 600, color: "rgb(5 122 85)" }}
                />
                <Chip
                  label={`${inactiveCount} inactive`}
                  sx={{ bgcolor: "rgba(239, 68, 68, 0.12)", fontWeight: 600, color: "rgb(185 28 28)" }}
                />
                <Chip
                  label={`${filteredTeachers.length} shown`}
                  variant="outlined"
                  sx={{ fontWeight: 600, borderColor: "rgba(79, 70, 229, 0.35)", 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, mb: 3 }}>
                <Box
                  onClick={toggleFilterPanel}
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    px: 2,
                    py: 1.5,
                    cursor: "pointer",
                    bgcolor: "rgba(248, 250, 252, 0.9)",
                    borderBottom: filterPanelOpen ? "1px solid rgba(15, 23, 42, 0.08)" : "none",
                    "&:hover": { bgcolor: "rgba(241, 245, 249, 0.95)" },
                  }}
                >
                  <Stack direction="row" alignItems="center" spacing={1}>
                    <Filter size={20} className="text-indigo-600" strokeWidth={1.75} />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Filters
                    </Typography>
                  </Stack>
                  <IconButton
                    size="small"
                    aria-expanded={filterPanelOpen}
                    aria-label="Toggle filters"
                    sx={{
                      borderRadius: "10px",
                      border: "1px solid rgba(15, 23, 42, 0.08)",
                      bgcolor: "#fff",
                      color: "rgb(71 85 105)",
                      transition: btnTransition,
                      "&:hover": {
                        bgcolor: "rgba(79, 70, 229, 0.06)",
                        borderColor: "rgba(79, 70, 229, 0.25)",
                        color: "rgb(79 70 229)",
                      },
                    }}
                  >
                    {filterPanelOpen ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
                  </IconButton>
                </Box>
                <Collapse in={filterPanelOpen}>
                  <Box sx={{ p: 2.5, pt: 2 }}>
                    <Grid container spacing={2}>
                      <Grid item xs={12} sm={6} md={3}>
                        <TextField
                          fullWidth
                          label="Name"
                          name="name"
                          value={filter.name}
                          onChange={handleFilterChange}
                          size="small"
                          sx={fieldSx}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <Search size={18} className="text-slate-400" />
                              </InputAdornment>
                            ),
                          }}
                        />
                      </Grid>
                      <Grid item xs={12} sm={6} md={3}>
                        <TextField
                          fullWidth
                          label="Email"
                          name="email"
                          value={filter.email}
                          onChange={handleFilterChange}
                          size="small"
                          sx={fieldSx}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <Mail size={18} className="text-slate-400" />
                              </InputAdornment>
                            ),
                          }}
                        />
                      </Grid>
                      <Grid item xs={6} sm={3} md={2}>
                        <TextField
                          fullWidth
                          label="Min age"
                          name="ageMin"
                          value={filter.ageMin}
                          onChange={handleFilterChange}
                          type="number"
                          size="small"
                          sx={fieldSx}
                        />
                      </Grid>
                      <Grid item xs={6} sm={3} md={2}>
                        <TextField
                          fullWidth
                          label="Max age"
                          name="ageMax"
                          value={filter.ageMax}
                          onChange={handleFilterChange}
                          type="number"
                          size="small"
                          sx={fieldSx}
                        />
                      </Grid>
                      <Grid item xs={12} sm={6} md={2}>
                        <FormControl fullWidth size="small" sx={fieldSx}>
                          <InputLabel>Status</InputLabel>
                          <Select
                            name="status"
                            value={filter.status}
                            onChange={handleFilterChange}
                            label="Status"
                          >
                            <MenuItem value="all">All</MenuItem>
                            <MenuItem value="active">Active</MenuItem>
                            <MenuItem value="inactive">Inactive</MenuItem>
                          </Select>
                        </FormControl>
                      </Grid>
                    </Grid>
                  </Box>
                </Collapse>
              </Paper>

              <Paper elevation={0} sx={{ ...paperCardSx }}>
                <TableContainer sx={{ overflowX: "auto" }}>
                  <Table size="medium" sx={{ minWidth: 1020 }}>
                    <TableHead>
                      <TableRow
                        sx={{
                          bgcolor: "rgba(79, 70, 229, 0.06)",
                          "& th": {
                            fontWeight: 700,
                            color: "rgb(15 23 42)",
                            fontSize: "0.8125rem",
                            textTransform: "uppercase",
                            letterSpacing: "0.04em",
                            borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                          },
                        }}
                      >
                        <TableCell>Name</TableCell>
                        <TableCell>Email</TableCell>
                        <TableCell align="center">Age</TableCell>
                        <TableCell>Contact</TableCell>
                        <TableCell>Status</TableCell>
                        <TableCell>Joined</TableCell>
                        <TableCell align="right" sx={{ whiteSpace: "nowrap", minWidth: 300 }}>
                          Actions
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {loading
                        ? Array.from({ length: rowsPerPage }).map((_, i) => (
                            <TableRow key={i}>
                              <TableCell colSpan={7}>
                                <Skeleton variant="rounded" height={44} sx={{ borderRadius: 1 }} />
                              </TableCell>
                            </TableRow>
                          ))
                        : paginatedRows.length === 0
                          ? (
                              <TableRow>
                                <TableCell colSpan={7} sx={{ py: 6, textAlign: "center" }}>
                                  <Typography color="text.secondary" fontWeight={500}>
                                    No teachers match your filters.
                                  </Typography>
                                </TableCell>
                              </TableRow>
                            )
                          : (
                              paginatedRows.map((teacher) => (
                                <TableRow
                                  key={teacher._id}
                                  hover
                                  sx={{
                                    "&:nth-of-type(even)": { bgcolor: "rgba(248, 250, 252, 0.6)" },
                                    "& td": { borderColor: "rgba(15, 23, 42, 0.06)", verticalAlign: "middle" },
                                  }}
                                >
                                  <TableCell>
                                    <Typography fontWeight={600} color="rgb(15 23 42)">
                                      {teacher.name}
                                    </Typography>
                                  </TableCell>
                                  <TableCell>
                                    <Typography variant="body2" color="rgb(71 85 105)" sx={{ wordBreak: "break-word" }}>
                                      {teacher.email}
                                    </Typography>
                                  </TableCell>
                                  <TableCell align="center">{teacher.age || "—"}</TableCell>
                                  <TableCell>
                                    <Stack direction="row" alignItems="center" spacing={0.5}>
                                      <Phone size={14} className="text-slate-400 shrink-0" />
                                      <Typography variant="body2" color="rgb(71 85 105)">
                                        {teacher.contactNumber || "—"}
                                      </Typography>
                                    </Stack>
                                  </TableCell>
                                  <TableCell>
                                    <Chip
                                      size="small"
                                      label={
                                        teacher.subscriptionStatus === "active" ? "Active" : "Inactive"
                                      }
                                      sx={{
                                        fontWeight: 700,
                                        bgcolor:
                                          teacher.subscriptionStatus === "active"
                                            ? "rgba(16, 185, 129, 0.15)"
                                            : "rgba(239, 68, 68, 0.12)",
                                        color:
                                          teacher.subscriptionStatus === "active"
                                            ? "rgb(5 122 85)"
                                            : "rgb(185 28 28)",
                                        border: "none",
                                      }}
                                    />
                                  </TableCell>
                                  <TableCell>
                                    <Stack direction="row" alignItems="center" spacing={0.5}>
                                      <Calendar size={14} className="text-slate-400 shrink-0" />
                                      <Typography variant="body2" color="rgb(71 85 105)">
                                        {new Date(teacher.createdAt).toLocaleDateString()}
                                      </Typography>
                                    </Stack>
                                  </TableCell>
                                  <TableCell align="right" sx={{ whiteSpace: "nowrap", verticalAlign: "middle" }}>
                                    <Stack
                                      direction="row"
                                      spacing={0.75}
                                      justifyContent="flex-end"
                                      alignItems="center"
                                      flexWrap="nowrap"
                                      sx={{ width: "100%" }}
                                    >
                                      {teacher.subscriptionStatus === "active" ? (
                                        <Tooltip title="Ban (deactivate)">
                                          <Button
                                            size="small"
                                            variant="contained"
                                            disableElevation
                                            onClick={() => handleBanTeacher(teacher._id)}
                                            startIcon={<Ban size={14} strokeWidth={2.25} />}
                                            sx={{
                                              ...btnActionSolid,
                                              bgcolor: "#0a0a0a",
                                              "&:hover": { bgcolor: "#262626", boxShadow: "0 2px 8px rgba(0,0,0,0.35)" },
                                            }}
                                          >
                                            Ban
                                          </Button>
                                        </Tooltip>
                                      ) : (
                                        <Tooltip title="Unban (reactivate)">
                                          <Button
                                            size="small"
                                            variant="contained"
                                            disableElevation
                                            onClick={() => handleUnbanTeacher(teacher._id)}
                                            startIcon={<CheckCircle size={14} strokeWidth={2.25} />}
                                            sx={{
                                              ...btnActionSolid,
                                              bgcolor: "#16a34a",
                                              "&:hover": { bgcolor: "#15803d", boxShadow: "0 2px 8px rgba(22,163,74,0.45)" },
                                            }}
                                          >
                                            Unban
                                          </Button>
                                        </Tooltip>
                                      )}
                                      <Tooltip title="Edit details">
                                        <Button
                                          size="small"
                                          variant="contained"
                                          disableElevation
                                          onClick={() => handleOpenEditModal(teacher)}
                                          startIcon={<Pencil size={14} strokeWidth={2.25} />}
                                          sx={{
                                            ...btnActionSolid,
                                            bgcolor: "#2563eb",
                                            "&:hover": { bgcolor: "#1d4ed8", boxShadow: "0 2px 8px rgba(37,99,235,0.45)" },
                                          }}
                                        >
                                          Edit
                                        </Button>
                                      </Tooltip>
                                      <Tooltip title="Delete teacher">
                                        <Button
                                          size="small"
                                          variant="contained"
                                          disableElevation
                                          onClick={() => handleRemoveTeacher(teacher._id)}
                                          startIcon={<Trash2 size={14} strokeWidth={2.25} />}
                                          sx={{
                                            ...btnActionSolid,
                                            bgcolor: "#dc2626",
                                            "&:hover": { bgcolor: "#b91c1c", boxShadow: "0 2px 8px rgba(220,38,38,0.45)" },
                                          }}
                                        >
                                          Remove
                                        </Button>
                                      </Tooltip>
                                    </Stack>
                                  </TableCell>
                                </TableRow>
                              ))
                            )}
                    </TableBody>
                  </Table>
                </TableContainer>
                <TablePagination
                  component="div"
                  rowsPerPageOptions={[8, 10, 25, 50]}
                  count={filteredTeachers.length}
                  rowsPerPage={rowsPerPage}
                  page={page}
                  onPageChange={handleChangePage}
                  onRowsPerPageChange={handleChangeRowsPerPage}
                  sx={{
                    borderTop: "1px solid rgba(15, 23, 42, 0.08)",
                    px: 1,
                    "& .MuiTablePagination-toolbar": { minHeight: 52 },
                  }}
                />
              </Paper>
            </div>
          </div>
        </div>
      </div>

      <Dialog
        open={editModalOpen}
        onClose={handleCloseEditModal}
        fullWidth
        maxWidth="sm"
        TransitionComponent={Fade}
        PaperProps={{ sx: { borderRadius: 3, overflow: "hidden" } }}
      >
        <DialogTitle
          sx={{
            py: 2,
            px: 2.5,
            fontWeight: 700,
            bgcolor: "rgb(79 70 229)",
            color: "#fff",
            display: "flex",
            alignItems: "center",
            gap: 1,
          }}
        >
          <Pencil size={22} strokeWidth={1.75} />
          Edit teacher
        </DialogTitle>
        <form onSubmit={handleEditSubmit}>
          <DialogContent sx={{ pt: 3, px: 2.5 }}>
            <TextField
              fullWidth
              label="Name"
              name="name"
              value={editFormData.name}
              onChange={handleEditFormChange}
              error={!!editErrors.name}
              helperText={editErrors.name}
              sx={{ ...fieldSx, mb: 2 }}
            />
            <TextField
              fullWidth
              label="Email"
              name="email"
              value={editFormData.email}
              onChange={handleEditFormChange}
              error={!!editErrors.email}
              helperText={editErrors.email}
              sx={{ ...fieldSx, mb: 2 }}
            />
            <TextField
              fullWidth
              label="Age"
              name="age"
              value={editFormData.age}
              onChange={handleEditFormChange}
              error={!!editErrors.age}
              helperText={editErrors.age}
              sx={{ ...fieldSx, mb: 2 }}
            />
            <TextField
              fullWidth
              label="Contact number"
              name="contactNumber"
              value={editFormData.contactNumber}
              onChange={handleEditFormChange}
              error={!!editErrors.contactNumber}
              helperText={editErrors.contactNumber}
              sx={fieldSx}
            />
          </DialogContent>
          <DialogActions
            sx={{
              px: 2.5,
              pb: 2.5,
              pt: 1,
              gap: 1.25,
              borderTop: "1px solid rgba(15, 23, 42, 0.06)",
              bgcolor: "rgba(248, 250, 252, 0.5)",
            }}
          >
            <Button
              variant="outlined"
              disableElevation
              onClick={handleCloseEditModal}
              sx={{
                ...btnDialog,
                borderColor: "rgba(15, 23, 42, 0.16)",
                color: "rgb(71 85 105)",
                bgcolor: "#fff",
                "&:hover": {
                  borderColor: "rgba(15, 23, 42, 0.28)",
                  bgcolor: "rgba(248, 250, 252, 1)",
                },
              }}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              variant="contained"
              disableElevation
              sx={{
                ...btnDialog,
                bgcolor: "rgb(79 70 229)",
                color: "#fff",
                boxShadow: "0 2px 12px rgba(79, 70, 229, 0.35)",
                "&:hover": {
                  bgcolor: "rgb(67 56 202)",
                  boxShadow: "0 4px 16px rgba(79, 70, 229, 0.42)",
                },
              }}
            >
              Save changes
            </Button>
          </DialogActions>
        </form>
      </Dialog>

      <Dialog
        open={confirmModalOpen}
        onClose={() => setConfirmModalOpen(false)}
        TransitionComponent={Fade}
        PaperProps={{ sx: { borderRadius: 3, p: 0.5 } }}
      >
        <DialogTitle sx={{ fontWeight: 700, color: "rgb(15 23 42)", pb: 0.5 }}>Confirm</DialogTitle>
        <DialogContent>
          <Typography variant="body2" color="text.secondary" sx={{ lineHeight: 1.6 }}>
            {confirmMessage}
          </Typography>
        </DialogContent>
        <DialogActions
          sx={{
            px: 3,
            pb: 2.5,
            pt: 1,
            gap: 1.25,
            borderTop: "1px solid rgba(15, 23, 42, 0.06)",
            bgcolor: "rgba(248, 250, 252, 0.5)",
          }}
        >
          <Button
            variant="outlined"
            disableElevation
            onClick={() => setConfirmModalOpen(false)}
            sx={{
              ...btnDialog,
              borderColor: "rgba(15, 23, 42, 0.16)",
              color: "rgb(71 85 105)",
              bgcolor: "#fff",
              "&:hover": {
                borderColor: "rgba(15, 23, 42, 0.28)",
                bgcolor: "rgba(248, 250, 252, 1)",
              },
            }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            disableElevation
            onClick={runConfirm}
            sx={{
              ...btnDialog,
              bgcolor: "rgb(220 38 38)",
              color: "#fff",
              boxShadow: "0 2px 10px rgba(220, 38, 38, 0.35)",
              "&:hover": {
                bgcolor: "rgb(185 28 28)",
                boxShadow: "0 4px 14px rgba(220, 38, 38, 0.4)",
              },
            }}
          >
            Confirm
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default TeacherList;
