"use client";

import React, { useState, useEffect } from "react";
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  TextField,
  MenuItem,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  CircularProgress,
  useMediaQuery,
  useTheme,
  Tooltip,
  Chip,
  Grid,
  FormControl,
  InputLabel,
  Snackbar,
  Select,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Divider,
} from "@mui/material";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterLuxon } from "@mui/x-date-pickers/AdapterLuxon";
import { DateTime } from "luxon";
import {
  Search as SearchIcon,
  FilterAlt as FilterIcon,
  FileDownload as ExportIcon,
  Visibility as ViewIcon,
  CheckCircle as SuccessIcon,
} from "@mui/icons-material";
import * as XLSX from "xlsx";

interface Transaction {
  _id: string;
  type: string;
  amount: number;
  balanceBefore: number;
  balanceAfter: number;
  status: string;
  userId?: string;
  userEmail: string;
  referenceId: string;
  createdAt: string;
  refund?: boolean;
  fundingType?: string;
  fundingSource?: string;
  planType?: string;
  plansize?: string;
  mobileNumber?: number;
  network?: string;
  discoName?: string;
  meterNumber?: number;
  token?: string;
  customerName?: string;
  iucOrSmartcardNumber?: number;
  provider?: string;
  cablePlan?: string;
  airtimeType?: string;
  buyingPrice?: number;
  bypass?: boolean;
  customerPhone?: number;
  meterType?: string;
  request_id?: string;
  customerAddress?: string;
  medium?: string;
  action?: string;
}

const statusColors: Record<string, "success" | "error" | "warning" | "info"> = {
  Successful: "success",
  Failed: "error",
  Pending: "warning",
};

const typeLabels: Record<string, string> = {
  CableSubscription: "Cable Subscription",
  BillPayment: "Bill Payment",
  ManualFunding: "Manual Funding",
  AutomaticFunding: "Auto Funding",
  DataTransaction: "Data",
  AirtimeTransaction: "Airtime",
  WithdrawalTransaction: "Withdrawal",
  ReferalBonus: "Referral Bonus",
  RefundTransaction: "Refund",
};

const headerConfigs: Record<
  string,
  { label: string; key: string; align?: "left" | "right" | "center" }[]
> = {
  default: [
    { label: "Reference ID", key: "referenceId", align: "left" },
    { label: "Type", key: "type", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Status", key: "status", align: "left" },
    { label: "Date", key: "createdAt", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  DataTransaction: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "Network", key: "network", align: "left" },
    { label: "Plan Type", key: "planType", align: "left" },
    { label: "Mobile", key: "mobileNumber", align: "left" },
    { label: "Plan Size", key: "plansize", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Status", key: "status", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  AirtimeTransaction: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "Airtime Type", key: "airtimeType", align: "left" },
    { label: "Network", key: "network", align: "left" },
    { label: "Mobile", key: "mobileNumber", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Buying Price", key: "buyingPrice", align: "right" },
    { label: "Status", key: "status", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  CableSubscription: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "Provider", key: "provider", align: "left" },
    { label: "Smartcard", key: "iucOrSmartcardNumber", align: "left" },
    { label: "Plan", key: "cablePlan", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Status", key: "status", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  BillPayment: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "Disco", key: "discoName", align: "left" },
    { label: "Meter No", key: "meterNumber", align: "left" },
    { label: "Customer", key: "customerName", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Token", key: "token", align: "left" },
    { label: "Status", key: "status", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  ManualFunding: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "User ID", key: "userId", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Method", key: "fundingSource", align: "left" },
    { label: "Status", key: "status", align: "left" },
    { label: "Date", key: "createdAt", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  AutomaticFunding: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "User ID", key: "userId", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Type", key: "fundingType", align: "left" },
    { label: "Status", key: "status", align: "left" },
    { label: "Date", key: "createdAt", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
  WithdrawalTransaction: [
    { label: "Reference", key: "referenceId", align: "left" },
    { label: "User Email", key: "userEmail", align: "left" },
    { label: "User ID", key: "userId", align: "left" },
    { label: "Amount", key: "amount", align: "right" },
    { label: "Status", key: "status", align: "left" },
    { label: "Date", key: "createdAt", align: "left" },
    { label: "Actions", key: "actions", align: "center" },
  ],
};

export default function TransactionsPage() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [snackbarSeverity, setSnackbarSeverity] = useState<
    "success" | "error" | "warning" | "info"
  >("info");

  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [total, setTotal] = useState(0);
  const [filterOpen, setFilterOpen] = useState(false);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedTransaction, setSelectedTransaction] =
    useState<Transaction | null>(null);
  const [refundLoading, setRefundLoading] = useState(false);
  const [successsLoading, setSuccessLoading] = useState(false);
  const [exportDialogOpen, setExportDialogOpen] = useState(false);
  const [exportStartDate, setExportStartDate] = useState<DateTime | null>(null);
  const [exportEndDate, setExportEndDate] = useState<DateTime | null>(null);
  const [exportLoading, setExportLoading] = useState(false);

  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [typeFilter, setTypeFilter] = useState<string>("");
  const [startDate, setStartDate] = useState<DateTime | null>(null);
  const [endDate, setEndDate] = useState<DateTime | null>(null);

  const showSnackbar = (
    message: string,
    severity: "success" | "error" | "warning" | "info" = "info"
  ) => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  const getHeaders = () => {
    if (typeFilter && headerConfigs[typeFilter]) {
      return headerConfigs[typeFilter];
    }
    return headerConfigs.default;
  };

  const fetchTransactions = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      params.append("page", (page + 1).toString());
      params.append("limit", rowsPerPage.toString());

      if (statusFilter) params.append("status", statusFilter);
      if (typeFilter) params.append("type", typeFilter);
      if (startDate) params.append("startDate", startDate.toISO() ?? "");
      if (endDate) params.append("endDate", endDate.toISO() ?? "");
      if (searchTerm) {
        if (searchTerm.startsWith("REF") || searchTerm.length >= 10) {
          params.append("referenceId", searchTerm);
        } else {
          params.append("userId", searchTerm);
        }
      }

      const response = await fetch(
        `/api/adminapi/transactions?${params.toString()}`
      );
      const data = await response.json();

      if (response.ok) {
        setTransactions(data.transactions);
        setTotal(data.pagination?.total || data.transactions.length);
      } else {
        throw new Error(data.message || "Failed to fetch transactions");
      }
    } catch (error) {
      console.error("Error fetching transactions:", error);
      showSnackbar(
        error instanceof Error ? error.message : "Failed to fetch transactions",
        "error"
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTransactions();
  }, [
    page,
    rowsPerPage,
    statusFilter,
    typeFilter,
    startDate,
    endDate,
    searchTerm,
  ]);

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

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleResetFilters = () => {
    setStatusFilter("");
    setTypeFilter("");
    setStartDate(null);
    setEndDate(null);
    setSearchTerm("");
    setPage(0);
  };

  const formatAmount = (amount: number) => {
    return new Intl.NumberFormat("en-NG", {
      style: "currency",
      currency: "NGN",
    }).format(amount);
  };

  const formatFieldValue = (key: string, value: any) => {
    if (value === undefined || value === null) return "N/A";

    switch (key) {
      case "amount":
      case "balanceBefore":
      case "balanceAfter":
      case "buyingPrice":
        return formatAmount(value);
      case "createdAt":
        return DateTime.fromISO(value).toLocaleString(DateTime.DATETIME_MED);
      case "status":
        return (
          <Chip
            label={value}
            color={statusColors[value] || "default"}
            size="small"
          />
        );
      case "type":
        return typeLabels[value] || value;
      case "refund":
        return value ? "Yes" : "No";
      case "mobileNumber":
      case "iucOrSmartcardNumber":
      case "meterNumber":
      case "customerPhone":
        return value.toString();
      default:
        return value.toString();
    }
  };

  const renderTableCell = (transaction: Transaction, key: string) => {
    if (key === "actions") {
      return (
        <Tooltip title="View transaction details">
          <IconButton
            onClick={() => {
              setSelectedTransaction(transaction);
              setDetailDialogOpen(true);
            }}
            color="primary"
          >
            <ViewIcon />
          </IconButton>
        </Tooltip>
      );
    }

    return formatFieldValue(key, transaction[key as keyof Transaction]);
  };

  // const handleViewDetail = (transaction: Transaction) => {
  //   setSelectedTransaction(transaction);
  //   setDetailDialogOpen(true);
  // };

  const handleRefundToggle = async () => {
    if (!selectedTransaction || selectedTransaction.refund) return;

    setRefundLoading(true);
    try {
      const response = await fetch("/api/adminapi/transactions/refund", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          transactionId: selectedTransaction._id,
          referenceId: selectedTransaction.referenceId,
          userId: selectedTransaction.userId,
          amount: selectedTransaction.amount,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        showSnackbar(
          data.message || "Refund processed successfully",
          "success"
        );
        fetchTransactions(); // Refresh the list
        setDetailDialogOpen(false);
      } else {
        throw new Error(data.message || "Failed to process refund");
      }
    } catch (error) {
      console.error("Error processing refund:", error);
      showSnackbar(
        error instanceof Error ? error.message : "Failed to process refund",
        "error"
      );
    } finally {
      setRefundLoading(false);
    }
  };
  const handleSuccessToggle = async () => {
    if (!selectedTransaction || selectedTransaction.status !== "Pending")
      return;

    setSuccessLoading(true);
    try {
      const response = await fetch("/api/adminapi/transactions/success", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          transactionId: selectedTransaction._id,
          referenceId: selectedTransaction.referenceId,
          userId: selectedTransaction.userId,
          amount: selectedTransaction.amount,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        showSnackbar(
          data.message || "Transaction marked as successful",
          "success"
        );
        fetchTransactions(); // Refresh the list
        setDetailDialogOpen(false);
      } else {
        throw new Error(
          data.message || "Failed to mark transaction as successful"
        );
      }
    } catch (error) {
      console.error("Error marking transaction as successful:", error);
      showSnackbar(
        error instanceof Error
          ? error.message
          : "Failed to mark transaction as successful",
        "error"
      );
    } finally {
      setSuccessLoading(false);
    }
  };

  const handleExport = async () => {
    setExportLoading(true);
    try {
      // Get all transactions for export (without pagination)
      const exportParams = new URLSearchParams();
      if (statusFilter) exportParams.append("status", statusFilter);
      if (typeFilter) exportParams.append("type", typeFilter);
      if (exportStartDate)
        exportParams.append("startDate", exportStartDate.toISO() ?? "");
      if (exportEndDate)
        exportParams.append("endDate", exportEndDate.toISO() ?? "");
      if (searchTerm) {
        if (searchTerm.startsWith("REF") || searchTerm.length >= 10) {
          exportParams.append("referenceId", searchTerm);
        } else {
          exportParams.append("userId", searchTerm);
        }
      }
      exportParams.append("limit", "10000"); // Get all matching records

      const response = await fetch(
        `/api/adminapi/transactions?${exportParams.toString()}`
      );
      const data = await response.json();

      if (!response.ok) {
        throw new Error(
          data.message || "Failed to fetch transactions for export"
        );
      }

      const exportData = data.transactions.map((tx: Transaction) => ({
        "Reference ID": tx.referenceId,
        Type: typeLabels[tx.type] || tx.type,
        Amount: tx.amount,
        Status: tx.status,
        Date: DateTime.fromISO(tx.createdAt).toLocaleString(
          DateTime.DATETIME_MED
        ),
        "User ID": tx.userId || "N/A",
        Refunded: tx.refund ? "Yes" : "No",
        ...(tx.type === "DataTransaction" && {
          Network: tx.network,
          "Plan Type": tx.planType,
          "Mobile Number": tx.mobileNumber,
          "Plan Size": tx.plansize,
        }),
        ...(tx.type === "AirtimeTransaction" && {
          "Airtime Type": tx.airtimeType,
          "Buying Price": tx.buyingPrice,
        }),
        ...(tx.type === "CableSubscription" && {
          Provider: tx.provider,
          "Smartcard Number": tx.iucOrSmartcardNumber,
          Plan: tx.cablePlan,
        }),
        ...(tx.type === "BillPayment" && {
          Disco: tx.discoName,
          "Meter Number": tx.meterNumber,
          Customer: tx.customerName,
          Token: tx.token,
        }),
        ...(tx.type === "ManualFunding" && {
          "Funding Source": tx.fundingSource,
        }),
        ...(tx.type === "AutomaticFunding" && {
          "Funding Type": tx.fundingType,
        }),
      }));

      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Transactions");

      const dateRange =
        exportStartDate && exportEndDate
          ? `${exportStartDate.toFormat(
              "yyyy-MM-dd"
            )}_to_${exportEndDate.toFormat("yyyy-MM-dd")}`
          : "all_transactions";

      XLSX.writeFile(workbook, `transactions_${dateRange}.xlsx`);
      showSnackbar("Export completed successfully", "success");
      setExportDialogOpen(false);
    } catch (error) {
      console.error("Error exporting transactions:", error);
      showSnackbar(
        error instanceof Error ? error.message : "Error exporting transactions",
        "error"
      );
    } finally {
      setExportLoading(false);
    }
  };

  const getTransactionDetails = (transaction: Transaction) => {
    const commonFields = [
      { label: "Reference ID", value: transaction.referenceId },
      {
        label: "Type",
        value: typeLabels[transaction.type] || transaction.type,
      },
      { label: "Amount", value: formatAmount(transaction.amount) },
      { label: "Status", value: transaction.status },
      {
        label: "Date",
        value: formatFieldValue("createdAt", transaction.createdAt),
      },
      { label: "User Email", value: transaction.userEmail || "N/A" },
      { label: "User ID", value: transaction.userId || "N/A" },
      {
        label: "Balance Before",
        value: formatAmount(transaction.balanceBefore),
      },
      { label: "Balance After", value: formatAmount(transaction.balanceAfter) },
      { label: "Refunded", value: transaction.refund ? "Yes" : "No" },
    ];

    const typeSpecificFields = [];

    switch (transaction.type) {
      case "DataTransaction":
        typeSpecificFields.push(
          { label: "Network", value: transaction.network || "N/A" },
          { label: "Plan Type", value: transaction.planType || "N/A" },
          { label: "Mobile Number", value: transaction.mobileNumber || "N/A" },
          { label: "Plan Size", value: transaction.plansize || "N/A" },
          { label: "Medium", value: transaction.medium || "N/A" }
        );
        break;
      case "AirtimeTransaction":
        typeSpecificFields.push(
          { label: "Airtime Type", value: transaction.airtimeType || "N/A" },
          { label: "Network", value: transaction.network || "N/A" },
          {
            label: "Buying Price",
            value: formatAmount(transaction.buyingPrice || 0),
          }
        );
        break;
      case "CableSubscription":
        typeSpecificFields.push(
          { label: "Provider", value: transaction.provider || "N/A" },
          {
            label: "Smartcard Number",
            value: transaction.iucOrSmartcardNumber || "N/A",
          },
          { label: "Plan", value: transaction.cablePlan || "N/A" },
          { label: "Action", value: transaction.action || "N/A" },
          { label: "Request ID", value: transaction.request_id || "N/A" }
        );
        break;
      case "BillPayment":
        typeSpecificFields.push(
          { label: "Disco", value: transaction.discoName || "N/A" },
          { label: "Meter Number", value: transaction.meterNumber || "N/A" },
          { label: "Customer Name", value: transaction.customerName || "N/A" },
          {
            label: "Customer Phone",
            value: transaction.customerPhone || "N/A",
          },
          {
            label: "Customer Address",
            value: transaction.customerAddress || "N/A",
          },
          { label: "Meter Type", value: transaction.meterType || "N/A" },
          { label: "Token", value: transaction.token || "N/A" }
        );
        break;
      case "ManualFunding":
        typeSpecificFields.push(
          {
            label: "Funding Source",
            value: transaction.fundingSource || "N/A",
          },
          { label: "Bypass", value: transaction.bypass ? "Yes" : "No" }
        );
        break;
      case "AutomaticFunding":
        typeSpecificFields.push({
          label: "Funding Type",
          value: transaction.fundingType || "N/A",
        });
        break;
      case "WithdrawalTransaction":
        typeSpecificFields
          .push
          // Add any withdrawal-specific fields here
          ();
        break;
    }

    return [...commonFields, ...typeSpecificFields];
  };

  return (
    <LocalizationProvider dateAdapter={AdapterLuxon}>
      <Box sx={{ p: isMobile ? 1 : 3 }}>
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 3,
          }}
        >
          <Typography variant="h5" component="h1">
            Transactions
          </Typography>

          <Box sx={{ display: "flex", gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<ExportIcon />}
              onClick={() => setExportDialogOpen(true)}
              size={isMobile ? "small" : "medium"}
            >
              {isMobile ? "Export" : "Export to Excel"}
            </Button>

            <Button
              variant="outlined"
              startIcon={<FilterIcon />}
              onClick={() => setFilterOpen(true)}
              size={isMobile ? "small" : "medium"}
            >
              {isMobile ? "Filter" : "Filter Transactions"}
            </Button>
          </Box>
        </Box>

        <Paper sx={{ mb: 2, p: isMobile ? 1 : 2 }}>
          <TextField
            fullWidth
            variant="outlined"
            placeholder="Search by Reference ID or User ID..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            InputProps={{
              startAdornment: <SearchIcon color="action" sx={{ mr: 1 }} />,
            }}
            size={isMobile ? "small" : "medium"}
          />
        </Paper>

        <Paper sx={{ width: "100%", overflow: "hidden" }}>
          {loading ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
              <CircularProgress />
            </Box>
          ) : (
            <>
              <TableContainer sx={{ maxHeight: "calc(100vh - 300px)" }}>
                <Table
                  stickyHeader
                  aria-label="transactions table"
                  size={isMobile ? "small" : "medium"}
                >
                  <TableHead>
                    <TableRow>
                      {getHeaders().map((header) => (
                        <TableCell key={header.key} align={header.align}>
                          {header.label}
                        </TableCell>
                      ))}
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {transactions.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={getHeaders().length} align="center">
                          No transactions found
                        </TableCell>
                      </TableRow>
                    ) : (
                      transactions.map((transaction) => (
                        <TableRow key={transaction._id} hover>
                          {getHeaders().map((header) => (
                            <TableCell
                              key={`${transaction._id}-${header.key}`}
                              align={header.align}
                            >
                              {renderTableCell(transaction, header.key)}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TableContainer>

              <TablePagination
                rowsPerPageOptions={[5, 10, 25, 50]}
                component="div"
                count={total}
                rowsPerPage={rowsPerPage}
                page={page}
                onPageChange={handleChangePage}
                onRowsPerPageChange={handleChangeRowsPerPage}
                sx={{
                  "& .MuiTablePagination-toolbar": {
                    flexWrap: "wrap",
                    justifyContent: "center",
                  },
                }}
              />
            </>
          )}
        </Paper>

        {/* Filter Dialog */}
        <Dialog
          open={filterOpen}
          onClose={() => setFilterOpen(false)}
          fullWidth
          maxWidth="sm"
        >
          <DialogTitle>Filter Transactions</DialogTitle>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid size={{ xs: 12, sm: 6 }}>
                <FormControl fullWidth size="small">
                  <InputLabel>Status</InputLabel>
                  <Select
                    value={statusFilter}
                    label="Status"
                    onChange={(e) => setStatusFilter(e.target.value as string)}
                  >
                    <MenuItem value="">All Statuses</MenuItem>
                    <MenuItem value="Pending">Pending</MenuItem>
                    <MenuItem value="Successful">Successful</MenuItem>
                    <MenuItem value="Failed">Failed</MenuItem>
                  </Select>
                </FormControl>
              </Grid>

              <Grid size={{ xs: 12, sm: 6 }}>
                <FormControl fullWidth size="small">
                  <InputLabel>Type</InputLabel>
                  <Select
                    value={typeFilter}
                    label="Type"
                    onChange={(e) => setTypeFilter(e.target.value as string)}
                  >
                    <MenuItem value="">All Types</MenuItem>
                    {Object.entries(typeLabels).map(([value, label]) => (
                      <MenuItem key={value} value={value}>
                        {label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>

              <Grid size={{ xs: 12, sm: 6 }}>
                <DatePicker
                  label="Start Date"
                  value={startDate}
                  onChange={setStartDate}
                  slotProps={{ textField: { fullWidth: true, size: "small" } }}
                />
              </Grid>

              <Grid size={{ xs: 12, sm: 6 }}>
                <DatePicker
                  label="End Date"
                  value={endDate}
                  onChange={setEndDate}
                  slotProps={{ textField: { fullWidth: true, size: "small" } }}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleResetFilters} color="error">
              Reset Filters
            </Button>
            <Button onClick={() => setFilterOpen(false)} color="primary">
              Apply Filters
            </Button>
          </DialogActions>
        </Dialog>

        {/* Transaction Detail Dialog */}
        <Dialog
          open={detailDialogOpen}
          onClose={() => setDetailDialogOpen(false)}
          fullWidth
          maxWidth="md"
        >
          <DialogTitle>Transaction Details</DialogTitle>
          <DialogContent>
            {selectedTransaction && (
              <>
                <List>
                  {getTransactionDetails(selectedTransaction).map(
                    (field, index) => (
                      <React.Fragment key={index}>
                        <ListItem>
                          <ListItemText
                            primary={field.label}
                            secondary={field.value}
                            primaryTypographyProps={{ fontWeight: "bold" }}
                          />
                        </ListItem>
                        {index <
                          getTransactionDetails(selectedTransaction).length -
                            1 && <Divider component="li" />}
                      </React.Fragment>
                    )
                  )}
                </List>

                <Box
                  sx={{
                    mt: 2,
                    display: "flex",
                    justifyContent: "flex-end",
                    gap: 1,
                  }}
                >
                  {/* Show Mark as Successful button only for pending transactions */}
                  {selectedTransaction.status === "Pending" &&
                    selectedTransaction.refund !== true && (
                      <Tooltip title="Mark this transaction as successful">
                        <Button
                          variant="contained"
                          color="success"
                          onClick={handleSuccessToggle}
                          disabled={successsLoading}
                          startIcon={
                            successsLoading ? (
                              <CircularProgress size={20} />
                            ) : (
                              <SuccessIcon />
                            )
                          }
                        >
                          {successsLoading
                            ? "Processing..."
                            : "Mark as Successful"}
                        </Button>
                      </Tooltip>
                    )}

                  {/* Show Refund button for both Successful and Pending transactions */}
                  {(selectedTransaction.status === "Successful" ||
                    selectedTransaction.status === "Pending") &&
                    selectedTransaction.refund !== true && (
                      <Tooltip title="Refund this transaction">
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={handleRefundToggle}
                          disabled={refundLoading}
                          startIcon={
                            refundLoading ? (
                              <CircularProgress size={20} />
                            ) : null
                          }
                        >
                          {refundLoading ? "Processing..." : "Refund"}
                        </Button>
                      </Tooltip>
                    )}
                </Box>
              </>
            )}
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setDetailDialogOpen(false)} color="primary">
              Close
            </Button>
          </DialogActions>
        </Dialog>

        {/* Export Dialog */}
        <Dialog
          open={exportDialogOpen}
          onClose={() => setExportDialogOpen(false)}
        >
          <DialogTitle>Export Transactions</DialogTitle>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid size={{ xs: 12, sm: 6 }}>
                <DatePicker
                  label="Start Date"
                  value={exportStartDate}
                  onChange={setExportStartDate}
                  slotProps={{ textField: { fullWidth: true, size: "small" } }}
                />
              </Grid>

              <Grid size={{ xs: 12, sm: 6 }}>
                <DatePicker
                  label="End Date"
                  value={exportEndDate}
                  onChange={setExportEndDate}
                  slotProps={{ textField: { fullWidth: true, size: "small" } }}
                />
              </Grid>

              <Grid size={{ xs: 12 }}>
                <Typography variant="body2" color="text.secondary">
                  Export will include all transactions matching current filters{" "}
                  {exportStartDate && exportEndDate
                    ? `between ${exportStartDate.toFormat(
                        "yyyy-MM-dd"
                      )} and ${exportEndDate.toFormat("yyyy-MM-dd")}`
                    : ""}
                </Typography>
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() => setExportDialogOpen(false)}
              disabled={exportLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleExport}
              color="primary"
              variant="contained"
              disabled={exportLoading}
              startIcon={exportLoading ? <CircularProgress size={20} /> : null}
            >
              {exportLoading ? "Exporting..." : "Export"}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={4000}
        onClose={() => setSnackbarOpen(false)}
        message={snackbarMessage}
        anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
        ContentProps={{
          sx: {
            bgcolor:
              snackbarSeverity === "success"
                ? "success.main"
                : snackbarSeverity === "error"
                ? "error.main"
                : snackbarSeverity === "warning"
                ? "warning.main"
                : "info.main",
          },
        }}
      />
    </LocalizationProvider>
  );
}
