"use client";

import React, { useState } from "react";
import {
  Typography,
  Container,
  Grid,
  ToggleButton,
  TextField,
  Button,
  Box,
  Snackbar,
  Alert,
  Card,
  CardContent,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import LoadingComponent from "@/app/components/loadingcomponent";

interface IReservedAccount {
  bankCode: string;
  bankName: string;
  accountNumber: string;
  accountName: string;
}

interface IReserverAccountDetails {
  accountName: string;
  accountReferences: string;
  reservationReference: string;
  accounts: IReservedAccount[];
}

const FundWallet: React.FC = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [fundingMethod, setFundingMethod] = useState<string | null>(null);
  const [amount, setAmount] = useState<string>("");
  const [reservedAccounts, setReservedAccounts] = useState<
    IReserverAccountDetails[]
  >([]);
  const [paymentData, setPaymentData] = useState<any | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: "",
    severity: "info",
  });

  const fetchReservedAccounts = async () => {
    try {
      const response = await fetch("/api/reserveraccount");
      const data = await response.json();
      if (data && data.reservedAccountDetails) {
        setReservedAccounts([...data.reservedAccountDetails]);
      }
    } catch (error) {
      setSnackbar({
        open: true,
        message: "Error fetching reserved accounts",
        severity: "error",
      });
      console.error("Error fetching reserved accounts:", error);
    }
  };

  const fetchUserDetail = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/onetimepayment");
      const data = await response.json();
      setPaymentData(data);
    } catch (error) {
      setSnackbar({
        open: true,
        message: "Error fetching user details",
        severity: "error",
      });
      console.error("Error fetching User Details", error);
    } finally {
      setLoading(false);
    }
  };

  const handlePayMonnify = async () => {
    setLoading(true);
    if (!amount) {
      setSnackbar({
        open: true,
        message: "Please enter an amount",
        severity: "warning",
      });
      setLoading(false);
      return;
    }
    try {
      if (paymentData) {
        launchMonnifyCheckout(paymentData);
      }
    } catch (error) {
      setSnackbar({
        open: true,
        message: "Error processing payment",
        severity: "error",
      });
      console.error("Error fetching one-time account:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleFundingMethodSelect = (method: string) => {
    setFundingMethod(method);
    setAmount("");

    if (method === "Reserved Account") {
      fetchReservedAccounts();
    } else if (method === "Monnify One Time Payment") {
      fetchUserDetail();
    }
  };

  const handlePaymentCompletion = async (response: any) => {
    if (response.status === "SUCCESS") {
      try {
        const res = await fetch("/api/onetimepayment", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            amount: parseFloat(amount),
            status: response.transactionReference,
          }),
        });

        if (res.status === 200) {
          setSnackbar({
            open: true,
            message:
              "Transaction Successful! Please check your wallet balance.",
            severity: "success",
          });
        } else {
          setSnackbar({
            open: true,
            message: "Transaction recorded but failed to update wallet.",
            severity: "warning",
          });
        }
      } catch (error) {
        console.error("Error updating transaction status:", error);
        setSnackbar({
          open: true,
          message: "Error updating transaction status",
          severity: "error",
        });
      }
    } else {
      setSnackbar({
        open: true,
        message: "Transaction failed",
        severity: "error",
      });
    }
  };

  const launchMonnifyCheckout = (paymentData: {
    customerEmail: string;
    paymentReference: string;
    customerName: string;
  }) => {
    if (typeof window !== "undefined" && window.MonnifySDK) {
      const { customerEmail, customerName, paymentReference } = paymentData;

      const monnifyOptions = {
        amount: parseFloat(amount),
        currency: "NGN",
        paymentReference,
        customerName,
        customerEmail,
        apiKey: "MK_PROD_WTNWLCU0DL",
        contractCode: "781809262377",
        paymentDescription: "Wallet Funding",
        paymentMethods: ["ACCOUNT_TRANSFER"],
        onClose: () => {
          setSnackbar({
            open: true,
            message: "Incomplete transaction",
            severity: "info",
          });
        },
        onComplete: (response: any) => {
          handlePaymentCompletion(response);
        },
      };

      window.MonnifySDK.initialize(monnifyOptions);
    } else {
      setSnackbar({
        open: true,
        message: "Monnify SDK is not loaded yet.",
        severity: "error",
      });
    }
  };

  return (
    <Container maxWidth="md" sx={{ py: 3 }}>
      <Card sx={{ mb: 3, boxShadow: 3 }}>
        <CardContent>
          <Typography variant="h4" gutterBottom>
            Fund Wallet
          </Typography>
          <Typography variant="body1" color="text.secondary">
            Choose your preferred funding method (Please Note there is 2%
            Deposit Fee)
          </Typography>
        </CardContent>
      </Card>

      {/* Funding Method Selection */}
      <Card sx={{ mb: 3, boxShadow: 2 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Select Funding Method
          </Typography>
          <Grid container spacing={2}>
            {["Monnify One Time Payment", "Reserved Account"].map((method) => (
              <Grid size={{ xs: 6, sm: 6 }} key={method}>
                <ToggleButton
                  value={method}
                  selected={fundingMethod === method}
                  onChange={() => handleFundingMethodSelect(method)}
                  sx={{
                    width: "100%",
                    height: "50px",
                    textTransform: "none",
                    "&.Mui-selected": {
                      backgroundColor: theme.palette.action.selected,
                    },
                  }}
                >
                  {method}
                </ToggleButton>
              </Grid>
            ))}
          </Grid>
        </CardContent>
      </Card>

      {/* Fund with Monnify */}
      {fundingMethod === "Monnify One Time Payment" && (
        <Card sx={{ mb: 3, boxShadow: 2 }}>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Enter Amount
            </Typography>
            <TextField
              fullWidth
              type="number"
              label="Amount (₦)"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              placeholder="Enter amount"
              sx={{ mb: 2 }}
              InputProps={{
                startAdornment: <Typography>₦</Typography>,
              }}
            />
            <Button
              variant="contained"
              color="primary"
              fullWidth
              size="large"
              onClick={handlePayMonnify}
              disabled={loading}
            >
              {loading ? (
                <>
                  <LoadingComponent />
                  <Box sx={{ ml: 1 }}>Processing...</Box>
                </>
              ) : (
                "Pay Now"
              )}
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Fund with Reserved Account */}
      {fundingMethod === "Reserved Account" && (
        <Card sx={{ mb: 3, boxShadow: 2 }}>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Reserved Account Details
            </Typography>
            {loading ? (
              <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
                <LoadingComponent />
              </Box>
            ) : reservedAccounts.length > 0 ? (
              reservedAccounts.map((reservedAccount, index) => (
                <Box key={index} sx={{ mb: 3 }}>
                  {reservedAccount?.accounts?.map((account, accIndex) => (
                    <Card key={accIndex} sx={{ mb: 2, p: 2, boxShadow: 1 }}>
                      <Typography
                        variant="subtitle1"
                        sx={{ fontWeight: "bold" }}
                      >
                        {account?.bankName}
                      </Typography>
                      <Typography>
                        Account Number: {account?.accountNumber}
                      </Typography>
                      <Typography>
                        Account Name: {account?.accountName}
                      </Typography>
                    </Card>
                  ))}
                </Box>
              ))
            ) : (
              <Typography variant="body1" color="text.secondary">
                No reserved accounts found
              </Typography>
            )}
          </CardContent>
        </Card>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          severity={snackbar.severity as any}
          sx={{ width: "100%" }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default FundWallet;
