// frontend/src/features/dashboard/student/RefundRequest.jsx
import { useState, useEffect, useCallback } from "react";
import {
  Typography,
  Breadcrumbs,
  Link as MuiLink,
  Snackbar,
  Alert,
  Box,
  TextField,
  Button,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Paper,
  Stack,
  Skeleton,
  CircularProgress,
} from "@mui/material";
import StudentSidebar from "../../../components/StudentSidebar/index";
import StudentHeader from "../../../components/StudentHeader/index";
import axios from "axios";
import { useNavigate, Link, useLocation } from "react-router-dom";
import useAuth from "../../../hooks/useAuth";
import { WalletCards, Send, FileImage, History } 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 fieldSx = {
  "& .MuiOutlinedInput-root": { borderRadius: 2 },
};

const RefundRequest = () => {
  const { user } = useAuth();
  const [classes, setClasses] = useState([]);
  const [classesLoading, setClassesLoading] = useState(true);
  const [classesError, setClassesError] = useState(null);
  const [classId, setClassId] = useState("");
  const [reason, setReason] = useState("");
  const [proof, setProof] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [successOpen, setSuccessOpen] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");
  const navigate = useNavigate();
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

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

  const fetchClasses = useCallback(async () => {
    if (!user?.token || user?.role !== "student") return;
    setClassesLoading(true);
    setClassesError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.get(`${API_BASE}/api/subscriptions/my-classes`, config);
      setClasses(Array.isArray(data) ? data : []);
    } catch (err) {
      setClassesError(err.response?.data?.message || "Could not load your classes.");
      setClasses([]);
    } finally {
      setClassesLoading(false);
    }
  }, [user?.token, user?.role]);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!user?.token) return;
    if (!classId) {
      setSubmitError("Please select a class.");
      return;
    }
    setSubmitError(null);
    setSubmitting(true);
    try {
      const config = {
        headers: {
          Authorization: `Bearer ${user.token}`,
          "Content-Type": "multipart/form-data",
        },
      };

      const formData = new FormData();
      formData.append("classId", classId);
      formData.append("reason", reason);
      if (proof) {
        formData.append("proof", proof);
      }

      await axios.post(`${API_BASE}/api/refunds/request`, formData, config);
      setSuccessMessage("Refund request submitted successfully.");
      setSuccessOpen(true);
      setClassId("");
      setReason("");
      setProof(null);
      setTimeout(() => {
        navigate("/student/dashboard/refund-history");
      }, 2000);
    } catch (error) {
      setSubmitError(error.response?.data?.message || "Failed to submit refund request. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleSuccessClose = () => {
    setSuccessOpen(false);
    setSuccessMessage("");
  };

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

  useEffect(() => {
    document.title = "Refund request - Student - EduConnect";
  }, []);

  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)]";

  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-xl">
              <Stack spacing={0.75} sx={{ mb: 3 }}>
                <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.75rem" },
                  }}
                >
                  <WalletCards size={30} strokeWidth={1.75} className="text-indigo-600 shrink-0" aria-hidden />
                  Request a refund
                </Typography>
                <Typography sx={{ color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  Choose a subscribed class, explain why you need a refund, and optionally attach a screenshot.
                </Typography>
              </Stack>

              <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
                <Button
                  component={Link}
                  to="/student/dashboard/refund-history"
                  variant="outlined"
                  size="small"
                  startIcon={<History size={16} strokeWidth={2} />}
                  sx={{
                    textTransform: "none",
                    fontWeight: 600,
                    borderRadius: 2,
                    borderColor: "rgba(15, 23, 42, 0.14)",
                    color: "rgb(71 85 105)",
                  }}
                >
                  Refund history
                </Button>
                <Button
                  variant="outlined"
                  size="small"
                  disabled={classesLoading}
                  onClick={() => fetchClasses()}
                  sx={{
                    textTransform: "none",
                    fontWeight: 600,
                    borderRadius: 2,
                    borderColor: "rgba(15, 23, 42, 0.14)",
                    color: "rgb(71 85 105)",
                  }}
                >
                  Refresh classes
                </Button>
              </Stack>

              {classesError && (
                <Alert severity="error" onClose={() => setClassesError(null)} sx={{ mb: 2, borderRadius: 2 }}>
                  {classesError}
                </Alert>
              )}
              {submitError && (
                <Alert severity="error" onClose={() => setSubmitError(null)} sx={{ mb: 2, borderRadius: 2 }}>
                  {submitError}
                </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,
                  }}
                >
                  <Send size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Refund form
                  </Typography>
                </Box>

                <Box sx={{ p: { xs: 2, md: 3 } }}>
                  {classesLoading ? (
                    <Stack spacing={2}>
                      <Skeleton variant="rounded" height={56} sx={{ borderRadius: 2 }} />
                      <Skeleton variant="rounded" height={120} sx={{ borderRadius: 2 }} />
                      <Skeleton variant="rounded" height={48} sx={{ borderRadius: 2 }} />
                    </Stack>
                  ) : (
                    <form onSubmit={handleSubmit}>
                      <Stack spacing={2.5}>
                        <FormControl fullWidth required sx={fieldSx}>
                          <InputLabel id="refund-class-label">Class</InputLabel>
                          <Select
                            labelId="refund-class-label"
                            value={classId}
                            label="Class"
                            onChange={(e) => setClassId(e.target.value)}
                            disabled={classes.length === 0}
                            displayEmpty
                            renderValue={(selected) => {
                              if (!selected) {
                                return (
                                  <Typography component="span" sx={{ color: "rgb(148 163 184)" }}>
                                    Select a class
                                  </Typography>
                                );
                              }
                              const cls = classes.find((c) => c._id === selected);
                              return cls?.subject || "Class";
                            }}
                            sx={{ borderRadius: 2 }}
                          >
                            {classes.length === 0 ? (
                              <MenuItem value="" disabled>
                                No subscribed classes
                              </MenuItem>
                            ) : (
                              [
                                <MenuItem key="placeholder" value="" disabled>
                                  Select a class
                                </MenuItem>,
                                ...classes.map((cls) => (
                                  <MenuItem key={cls._id} value={cls._id}>
                                    {cls?.subject || "Class"}
                                  </MenuItem>
                                )),
                              ]
                            )}
                          </Select>
                        </FormControl>

                        <TextField
                          fullWidth
                          label="Reason for refund"
                          multiline
                          rows={5}
                          value={reason}
                          onChange={(e) => setReason(e.target.value)}
                          required
                          sx={fieldSx}
                          placeholder="Describe what went wrong or why you are requesting a refund."
                        />

                        <Box>
                          <Typography
                            component="label"
                            htmlFor="proof-upload"
                            sx={{
                              display: "flex",
                              alignItems: "center",
                              gap: 0.75,
                              mb: 1,
                              fontWeight: 600,
                              fontSize: "0.875rem",
                              color: "rgb(71 85 105)",
                            }}
                          >
                            <FileImage size={16} className="text-slate-500" />
                            Proof (optional, JPG or PNG)
                          </Typography>
                          <Button
                            component="label"
                            variant="outlined"
                            sx={{
                              textTransform: "none",
                              fontWeight: 600,
                              borderRadius: 2,
                              borderColor: "rgba(15, 23, 42, 0.14)",
                              color: "rgb(71 85 105)",
                            }}
                          >
                            Choose file
                            <input
                              type="file"
                              accept="image/jpeg,image/png"
                              hidden
                              onChange={(e) => setProof(e.target.files?.[0] || null)}
                            />
                          </Button>
                          {proof && (
                            <Typography variant="caption" display="block" sx={{ color: "rgb(100 116 139)", mt: 1 }}>
                              Selected: {proof.name}
                            </Typography>
                          )}
                        </Box>

                        <Button
                          type="submit"
                          variant="contained"
                          disabled={submitting || classes.length === 0}
                          startIcon={
                            submitting ? <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)" },
                          }}
                        >
                          Submit refund request
                        </Button>
                      </Stack>
                    </form>
                  )}
                </Box>
              </Paper>
            </div>
          </div>
        </div>
      </div>

      <Snackbar
        open={successOpen}
        autoHideDuration={4000}
        onClose={handleSuccessClose}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Alert onClose={handleSuccessClose} severity="success" variant="filled" sx={{ width: "100%", borderRadius: 2 }}>
          {successMessage}
        </Alert>
      </Snackbar>
    </div>
  );
};

export default RefundRequest;
