// components/WalletManagement.tsx
"use client";
import React, { useState, useEffect } from "react";
import {
  Box,
  Tabs,
  Tab,
  TextField,
  Button,
  Typography,
  Modal,
  Paper,
  CircularProgress,
  Snackbar,
  Alert,
  Grid,
  Divider,
  List,
  ListItem,
  ListItemText,
  Avatar,
  Select,
  MenuItem,
  InputLabel,
  FormControl,
} from "@mui/material";
import {
  Search as SearchIcon,
  AccountBalanceWallet,
  AttachMoney,
} from "@mui/icons-material";

interface User {
  _id: string;
  name: string;
  email: string;
  mobileNumber: string;
  username: string;
  accountBalance: number;
  image?: string;
  role: "admin" | "user";
}

interface Transaction {
  _id: string;
  type: string;
  amount: number;
  balanceBefore: number;
  balanceAfter: number;
  status: string;
  userId: string;
  referenceId: string;
  createdAt: string;
  fundingType?: "Manual" | "Automatic";
  fundingSource?: "API" | "Admin";
}

const WalletManagement = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [searchQuery, setSearchQuery] = useState("");
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [amount, setAmount] = useState("");
  const [description, setDescription] = useState("");
  const [fundingType, setFundingType] = useState<"Manual" | "Automatic">(
    "Manual"
  );
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [transactionResult, setTransactionResult] =
    useState<Transaction | null>(null);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "success"
  );
  const [recentTransactions, setRecentTransactions] = useState<Transaction[]>(
    []
  );

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setActiveTab(newValue);
    resetForm();
  };

  const resetForm = () => {
    setSearchQuery("");
    setUsers([]);
    setSelectedUser(null);
    setAmount("");
    setDescription("");
    setFundingType("Manual");
    setTransactionResult(null);
  };

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;

    try {
      const response = await fetch("/api/adminapi/wallet/search-users", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ query: searchQuery }),
      });

      const data = await response.json();
      if (response.ok) {
        setUsers(data.users);
      } else {
        throw new Error(data.message || "Failed to search users");
      }
    } catch (error) {
      setSnackbarMessage(
        error instanceof Error ? error.message : "An error occurred"
      );
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

  const handleUserSelect = (user: User) => {
    setSelectedUser(user);
    setUsers([]);
  };

  const handleSubmit = () => {
    if (!selectedUser || !amount || isNaN(Number(amount))) return;
    setOpenConfirmModal(true);
  };

  const confirmTransaction = async () => {
    if (!selectedUser || !amount || isNaN(Number(amount))) return;

    setIsProcessing(true);
    setOpenConfirmModal(false);

    try {
      const endpoint =
        activeTab === 0
          ? "/api/adminapi/wallet/fund"
          : "/api/adminapi/wallet/withdraw";
      const response = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: selectedUser._id,
          amount: Number(amount),
          description,
          fundingType: activeTab === 0 ? fundingType : undefined,
        }),
      });

      const data = await response.json();
      if (response.ok) {
        setTransactionResult(data.transaction);
        setSelectedUser({ ...selectedUser, accountBalance: data.newBalance });
        setSnackbarMessage(
          data.message || "Transaction completed successfully"
        );
        setSnackbarSeverity("success");
        fetchRecentTransactions(selectedUser._id);
      } else {
        throw new Error(data.message || "Transaction failed");
      }
    } catch (error) {
      setSnackbarMessage(
        error instanceof Error ? error.message : "Transaction failed"
      );
      setSnackbarSeverity("error");
    } finally {
      setIsProcessing(false);
      setSnackbarOpen(true);
    }
  };

  const fetchRecentTransactions = async (userId: string) => {
    try {
      const response = await fetch(
        `/api/adminapi/wallet/transactions?userId=${userId}&type=${
          activeTab === 0
            ? "ManualFunding,AutomaticFunding"
            : "WithdrawalTransaction"
        }`
      );
      const data = await response.json();
      if (response.ok) {
        setRecentTransactions(data.transactions);
      }
    } catch (error) {
      console.error("Failed to fetch transactions", error);
    }
  };

  useEffect(() => {
    if (selectedUser) {
      fetchRecentTransactions(selectedUser._id);
    }
  }, [selectedUser, activeTab]);

  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        Wallet Management
      </Typography>

      <Paper sx={{ mb: 3 }}>
        <Tabs value={activeTab} onChange={handleTabChange} variant="fullWidth">
          <Tab label="Fund Wallet" icon={<AttachMoney />} />
          <Tab label="Withdraw Funds" icon={<AccountBalanceWallet />} />
        </Tabs>
      </Paper>

      <Grid container spacing={3}>
        <Grid size={{ xs: 12, md: 6 }}>
          <Paper sx={{ p: 3 }}>
            <Box sx={{ mb: 3 }}>
              <Typography variant="h6" gutterBottom>
                {activeTab === 0
                  ? "Fund User Wallet"
                  : "Withdraw from User Wallet"}
              </Typography>

              <Box sx={{ display: "flex", gap: 2, mb: 2 }}>
                <TextField
                  fullWidth
                  label="Search user by name, email, phone or username"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyPress={(e) => e.key === "Enter" && handleSearch()}
                />
                <Button
                  variant="contained"
                  onClick={handleSearch}
                  startIcon={<SearchIcon />}
                >
                  Search
                </Button>
              </Box>

              {users.length > 0 && (
                <Paper sx={{ maxHeight: 200, overflow: "auto", mb: 2 }}>
                  <List>
                    {users.map((user) => (
                      <ListItem
                        key={user._id}
                        component="button"
                        onClick={() => handleUserSelect(user)}
                        sx={{ "&:hover": { backgroundColor: "action.hover" } }}
                      >
                        <Avatar sx={{ mr: 2 }} src={user.image} alt={user.name}>
                          {user.name?.charAt(0).toUpperCase()}
                        </Avatar>
                        <ListItemText
                          primary={user.name || user.username}
                          secondary={`${user.email} • ${user.mobileNumber} • @${user.username}`}
                        />
                        <Typography variant="body2" color="text.secondary">
                          ₦{user.accountBalance?.toFixed(2)}
                        </Typography>
                      </ListItem>
                    ))}
                  </List>
                </Paper>
              )}

              {selectedUser && (
                <>
                  <Box
                    sx={{
                      p: 2,
                      mb: 2,
                      backgroundColor: "background.paper",
                      borderRadius: 1,
                    }}
                  >
                    <Typography variant="subtitle1">
                      Selected User:{" "}
                      <strong>
                        {selectedUser.name || selectedUser.username}
                      </strong>
                    </Typography>
                    <Typography variant="body2">
                      Email: {selectedUser.email} • Wallet: ₦
                      {selectedUser.accountBalance?.toFixed(2)}
                    </Typography>
                  </Box>

                  <TextField
                    fullWidth
                    label="Amount"
                    type="number"
                    value={amount}
                    onChange={(e) => {
                      const input = e.target.value;
                      if (parseFloat(input) >= 0 || input === "") {
                        setAmount(input);
                      }
                    }}
                    sx={{ mb: 2 }}
                    InputProps={{
                      startAdornment: <Typography sx={{ mr: 1 }}>₦</Typography>,
                    }}
                  />

                  {activeTab === 0 && (
                    <FormControl fullWidth sx={{ mb: 2 }}>
                      <InputLabel>Funding Type</InputLabel>
                      <Select
                        value={fundingType}
                        label="Funding Type"
                        onChange={(e) =>
                          setFundingType(
                            e.target.value as "Manual" | "Automatic"
                          )
                        }
                      >
                        <MenuItem value="Manual">Manual</MenuItem>
                        <MenuItem value="Automatic">Automatic</MenuItem>
                      </Select>
                    </FormControl>
                  )}

                  <TextField
                    fullWidth
                    label="Description"
                    multiline
                    rows={3}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder={`Reason for ${
                      activeTab === 0 ? "funding" : "withdrawal"
                    }...`}
                    sx={{ mb: 2 }}
                  />

                  <Button
                    fullWidth
                    variant="contained"
                    size="large"
                    onClick={handleSubmit}
                    disabled={!amount || isNaN(Number(amount)) || !description}
                  >
                    {activeTab === 0 ? "Fund Wallet" : "Withdraw Funds"}
                  </Button>
                </>
              )}
            </Box>

            {isProcessing && (
              <Box sx={{ display: "flex", justifyContent: "center", my: 3 }}>
                <CircularProgress />
                <Typography sx={{ ml: 2 }}>
                  Processing transaction...
                </Typography>
              </Box>
            )}
          </Paper>
        </Grid>

        <Grid size={{ xs: 12, md: 6 }}>
          {selectedUser && (
            <Paper sx={{ p: 3, height: "100%" }}>
              <Typography variant="h6" gutterBottom>
                Recent {activeTab === 0 ? "Funding" : "Withdrawal"} Transactions
              </Typography>

              {recentTransactions.length > 0 ? (
                <List>
                  {recentTransactions.map((tx) => (
                    <React.Fragment key={tx._id}>
                      <ListItem>
                        <Avatar
                          sx={{
                            mr: 2,
                            bgcolor: tx.type.includes("Funding")
                              ? "success.light"
                              : "error.light",
                          }}
                        >
                          {tx.type.includes("Funding") ? "+" : "-"}
                        </Avatar>
                        <ListItemText
                          primary={`₦${tx.amount.toFixed(2)} • ${tx.status}`}
                          secondary={
                            <>
                              <Typography
                                component="span"
                                variant="body2"
                                color="text.primary"
                              >
                                {new Date(tx.createdAt).toLocaleString()}
                              </Typography>
                              {` • New balance: ₦${tx.balanceAfter.toFixed(2)}`}
                              {tx.fundingType && ` • Type: ${tx.fundingType}`}
                            </>
                          }
                        />
                      </ListItem>
                      <Divider component="li" />
                    </React.Fragment>
                  ))}
                </List>
              ) : (
                <Typography variant="body2" color="text.secondary">
                  No recent transactions found
                </Typography>
              )}
            </Paper>
          )}
        </Grid>
      </Grid>

      <Modal
        open={openConfirmModal}
        onClose={() => setOpenConfirmModal(false)}
        aria-labelledby="confirm-transaction-modal"
      >
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: 400,
            bgcolor: "background.paper",
            boxShadow: 24,
            p: 4,
            borderRadius: 1,
          }}
        >
          <Typography variant="h6" gutterBottom>
            Confirm Transaction
          </Typography>
          <Typography sx={{ mb: 2 }}>
            Are you sure you want to{" "}
            {activeTab === 0 ? "fund" : "withdraw from"}{" "}
            {selectedUser?.name || selectedUser?.username}'s wallet?
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            Amount: ₦{amount} • New balance: ₦
            {selectedUser
              ? activeTab === 0
                ? (selectedUser.accountBalance + Number(amount)).toFixed(2)
                : (selectedUser.accountBalance - Number(amount)).toFixed(2)
              : "0.00"}
          </Typography>
          <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
            <Button
              variant="outlined"
              onClick={() => setOpenConfirmModal(false)}
            >
              Cancel
            </Button>
            <Button variant="contained" onClick={confirmTransaction}>
              Confirm
            </Button>
          </Box>
        </Box>
      </Modal>

      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={snackbarSeverity}
          sx={{ width: "100%" }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default WalletManagement;
