// frontend/src/features/dashboard/student/ActiveTeachers.jsx
import { useState, useEffect, useCallback } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  Paper,
  Button,
  Alert,
  Stack,
  Chip,
  Skeleton,
  CircularProgress,
  Collapse,
  Avatar,
  Divider,
} from "@mui/material";
import { Link, useLocation } from "react-router-dom";
import StudentSidebar from "../../../components/StudentSidebar/index";
import StudentHeader from "../../../components/StudentHeader/index";
import axios from "axios";
import PaymentModal from "../../../components/PaymentModal";
import useAuth from "../../../hooks/useAuth";
import {
  Users,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  Mail,
  GraduationCap,
  BookOpen,
  DollarSign,
} 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",
};

const ActiveTeachers = () => {
  const { user } = useAuth();
  const [teachers, setTeachers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [selectedTeacher, setSelectedTeacher] = useState(null);
  const [classes, setClasses] = useState([]);
  const [classesLoading, setClassesLoading] = useState(false);
  const [classesError, setClassesError] = useState(null);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [selectedClassId, setSelectedClassId] = useState(null);
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

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

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

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

  const fetchClassesForTeacher = async (teacherId) => {
    setClassesLoading(true);
    setClassesError(null);
    try {
      const { data } = await axios.get(`${API_BASE}/api/classes/teacher/${teacherId}`);
      setClasses(Array.isArray(data) ? data : []);
      setSelectedTeacher(teacherId);
    } catch (err) {
      setClassesError(err.response?.data?.message || "Failed to load classes.");
    } finally {
      setClassesLoading(false);
    }
  };

  const handleSeeClasses = (teacherId) => {
    if (selectedTeacher === teacherId) {
      setSelectedTeacher(null);
      setClasses([]);
      setClassesError(null);
    } else {
      fetchClassesForTeacher(teacherId);
    }
  };

  const handlePayClassFee = (classId) => {
    setSelectedClassId(classId);
    setPaymentModalOpen(true);
  };

  const handlePaymentSubmit = async (paymentData) => {
    if (!user?.token) throw new Error("Not signed in.");
    const config = { headers: { Authorization: `Bearer ${user.token}` } };
    await axios.post(
      `${API_BASE}/api/payments/subscribe`,
      {
        classId: paymentData.classId,
        cardNumber: paymentData.cardNumber,
        expiryDate: paymentData.expiryDate,
        cvv: paymentData.cvv,
      },
      config
    );
    setSuccess("Subscription successful.");
    setPaymentModalOpen(false);
  };

  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 crumbSegments =
    pathnames[0] === "student" && pathnames[1] === "dashboard" ? pathnames.slice(2) : pathnames;
  const formatSegment = (s) =>
    s
      .split("-")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");

  const breadcrumbItems = crumbSegments.map((value, index) => {
    const last = index === crumbSegments.length - 1;
    const to = `/student/dashboard/${crumbSegments.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 = "All teachers - Student - EduConnect";
  }, []);

  const isStudent = user?.role === "student";

  if (!isStudent) {
    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">
      <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="/student/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-5xl">
              <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" },
                    }}
                  >
                    <Users size={32} strokeWidth={1.75} className="text-indigo-600 shrink-0" aria-hidden />
                    All teachers
                  </Typography>
                  <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                    Browse teachers offering classes and subscribe to a class when you&apos;re ready.
                  </Typography>
                </Box>
                <Button
                  variant="outlined"
                  disabled={loading}
                  onClick={() => fetchTeachers()}
                  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>

              {!loading && (
                <Chip
                  label={`${teachers.length} teacher${teachers.length === 1 ? "" : "s"}`}
                  sx={{ mb: 2, fontWeight: 600, bgcolor: "rgba(79, 70, 229, 0.1)", color: "rgb(79 70 229)" }}
                />
              )}

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

              {loading ? (
                <Stack spacing={2}>
                  {[1, 2, 3].map((i) => (
                    <Skeleton key={i} variant="rounded" height={120} sx={{ borderRadius: 3 }} />
                  ))}
                </Stack>
              ) : teachers.length === 0 ? (
                <Paper elevation={0} sx={{ ...paperCardSx, p: 6, textAlign: "center" }}>
                  <GraduationCap size={48} strokeWidth={1.25} className="mx-auto text-slate-300" />
                  <Typography sx={{ mt: 2, color: "rgb(100 116 139)", fontWeight: 500 }}>
                    No teachers available yet.
                  </Typography>
                </Paper>
              ) : (
                <Stack spacing={2.5}>
                  {teachers.map((teacher) => {
                    const quals = Array.isArray(teacher?.qualifications) ? teacher.qualifications : [];
                    const initials = (teacher?.name || "?")
                      .split(/\s+/)
                      .map((p) => p[0])
                      .join("")
                      .slice(0, 2)
                      .toUpperCase();
                    const expanded = selectedTeacher === teacher._id;

                    return (
                      <Paper key={teacher._id} elevation={0} sx={paperCardSx}>
                        <Box
                          sx={{
                            p: { xs: 2, md: 2.5 },
                            display: "flex",
                            flexDirection: { xs: "column", sm: "row" },
                            alignItems: { sm: "flex-start" },
                            justifyContent: "space-between",
                            gap: 2,
                          }}
                        >
                          <Stack direction="row" spacing={2} alignItems="flex-start">
                            <Avatar
                              sx={{
                                width: 52,
                                height: 52,
                                bgcolor: "rgba(79, 70, 229, 0.15)",
                                color: "rgb(79 70 229)",
                                fontWeight: 700,
                              }}
                            >
                              {initials}
                            </Avatar>
                            <Box>
                              <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                                {teacher?.name || "—"}
                              </Typography>
                              <Stack direction="row" alignItems="center" spacing={0.75} sx={{ mt: 0.5 }}>
                                <Mail size={14} className="text-slate-400 shrink-0" />
                                <Typography variant="body2" color="rgb(71 85 105)">
                                  {teacher?.email || "—"}
                                </Typography>
                              </Stack>
                              {quals.length > 0 && (
                                <Stack direction="row" flexWrap="wrap" gap={0.75} sx={{ mt: 1.5 }}>
                                  {quals.map((qual, idx) => (
                                    <Chip
                                      key={`${teacher._id}-q-${idx}`}
                                      size="small"
                                      label={qual}
                                      sx={{
                                        fontWeight: 600,
                                        bgcolor: "rgba(79, 70, 229, 0.08)",
                                        color: "rgb(67 56 202)",
                                      }}
                                    />
                                  ))}
                                </Stack>
                              )}
                            </Box>
                          </Stack>
                          <Button
                            variant="contained"
                            onClick={() => handleSeeClasses(teacher._id)}
                            endIcon={
                              expanded ? (
                                <ChevronUp size={18} strokeWidth={2} />
                              ) : (
                                <ChevronDown size={18} strokeWidth={2} />
                              )
                            }
                            sx={{
                              textTransform: "none",
                              fontWeight: 600,
                              borderRadius: 2,
                              px: 2.5,
                              bgcolor: "rgb(79 70 229)",
                              "&:hover": { bgcolor: "rgb(67 56 202)" },
                              alignSelf: { xs: "stretch", sm: "center" },
                              flexShrink: 0,
                            }}
                          >
                            {expanded ? "Hide classes" : "View classes"}
                          </Button>
                        </Box>

                        <Collapse in={expanded} timeout="auto" unmountOnExit>
                          <Divider sx={{ borderColor: "rgba(15, 23, 42, 0.08)" }} />
                          <Box sx={{ p: { xs: 2, md: 2.5 }, bgcolor: "rgba(248, 250, 252, 0.85)" }}>
                            {classesLoading ? (
                              <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
                                <CircularProgress size={36} sx={{ color: "rgb(79 70 229)" }} />
                              </Box>
                            ) : classesError ? (
                              <Alert severity="error" onClose={() => setClassesError(null)} sx={{ borderRadius: 2 }}>
                                {classesError}
                              </Alert>
                            ) : classes.length === 0 ? (
                              <Typography color="rgb(100 116 139)" textAlign="center" sx={{ py: 2 }}>
                                No classes listed for this teacher.
                              </Typography>
                            ) : (
                              <Stack spacing={2}>
                                <Stack direction="row" alignItems="center" spacing={1}>
                                  <BookOpen size={18} className="text-indigo-600" />
                                  <Typography fontWeight={700} color="rgb(15 23 42)">
                                    Classes
                                  </Typography>
                                </Stack>
                                <Box
                                  sx={{
                                    display: "grid",
                                    gridTemplateColumns: { xs: "1fr", md: "repeat(2, 1fr)" },
                                    gap: 2,
                                  }}
                                >
                                  {classes.map((cls) => (
                                    <Paper
                                      key={cls._id}
                                      variant="outlined"
                                      sx={{
                                        p: 2,
                                        borderRadius: 2,
                                        borderColor: "rgba(15, 23, 42, 0.1)",
                                        bgcolor: "white",
                                      }}
                                    >
                                      <Typography fontWeight={700} color="rgb(15 23 42)">
                                        {cls?.subject || "Class"}
                                      </Typography>
                                      <Typography variant="body2" color="rgb(71 85 105)" sx={{ mt: 0.75, lineHeight: 1.5 }}>
                                        {cls?.description || "Course curriculum and materials from your teacher."}
                                      </Typography>
                                      <Stack
                                        direction="row"
                                        alignItems="center"
                                        justifyContent="space-between"
                                        sx={{ mt: 2, flexWrap: "wrap", gap: 1.5 }}
                                      >
                                        <Stack direction="row" alignItems="center" spacing={0.5}>
                                          <DollarSign size={18} className="text-emerald-700" />
                                          <Typography fontWeight={700} color="rgb(5 122 85)">
                                            USD {cls?.monthlyFee ?? "—"}/mo
                                          </Typography>
                                        </Stack>
                                        <Button
                                          size="small"
                                          variant="contained"
                                          onClick={() => handlePayClassFee(cls._id)}
                                          sx={{
                                            textTransform: "none",
                                            fontWeight: 600,
                                            borderRadius: 2,
                                            bgcolor: "rgb(79 70 229)",
                                            "&:hover": { bgcolor: "rgb(67 56 202)" },
                                          }}
                                        >
                                          Pay now
                                        </Button>
                                      </Stack>
                                    </Paper>
                                  ))}
                                </Box>
                              </Stack>
                            )}
                          </Box>
                        </Collapse>
                      </Paper>
                    );
                  })}
                </Stack>
              )}
            </div>
          </div>
        </div>
      </div>

      <PaymentModal
        open={paymentModalOpen}
        onClose={() => setPaymentModalOpen(false)}
        onSubmit={handlePaymentSubmit}
        classId={selectedClassId}
      />
    </div>
  );
};

export default ActiveTeachers;
