"use client";

import React, { useState, useEffect } from "react";
import {
  Typography,
  Container,
  Grid,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  Pagination,
  Snackbar,
  Alert,
  useMediaQuery,
  ThemeProvider,
  createTheme,
  Box,
  Chip,
  IconButton,
  Tooltip,
  TableSortLabel,
  Card,
  CardHeader,
  CardContent,
  Skeleton,
  Divider,
} from "@mui/material";
import {
  Search,
  FilterList,
  Refresh,
  Visibility,
  //   ArrowUpward,
  //   ArrowDownward,
} from "@mui/icons-material";
import TransactionDetailsModal from "@/app/dashboard/transactions/TransactionDetailsModal";

// Create a custom theme with modern colors
const theme = createTheme({
  palette: {
    primary: {
      main: "#3f51b5",
    },
    secondary: {
      main: "#f50057",
    },
    background: {
      default: "#f5f7fa",
    },
  },
  typography: {
    fontFamily: "'Inter', 'Roboto', sans-serif",
  },
});

const statusColors: Record<string, string> = {
  pending: "#ff9800",
  success: "#4caf50",
  failed: "#f44336",
  processing: "#2196f3",
};

const typeIcons: Record<string, string> = {
  DataTransaction: "📶",
  AirtimeTransaction: "📱",
  CableSubscription: "📺",
  BillPayment: "💡",
  ManualFunding: "💰",
  AutomaticFunding: "💳",
  WithdrawalTransaction: "🏧",
  ReferalBonus: "🎁",
};

const Transactions: React.FC = () => {
  const [transactions, setTransactions] = useState<any[]>([]);
  const [filteredTransactions, setFilteredTransactions] = useState<any[]>([]);
  const [filterType, setFilterType] = useState<string>("");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [page, setPage] = useState(1);
  const [rowsPerPage] = useState(10);
  const [order, setOrder] = useState<"asc" | "desc">("asc");
  const [orderBy, setOrderBy] = useState<string>("createdAt");
  const [selectedTransaction, setSelectedTransaction] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [refreshing, setRefreshing] = useState<boolean>(false);
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: "success" | "error" | "info";
  }>({ open: false, message: "", severity: "info" });
  const [userWalletBalance, setUserWalletBalance] = useState<number | null>(
    null
  );

  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.between("sm", "md"));

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

  const fetchTransactions = async () => {
    try {
      setLoading(true);
      //   await fetch("/api/updatependingtransaction", { method: "GET" });

      let url = "/api/adminapi/transactions/ausertransaction";
      if (searchQuery) {
        url += `?search=${encodeURIComponent(searchQuery)}`;
      }

      const response = await fetch(url);
      const data = await response.json();

      // Handle both old and new API response formats
      const transactionsData = data.transactions || data;
      setTransactions(transactionsData);
      setFilteredTransactions(transactionsData);

      // Set user wallet balance if available
      if (data.userWalletBalance !== undefined) {
        setUserWalletBalance(data.userWalletBalance);
      } else {
        setUserWalletBalance(null);
      }

      setSnackbar({
        open: true,
        message: "Transactions loaded successfully",
        severity: "success",
      });
    } catch (error) {
      setSnackbar({
        open: true,
        message: "Failed to fetch transactions",
        severity: "error",
      });
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const handleRefresh = () => {
    setRefreshing(true);
    fetchTransactions();
  };

  useEffect(() => {
    // Fetch transactions when search query changes
    if (searchQuery) {
      const timer = setTimeout(() => {
        fetchTransactions();
      }, 500); // Debounce search to avoid too many API calls
      return () => clearTimeout(timer);
    } else {
      fetchTransactions();
    }
  }, [searchQuery]);

  useEffect(() => {
    // Filter transactions by type on the client side
    let filtered = transactions;
    if (filterType) {
      filtered = filtered.filter(
        (transaction) => transaction.type === filterType
      );
    }
    setFilteredTransactions(filtered);
    setPage(1); // Reset to first page when filters change
  }, [filterType, transactions]);

  const handleSort = (property: string) => {
    const isAsc = orderBy === property && order === "asc";
    setOrder(isAsc ? "desc" : "asc");
    setOrderBy(property);
    setFilteredTransactions(
      [...filteredTransactions].sort((a, b) => {
        if (a[property] < b[property]) return isAsc ? -1 : 1;
        if (a[property] > b[property]) return isAsc ? 1 : -1;
        return 0;
      })
    );
  };

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

  const handleViewDetails = (transaction: any) => {
    setSelectedTransaction(transaction);
  };

  const formatDate = (dateString: string) => {
    const options: Intl.DateTimeFormatOptions = {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    };
    return new Date(dateString).toLocaleDateString(undefined, options);
  };

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

  return (
    <ThemeProvider theme={theme}>
      <Container
        maxWidth="xl"
        sx={{
          p: isMobile ? 1 : 3,
          backgroundColor: "background.default",
        }}
      >
        <Card
          sx={{
            mb: 3,
            boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.1)",
            borderRadius: "12px",
          }}
        >
          <CardHeader
            title={
              <Typography
                variant="h5"
                sx={{
                  fontWeight: 600,
                  fontSize: isMobile ? "1.25rem" : "1.5rem",
                }}
              >
                Transaction History
              </Typography>
            }
            action={
              <Tooltip title="Refresh transactions">
                <IconButton
                  onClick={handleRefresh}
                  color="primary"
                  disabled={refreshing}
                >
                  <Refresh sx={{ rotate: refreshing ? "360deg" : "0deg" }} />
                </IconButton>
              </Tooltip>
            }
          />
          <Divider />
          <CardContent>
            <Grid container spacing={2} alignItems="center">
              <Grid size={{ xs: 12, sm: 6, md: 4 }}>
                <FormControl fullWidth size={isMobile ? "small" : "medium"}>
                  <InputLabel>Transaction Type</InputLabel>
                  <Select
                    value={filterType}
                    onChange={(e) => setFilterType(e.target.value)}
                    label="Transaction Type"
                    startAdornment={
                      <FilterList color="action" sx={{ mr: 1, opacity: 0.6 }} />
                    }
                  >
                    <MenuItem value="">All Transactions</MenuItem>
                    <MenuItem value="DataTransaction">Data Purchase</MenuItem>
                    <MenuItem value="AirtimeTransaction">
                      Airtime Purchase
                    </MenuItem>
                    <MenuItem value="CableSubscription">
                      Cable Subscription
                    </MenuItem>
                    <MenuItem value="BillPayment">Electricity Bill</MenuItem>
                    <MenuItem value="ManualFunding">Manual Deposit</MenuItem>
                    <MenuItem value="AutomaticFunding">
                      Automatic Deposit
                    </MenuItem>
                    <MenuItem value="WithdrawalTransaction">
                      Withdrawal
                    </MenuItem>
                    <MenuItem value="ReferalBonus">Referral Bonus</MenuItem>
                  </Select>
                </FormControl>
              </Grid>

              <Grid size={{ xs: 12, sm: 6, md: 4 }}>
                <TextField
                  fullWidth
                  label="Search User"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  size={isMobile ? "small" : "medium"}
                  InputProps={{
                    startAdornment: (
                      <Search color="action" sx={{ mr: 1, opacity: 0.6 }} />
                    ),
                  }}
                />
              </Grid>

              <Grid size={{ xs: 12, md: 4 }}>
                <Box
                  display="flex"
                  flexWrap="wrap"
                  gap={1}
                  justifyContent={isMobile ? "flex-start" : "flex-end"}
                >
                  {userWalletBalance !== null && (
                    <Chip
                      label={`User Balance: ${formatAmount(userWalletBalance)}`}
                      variant="filled"
                      color="primary"
                    />
                  )}
                  <Chip
                    label={`Total: ${filteredTransactions.length}`}
                    variant="outlined"
                  />
                  <Chip
                    label={`Success: ${
                      filteredTransactions.filter(
                        (t) => t.status === "Successful"
                      ).length
                    }`}
                    variant="outlined"
                    color="success"
                  />
                  <Chip
                    label={`Pending: ${
                      filteredTransactions.filter((t) => t.status === "Pending")
                        .length
                    }`}
                    variant="outlined"
                    color="warning"
                  />
                  <Chip
                    label={`Failed: ${
                      filteredTransactions.filter((t) => t.status === "Failed")
                        .length
                    }`}
                    variant="outlined"
                    color="error"
                  />
                </Box>
              </Grid>
            </Grid>
          </CardContent>
        </Card>

        {loading ? (
          <Card>
            <CardContent>
              {[...Array(5)].map((_, index) => (
                <Skeleton
                  key={index}
                  variant="rectangular"
                  height={56}
                  sx={{ mb: 1 }}
                />
              ))}
            </CardContent>
          </Card>
        ) : (
          <>
            <TableContainer
              component={Paper}
              sx={{
                borderRadius: "12px",
                boxShadow: "none",
                border: "1px solid rgba(0, 0, 0, 0.12)",
                overflowX: "auto",
              }}
            >
              <Table sx={{ minWidth: 400 }} aria-label="transactions table">
                <TableHead>
                  <TableRow sx={{ backgroundColor: "primary.main" }}>
                    <TableCell sx={{ color: "common.white" }}>
                      <TableSortLabel
                        active={orderBy === "type"}
                        direction={orderBy === "type" ? order : "asc"}
                        onClick={() => handleSort("type")}
                        sx={{ color: "common.white !important" }}
                      >
                        Type
                      </TableSortLabel>
                    </TableCell>
                    <TableCell sx={{ color: "common.white" }}>
                      <TableSortLabel
                        active={orderBy === "amount"}
                        direction={orderBy === "amount" ? order : "asc"}
                        onClick={() => handleSort("amount")}
                        sx={{ color: "common.white !important" }}
                      >
                        Amount
                      </TableSortLabel>
                    </TableCell>
                    {!isMobile && (
                      <>
                        <TableCell sx={{ color: "common.white" }}>
                          <TableSortLabel
                            active={orderBy === "balanceBefore"}
                            direction={
                              orderBy === "balanceBefore" ? order : "asc"
                            }
                            onClick={() => handleSort("balanceBefore")}
                            sx={{ color: "common.white !important" }}
                          >
                            Previous Balance
                          </TableSortLabel>
                        </TableCell>
                        <TableCell sx={{ color: "common.white" }}>
                          <TableSortLabel
                            active={orderBy === "balanceAfter"}
                            direction={
                              orderBy === "balanceAfter" ? order : "asc"
                            }
                            onClick={() => handleSort("balanceAfter")}
                            sx={{ color: "common.white !important" }}
                          >
                            New Balance
                          </TableSortLabel>
                        </TableCell>
                      </>
                    )}
                    <TableCell sx={{ color: "common.white" }}>
                      <TableSortLabel
                        active={orderBy === "status"}
                        direction={orderBy === "status" ? order : "asc"}
                        onClick={() => handleSort("status")}
                        sx={{ color: "common.white !important" }}
                      >
                        Status
                      </TableSortLabel>
                    </TableCell>
                    {!isMobile && (
                      <TableCell sx={{ color: "common.white" }}>
                        <TableSortLabel
                          active={orderBy === "createdAt"}
                          direction={orderBy === "createdAt" ? order : "desc"}
                          onClick={() => handleSort("createdAt")}
                          sx={{ color: "common.white !important" }}
                        >
                          Date
                        </TableSortLabel>
                      </TableCell>
                    )}
                    <TableCell sx={{ color: "common.white" }}>
                      Actions
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredTransactions && filteredTransactions.length > 0 ? (
                    filteredTransactions
                      .slice((page - 1) * rowsPerPage, page * rowsPerPage)
                      .map((transaction) => (
                        <TableRow
                          key={transaction._id}
                          hover
                          sx={{
                            "&:nth-of-type(odd)": {
                              backgroundColor: "action.hover",
                            },
                          }}
                        >
                          <TableCell>
                            <Box display="flex" alignItems="center">
                              <span style={{ marginRight: 8 }}>
                                {typeIcons[transaction.type] || "📊"}
                              </span>
                              {isMobile
                                ? transaction.type.replace("Transaction", "")
                                : transaction.type}
                            </Box>
                          </TableCell>
                          <TableCell sx={{ fontWeight: 500 }}>
                            {formatAmount(transaction.amount)}
                          </TableCell>
                          {!isMobile && (
                            <>
                              <TableCell>
                                {formatAmount(transaction.balanceBefore)}
                              </TableCell>
                              <TableCell>
                                {formatAmount(transaction.balanceAfter)}
                              </TableCell>
                            </>
                          )}
                          <TableCell>
                            <Chip
                              label={transaction.status}
                              size="small"
                              sx={{
                                backgroundColor:
                                  statusColors[transaction.status] || "#9e9e9e",
                                color: "white",
                                fontWeight: 500,
                              }}
                            />
                          </TableCell>
                          {!isMobile && (
                            <TableCell>
                              {formatDate(transaction.createdAt)}
                            </TableCell>
                          )}
                          <TableCell>
                            <Tooltip title="View details">
                              <IconButton
                                onClick={() => handleViewDetails(transaction)}
                                size="small"
                                color="primary"
                              >
                                <Visibility />
                              </IconButton>
                            </Tooltip>
                          </TableCell>
                        </TableRow>
                      ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={isMobile ? 4 : 7}
                        sx={{ textAlign: "center", py: 4 }}
                      >
                        <Typography variant="body1" color="textSecondary">
                          No transactions found
                        </Typography>
                        {filterType || searchQuery ? (
                          <Button
                            onClick={() => {
                              setFilterType("");
                              setSearchQuery("");
                            }}
                            sx={{ mt: 1 }}
                          >
                            Clear filters
                          </Button>
                        ) : null}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>

            {filteredTransactions && filteredTransactions.length > 0 && (
              <Box
                display="flex"
                justifyContent="space-between"
                alignItems="center"
                mt={2}
                flexDirection={isMobile ? "column" : "row"}
              >
                <Typography variant="body2" color="textSecondary">
                  Showing {(page - 1) * rowsPerPage + 1} to{" "}
                  {Math.min(page * rowsPerPage, filteredTransactions.length)} of{" "}
                  {filteredTransactions.length} transactions
                </Typography>
                <Pagination
                  count={Math.ceil(filteredTransactions.length / rowsPerPage)}
                  page={page}
                  onChange={handleChangePage}
                  color="primary"
                  shape="rounded"
                  sx={{ mt: isMobile ? 2 : 0 }}
                />
              </Box>
            )}
          </>
        )}

        {selectedTransaction && (
          <TransactionDetailsModal
            transaction={selectedTransaction}
            onClose={() => setSelectedTransaction(null)}
          />
        )}

        <Snackbar
          open={snackbar.open}
          autoHideDuration={4000}
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        >
          <Alert
            severity={snackbar.severity}
            onClose={() => setSnackbar({ ...snackbar, open: false })}
            sx={{ boxShadow: theme.shadows[3] }}
          >
            {snackbar.message}
          </Alert>
        </Snackbar>
      </Container>
    </ThemeProvider>
  );
};

export default Transactions;
