import { useState, useEffect } from "react";
import { useLocation, Link } from "react-router-dom";
import axios from "axios";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography,
  Breadcrumbs,
  Link as MuiLink,
  TextField,
  Grid,
  Button,
  Box,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  TablePagination,
  InputAdornment,
  Chip,
  Skeleton,
} from "@mui/material";
import { saveAs } from "file-saver";
import * as XLSX from "xlsx";
import jsPDF from "jspdf";
import "jspdf-autotable";
import StudentSidebar from "../../../components/StudentSidebar/index";
import StudentHeader from "../../../components/StudentHeader/index";
import {
  Search,
  User,
  Calendar,
  CreditCard,
  ListFilter,
  RotateCcw,
  Receipt,
  FileSpreadsheet,
  FileText,
  Download,
  X,
} from "lucide-react";

const PaymentHistoryDash = () => {
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [payments, setPayments] = useState([]);
  const [filteredPayments, setFilteredPayments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    className: "",
    teacherName: "",
    paymentDate: "",
  });
  const [openReceiptDialog, setOpenReceiptDialog] = useState(false);
  const [selectedReceipt, setSelectedReceipt] = useState(null);
  const [page, setPage] = useState(0);
  const [rowsPerPage] = useState(8);

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

  useEffect(() => {
    const fetchPaymentHistory = async () => {
      setLoading(true);
      try {
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
        const { data } = await axios.get(`${API_BASE}/api/auth/subscriptions/payment-history`, config);
        setPayments(data);
        setFilteredPayments(data);
      } catch (error) {
        console.error("Error fetching payment history:", error);
      } finally {
        setLoading(false);
      }
    };

    const handleResize = () => {
      const mobileView = window.innerWidth <= 768;
      setIsMobile(mobileView);
      setIsSidebarCollapsed(mobileView);
    };

    fetchPaymentHistory();
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

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

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

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

    if (filters.className) {
      filtered = filtered.filter(
        (payment) =>
          payment.classId?.subject?.toLowerCase().includes(filters.className.toLowerCase())
      );
    }

    if (filters.teacherName) {
      filtered = filtered.filter(
        (payment) =>
          payment.classId?.teacherId?.name
            ?.toLowerCase()
            .includes(filters.teacherName.toLowerCase())
      );
    }

    if (filters.paymentDate) {
      filtered = filtered.filter(
        (payment) =>
          new Date(payment.createdAt).toLocaleDateString() ===
          new Date(filters.paymentDate).toLocaleDateString()
      );
    }

    setFilteredPayments(filtered);
    setPage(0);
  };

  const clearFilters = () => {
    setFilters({ className: "", teacherName: "", paymentDate: "" });
    setFilteredPayments(payments);
    setPage(0);
  };

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleViewReceipt = async (subscriptionId) => {
    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      const config = { headers: { Authorization: `Bearer ${userInfo.token}` } };
      const { data } = await axios.get(`${API_BASE}/api/auth/subscriptions/receipt/${subscriptionId}`, config);
      setSelectedReceipt(data);
      setOpenReceiptDialog(true);
    } catch (error) {
      console.error("Error fetching receipt details:", error);
      alert("Failed to fetch receipt details. Please try again.");
    }
  };

  const handleCloseReceiptDialog = () => {
    setOpenReceiptDialog(false);
    setSelectedReceipt(null);
  };

  const handleDownloadCSV = () => {
    if (!selectedReceipt) return;
    const receiptData = [
      ["Invoice Number", selectedReceipt.invoiceNumber],
      ["Student Name", selectedReceipt.studentName],
      ["Student Email", selectedReceipt.studentEmail],
      ["Class Name", selectedReceipt.className],
      ["Teacher Name", selectedReceipt.teacherName],
      ["Original Fee", `$${selectedReceipt.originalFee}`],
      ["Discount Percentage", `${selectedReceipt.discountPercentage}%`],
      ["Final Fee", `$${selectedReceipt.finalFee}`],
      ["Payment Date", new Date(selectedReceipt.paymentDate).toLocaleDateString()],
      ["Payment Method", selectedReceipt.paymentMethod],
      ["Status", selectedReceipt.status],
    ];
    const csvContent = receiptData.map((row) => row.join(",")).join("\n");
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    saveAs(blob, `receipt-${selectedReceipt.invoiceNumber}.csv`);
  };

  const handleDownloadXLSX = () => {
    if (!selectedReceipt) return;
    const receiptData = [
      ["Invoice Number", selectedReceipt.invoiceNumber],
      ["Student Name", selectedReceipt.studentName],
      ["Student Email", selectedReceipt.studentEmail],
      ["Class Name", selectedReceipt.className],
      ["Teacher Name", selectedReceipt.teacherName],
      ["Original Fee", `$${selectedReceipt.originalFee}`],
      ["Discount Percentage", `${selectedReceipt.discountPercentage}%`],
      ["Final Fee", `$${selectedReceipt.finalFee}`],
      ["Payment Date", new Date(selectedReceipt.paymentDate).toLocaleDateString()],
      ["Payment Method", selectedReceipt.paymentMethod],
      ["Status", selectedReceipt.status],
    ];
    const ws = XLSX.utils.aoa_to_sheet(receiptData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Receipt");
    XLSX.writeFile(wb, `receipt-${selectedReceipt.invoiceNumber}.xlsx`);
  };

  const handleDownloadPDF = () => {
    if (!selectedReceipt) return;
    try {
      const doc = new jsPDF();
      if (!doc || typeof doc.setFontSize !== "function") {
        throw new Error("jsPDF instance is not properly initialized");
      }
      doc.addImage("/educonnetlogo.png", "PNG", 19, 17, 35, 30, undefined, "FAST");
      doc.setFontSize(24);
      doc.setFont("helvetica", "bold");
      doc.setTextColor(67, 56, 202);
      doc.text("RECEIPT", 105, 20, { align: "center" });
      doc.setFontSize(12);
      doc.setTextColor(0, 0, 0);
      doc.text(`Invoice Number: ${selectedReceipt.invoiceNumber}`, 20, 50);
      doc.text(`Student Name: ${selectedReceipt.studentName}`, 20, 60);
      doc.text(`Student Email: ${selectedReceipt.studentEmail}`, 20, 70);
      doc.text(`Class Name: ${selectedReceipt.className}`, 20, 80);
      doc.text(`Teacher Name: ${selectedReceipt.teacherName}`, 20, 90);
      doc.text(`Payment Date: ${new Date(selectedReceipt.paymentDate).toLocaleDateString()}`, 20, 100);
      doc.text(`Payment Method: ${selectedReceipt.paymentMethod}`, 20, 110);
      doc.text(`Status: ${selectedReceipt.status}`, 20, 120);
      doc.setFontSize(14);
      doc.text("Receipt Details", 20, 140);
      doc.setFontSize(12);
      doc.autoTable({
        startY: 150,
        head: [["Description", "Price"]],
        body: [
          [`Original Fee`, `$${selectedReceipt.originalFee}`],
          [`Discount (${selectedReceipt.discountPercentage}%)`, `-${(selectedReceipt.originalFee - selectedReceipt.finalFee).toFixed(2)}`],
          ["Final Fee", `$${selectedReceipt.finalFee}`],
        ],
        theme: "striped",
        headStyles: { fillColor: [79, 70, 229], textColor: [255, 255, 255] },
        bodyStyles: { textColor: [30, 41, 59] },
        alternateRowStyles: { fillColor: [248, 250, 252] },
      });
      doc.save(`receipt-${selectedReceipt.invoiceNumber}.pdf`);
    } catch (error) {
      console.error("Error generating PDF:", error);
      alert("Failed to generate PDF. Please try again.");
    }
  };

  const pathnames = location.pathname.split("/").filter((x) => x);
  const breadcrumbItems = pathnames.map((value, index) => {
    const last = index === pathnames.length - 1;
    const to = `/${pathnames.slice(0, index + 1).join("/")}`;
    const displayName = value
      .split("-")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");

    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 pageTitle =
    pathnames.length > 0
      ? pathnames[pathnames.length - 1]
          .split("-")
          .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
          .join(" ")
      : "Dashboard";

  useEffect(() => {
    document.title = `${pageTitle} - Student Dashboard - EduConnect`;
  }, [pageTitle]);

  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 barOffset = isSidebarCollapsed
    ? "ml-[60px] w-[calc(100%-60px)]"
    : "ml-[18%] w-[calc(100%-18%)] md:ml-[250px] md:w-[calc(100%-250px)]";

  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] h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <div className="mx-auto max-w-6xl">
              <Box sx={{ mb: 4 }}>
                <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" },
                  }}
                >
                  <CreditCard size={32} strokeWidth={1.75} className="text-indigo-600" aria-hidden />
                  Payment history
                </Typography>
                <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  View class subscriptions, fees paid, and download receipts
                </Typography>
              </Box>

              <Paper
                elevation={0}
                sx={{
                  p: { xs: 2, md: 3 },
                  mb: 3,
                  borderRadius: 3,
                  border: "1px solid rgba(15, 23, 42, 0.08)",
                  boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                  bgcolor: "#fff",
                }}
              >
                <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2.5 }}>
                  <ListFilter size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Filter payments
                  </Typography>
                </Box>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={4}>
                    <TextField
                      fullWidth
                      label="Class name"
                      name="className"
                      value={filters.className}
                      onChange={handleFilterChange}
                      variant="outlined"
                      size="small"
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Search size={18} strokeWidth={1.75} className="text-slate-400" />
                          </InputAdornment>
                        ),
                      }}
                      sx={fieldSx}
                    />
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <TextField
                      fullWidth
                      label="Teacher name"
                      name="teacherName"
                      value={filters.teacherName}
                      onChange={handleFilterChange}
                      variant="outlined"
                      size="small"
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <User size={18} strokeWidth={1.75} className="text-slate-400" />
                          </InputAdornment>
                        ),
                      }}
                      sx={fieldSx}
                    />
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <TextField
                      fullWidth
                      label="Payment date"
                      name="paymentDate"
                      type="date"
                      value={filters.paymentDate}
                      onChange={handleFilterChange}
                      InputLabelProps={{ shrink: true }}
                      variant="outlined"
                      size="small"
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Calendar size={18} strokeWidth={1.75} className="text-slate-400" />
                          </InputAdornment>
                        ),
                      }}
                      sx={fieldSx}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1.5, justifyContent: "flex-end" }}>
                      <Button
                        variant="contained"
                        disableElevation
                        onClick={applyFilters}
                        startIcon={<ListFilter size={18} strokeWidth={1.75} />}
                        sx={{
                          borderRadius: 2,
                          px: 2.5,
                          py: 1,
                          textTransform: "none",
                          fontWeight: 600,
                          bgcolor: "rgb(79 70 229)",
                          boxShadow: "none",
                          "&:hover": { bgcolor: "rgb(67 56 202)", boxShadow: "0 2px 8px rgba(79, 70, 229, 0.35)" },
                        }}
                      >
                        Apply filters
                      </Button>
                      <Button
                        variant="outlined"
                        disableElevation
                        onClick={clearFilters}
                        startIcon={<RotateCcw size={18} strokeWidth={1.75} />}
                        sx={{
                          borderRadius: 2,
                          px: 2.5,
                          py: 1,
                          textTransform: "none",
                          fontWeight: 600,
                          borderColor: "rgba(15, 23, 42, 0.12)",
                          color: "rgb(51 65 85)",
                          borderWidth: 1.5,
                          "&:hover": {
                            borderWidth: 1.5,
                            borderColor: "rgba(15, 23, 42, 0.2)",
                            bgcolor: "rgba(15, 23, 42, 0.04)",
                          },
                        }}
                      >
                        Reset
                      </Button>
                    </Box>
                  </Grid>
                </Grid>
              </Paper>

              {loading ? (
                <Paper elevation={0} sx={{ borderRadius: 3, overflow: "hidden", border: "1px solid rgba(15, 23, 42, 0.08)" }}>
                  {[1, 2, 3, 4, 5].map((i) => (
                    <Skeleton key={i} variant="rectangular" height={56} sx={{ mb: 0.5 }} animation="wave" />
                  ))}
                </Paper>
              ) : filteredPayments.length === 0 ? (
                <Paper
                  elevation={0}
                  sx={{
                    py: 8,
                    px: 3,
                    textAlign: "center",
                    borderRadius: 3,
                    border: "1px dashed rgba(148, 163, 184, 0.6)",
                    bgcolor: "#fff",
                  }}
                >
                  <Receipt size={48} strokeWidth={1.25} className="mx-auto mb-3 text-slate-300" />
                  <Typography sx={{ fontWeight: 700, color: "rgb(15 23 42)", mb: 1 }}>
                    No payments found
                  </Typography>
                  <Typography sx={{ color: "rgb(100 116 139)", maxWidth: 360, mx: "auto" }}>
                    {payments.length === 0
                      ? "You do not have any payment records yet."
                      : "Try adjusting filters to see more results."}
                  </Typography>
                </Paper>
              ) : (
                <>
                  <TableContainer
                    component={Paper}
                    elevation={0}
                    sx={{
                      borderRadius: 3,
                      border: "1px solid rgba(15, 23, 42, 0.08)",
                      boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                      overflow: "hidden",
                    }}
                  >
                    <Table size="medium">
                      <TableHead>
                        <TableRow sx={{ bgcolor: "rgb(248 250 252)" }}>
                          {["Class", "Teacher", "Fee paid", "Date", ""].map((h) => (
                            <TableCell
                              key={h || "actions"}
                              sx={{
                                fontWeight: 700,
                                color: "rgb(51 65 85)",
                                fontSize: "0.75rem",
                                textTransform: "uppercase",
                                letterSpacing: "0.06em",
                                borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                                py: 2,
                              }}
                            >
                              {h}
                            </TableCell>
                          ))}
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {filteredPayments.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((payment) => (
                          <TableRow
                            key={payment._id}
                            hover
                            sx={{
                              "&:last-child td": { borderBottom: 0 },
                              "& td": {
                                borderBottom: "1px solid rgba(15, 23, 42, 0.06)",
                                py: 2,
                                color: "rgb(30 41 59)",
                                fontSize: "0.9375rem",
                              },
                            }}
                          >
                            <TableCell sx={{ fontWeight: 600 }}>{payment.classId?.subject ?? "—"}</TableCell>
                            <TableCell>{payment.classId?.teacherId?.name ?? "—"}</TableCell>
                            <TableCell>
                              <Chip
                                label={`$${payment.feePaid}`}
                                size="small"
                                sx={{
                                  fontWeight: 700,
                                  bgcolor: "rgba(79, 70, 229, 0.1)",
                                  color: "rgb(67 56 202)",
                                  border: "none",
                                }}
                              />
                            </TableCell>
                            <TableCell sx={{ color: "rgb(100 116 139)" }}>
                              {new Date(payment.createdAt).toLocaleDateString(undefined, {
                                year: "numeric",
                                month: "short",
                                day: "numeric",
                              })}
                            </TableCell>
                            <TableCell align="right">
                              <Button
                                variant="contained"
                                disableElevation
                                size="small"
                                onClick={() => handleViewReceipt(payment._id)}
                                startIcon={<Receipt size={16} strokeWidth={1.75} />}
                                sx={{
                                  borderRadius: 2,
                                  textTransform: "none",
                                  fontWeight: 600,
                                  px: 2,
                                  bgcolor: "rgb(79 70 229)",
                                  boxShadow: "none",
                                  "&:hover": { bgcolor: "rgb(67 56 202)" },
                                }}
                              >
                                Receipt
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                  <TablePagination
                    component="div"
                    count={filteredPayments.length}
                    page={page}
                    onPageChange={handleChangePage}
                    rowsPerPage={rowsPerPage}
                    rowsPerPageOptions={[]}
                    labelDisplayedRows={({ from, to, count }) => `${from}–${to} of ${count}`}
                    sx={{
                      borderTop: "1px solid rgba(15, 23, 42, 0.08)",
                      bgcolor: "#fff",
                      borderRadius: "0 0 12px 12px",
                      "& .MuiTablePagination-toolbar": { px: 2, minHeight: 52 },
                      "& .MuiTablePagination-displayedRows": { fontSize: "0.875rem", color: "rgb(100 116 139)" },
                      "& .MuiIconButton-root": { color: "rgb(79 70 229)" },
                    }}
                  />
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      <Dialog
        open={openReceiptDialog}
        onClose={handleCloseReceiptDialog}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          elevation: 0,
          sx: {
            borderRadius: 3,
            border: "1px solid rgba(15, 23, 42, 0.08)",
            boxShadow: "0 25px 50px -12px rgba(15, 23, 42, 0.25)",
          },
        }}
      >
        <DialogTitle
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            py: 2,
            px: 3,
            borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
            bgcolor: "rgb(248 250 252)",
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: 1.25 }}>
            <Receipt size={22} strokeWidth={1.75} className="text-indigo-600" />
            <Typography variant="h6" sx={{ fontWeight: 700, color: "rgb(15 23 42)", fontSize: "1.1rem" }}>
              Receipt
            </Typography>
          </Box>
          <Button
            size="small"
            onClick={handleCloseReceiptDialog}
            sx={{ minWidth: 0, p: 0.75, color: "rgb(100 116 139)" }}
            aria-label="Close"
          >
            <X size={20} strokeWidth={1.75} />
          </Button>
        </DialogTitle>
        <DialogContent sx={{ px: 3, py: 3 }}>
          {selectedReceipt && (
            <Box>
              <Box sx={{ display: "flex", justifyContent: "center", mb: 2 }}>
                <img
                  src="/educonnetlogo.png"
                  alt="EduConnect"
                  style={{ width: 96, height: "auto" }}
                  onError={(e) => {
                    e.target.style.display = "none";
                  }}
                />
              </Box>
              <Divider sx={{ mb: 2, borderColor: "rgba(15, 23, 42, 0.08)" }} />
              <Grid container spacing={1.5} sx={{ mb: 2 }}>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Invoice
                  </Typography>
                  <Typography sx={{ fontWeight: 600, color: "rgb(15 23 42)" }}>{selectedReceipt.invoiceNumber}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Date
                  </Typography>
                  <Typography sx={{ fontWeight: 600, color: "rgb(15 23 42)" }}>
                    {new Date(selectedReceipt.paymentDate).toLocaleDateString()}
                  </Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Student
                  </Typography>
                  <Typography sx={{ color: "rgb(30 41 59)" }}>{selectedReceipt.studentName}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Email
                  </Typography>
                  <Typography sx={{ color: "rgb(30 41 59)", wordBreak: "break-all" }}>{selectedReceipt.studentEmail}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Class
                  </Typography>
                  <Typography sx={{ color: "rgb(30 41 59)" }}>{selectedReceipt.className}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Teacher
                  </Typography>
                  <Typography sx={{ color: "rgb(30 41 59)" }}>{selectedReceipt.teacherName}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Method
                  </Typography>
                  <Typography sx={{ color: "rgb(30 41 59)" }}>{selectedReceipt.paymentMethod}</Typography>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <Typography variant="caption" sx={{ color: "rgb(100 116 139)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                    Status
                  </Typography>
                  <Chip label={selectedReceipt.status} size="small" sx={{ mt: 0.5, fontWeight: 600 }} color="primary" variant="outlined" />
                </Grid>
              </Grid>
              <Typography sx={{ fontWeight: 700, mb: 1, color: "rgb(15 23 42)" }}>Line items</Typography>
              <TableContainer
                component={Paper}
                elevation={0}
                sx={{ border: "1px solid rgba(15, 23, 42, 0.08)", borderRadius: 2, overflow: "hidden" }}
              >
                <Table size="small">
                  <TableHead>
                    <TableRow sx={{ bgcolor: "rgb(248 250 252)" }}>
                      <TableCell sx={{ fontWeight: 700, color: "rgb(51 65 85)", fontSize: "0.75rem" }}>Description</TableCell>
                      <TableCell align="right" sx={{ fontWeight: 700, color: "rgb(51 65 85)", fontSize: "0.75rem" }}>
                        Amount
                      </TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    <TableRow>
                      <TableCell>Original fee</TableCell>
                      <TableCell align="right">${selectedReceipt.originalFee}</TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell>Discount ({selectedReceipt.discountPercentage}%)</TableCell>
                      <TableCell align="right">-${(selectedReceipt.originalFee - selectedReceipt.finalFee).toFixed(2)}</TableCell>
                    </TableRow>
                    <TableRow sx={{ bgcolor: "rgba(79, 70, 229, 0.06)" }}>
                      <TableCell sx={{ fontWeight: 700 }}>Final fee</TableCell>
                      <TableCell align="right" sx={{ fontWeight: 700, color: "rgb(67 56 202)" }}>
                        ${selectedReceipt.finalFee}
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </TableContainer>
            </Box>
          )}
        </DialogContent>
        <DialogActions
          sx={{
            flexWrap: "wrap",
            gap: 1,
            px: 3,
            py: 2,
            borderTop: "1px solid rgba(15, 23, 42, 0.08)",
            bgcolor: "rgb(248 250 252)",
          }}
        >
          <Button
            onClick={handleDownloadCSV}
            variant="outlined"
            size="small"
            startIcon={<FileText size={16} strokeWidth={1.75} />}
            sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2, borderWidth: 1.5 }}
          >
            CSV
          </Button>
          <Button
            onClick={handleDownloadXLSX}
            variant="outlined"
            size="small"
            startIcon={<FileSpreadsheet size={16} strokeWidth={1.75} />}
            sx={{ textTransform: "none", fontWeight: 600, borderRadius: 2, borderWidth: 1.5 }}
          >
            Excel
          </Button>
          <Button
            onClick={handleDownloadPDF}
            variant="contained"
            disableElevation
            size="small"
            startIcon={<Download size={16} strokeWidth={1.75} />}
            sx={{
              textTransform: "none",
              fontWeight: 600,
              borderRadius: 2,
              bgcolor: "rgb(79 70 229)",
              "&:hover": { bgcolor: "rgb(67 56 202)" },
            }}
          >
            PDF
          </Button>
          <Box sx={{ flexGrow: 1 }} />
          <Button onClick={handleCloseReceiptDialog} sx={{ textTransform: "none", fontWeight: 600, color: "rgb(100 116 139)" }}>
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default PaymentHistoryDash;
