"use client";

import React, { useEffect, useState } from "react";
import {
  Typography,
  Container,
  Grid,
  TextField,
  Switch,
  FormControlLabel,
  Button,
  ToggleButton,
  Box,
  Snackbar,
  Alert,
  Backdrop,
  Card,
  CardContent,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import Image from "next/image";
import { useSession } from "next-auth/react";
import { AuthModal, ConfirmModal } from "@/app/components/modals/authmodal";
import TransactionModal from "@/app/components/modals/TransactionModal";
import axios from "axios";
import mtnLogo from "../../../public/images/mtn.png";
import airtelLogo from "../../../public/images/aritel.png";
import mobile9Logo from "../../../public/images/9mobile.png";
import gloLogo from "../../../public/images/glo.jpg";
import LoadingComponent from "@/app/components/loadingcomponent";

const airtimeTypes = ["VTU", "Share and Sell"];

type AirtimeType = "VTU" | "Share and Sell";
type NetworkKeys = "MTN" | "Airtel" | "Glo" | "9Mobile";

const BuyAirtime: React.FC = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const { data: session } = useSession();

  const [selectedNetwork, setSelectedNetwork] = useState<NetworkKeys | null>(
    null
  );
  const [selectedAirtimeType, setSelectedAirtimeType] =
    useState<AirtimeType | null>(null);
  const [amount, setAmount] = useState<string>("");
  const [mobileNumber, setMobileNumber] = useState<string>("");
  const [bypass, setBypass] = useState<boolean>(false);
  const [userType, setUserType] = useState<string | null>(null);
  const [userId, setUserId] = useState<string | null>(null);
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [authOpen, setAuthOpen] = useState(false);
  const [isTransactionModalOpen, setIsTransactionModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isBackdropOpen, setIsBackdropOpen] = useState(false);
  const [walletBalance, setWalletBalance] = useState<string>("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [transactionPinStatus, setTransactionPinStatus] =
    useState<boolean>(false);
  const [thumbPrintStatus, setThumbPrintStatus] = useState<boolean>(false);
  const [transactionDetails, setTransactionDetails] = useState({
    finalMessage: "",
    amount: "",
    recipient: "",
    date: "",
    status: "success" as "success" | "pending" | "failed",
  });
  const [airtimePlan, setAirtimePlan] = useState<{
    network: string;
    airtimeType: string;
    smartEarnerPercent: number;
    affiliatePercent: number;
    topUserPercent: number;
  } | null>(null);

  useEffect(() => {
    const fetchUserType = async () => {
      try {
        setIsLoading(true);
        setIsBackdropOpen(true);
        const response = await axios.get(`/api/users/getSingleUser`);
        setUserType(response.data.userType);
        setUserId(response.data._id);
        setUserEmail(response.data.email);
        setWalletBalance(response.data.accountBalance);
        setTransactionPinStatus(response.data.transactionStatus);
        setThumbPrintStatus(response.data.thumbprintStatus);
      } catch (error) {
        console.error("Error fetching user type:", error);
      } finally {
        setIsLoading(false);
        setIsBackdropOpen(false);
      }
    };

    fetchUserType();
  }, [session]);

  const handleNetworkSelect = (network: NetworkKeys) => {
    setSelectedNetwork(network);
    setSelectedAirtimeType(null);
    setAmount("");
  };

  const handleAirtimeTypeSelect = (type: AirtimeType) => {
    setSelectedAirtimeType(type);
  };

  const handleSubmit = async () => {
    if (!selectedNetwork || !selectedAirtimeType || !amount || !mobileNumber) {
      setSnackbarMessage("Please fill in all required fields.");
      setSnackbarOpen(true);
      return;
    }
    if (parseFloat(walletBalance) >= parseFloat(amount)) {
      setTransactionDetails({
        finalMessage: `Are you sure you want to buy ₦${amount} ${selectedNetwork}'s airtime for ${mobileNumber}?`,
        amount: amount,
        recipient: mobileNumber,
        date: new Date().toLocaleString(),
        status: "success",
      });
      setConfirmOpen(true);
    } else {
      setSnackbarMessage("Insufficient Balance, Please Fund your Wallet");
      setSnackbarOpen(true);
      setConfirmOpen(false);
    }
  };

  const handleConfirm = () => {
    setConfirmOpen(false);
    if (thumbPrintStatus || transactionPinStatus) {
      setAuthOpen(true);
    } else {
      handleVerify();
    }
  };

  const handleVerify = async () => {
    setAuthOpen(false);
    setIsLoading(true);
    setIsBackdropOpen(true);
    try {
      const airtimePlanResponse = await axios.get(
        `/api/airtimeplan?network=${selectedNetwork}&airtimeType=${selectedAirtimeType}`
      );
      setAirtimePlan(airtimePlanResponse.data);

      const payload = {
        network: selectedNetwork,
        airtimeType: selectedAirtimeType,
        amount: parseFloat(amount),
        phone: mobileNumber,
        bypass,
        userId,
        userEmail,
        userType,
        airtimePlan,
      };

      const purchaseResponse = await fetch("/api/buyairtime", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

      const result = await purchaseResponse.json();
      if (result.status === 429) {
        setTransactionDetails({
          finalMessage: result.data.message,
          amount: amount,
          recipient: mobileNumber,
          date: new Date().toLocaleString(),
          status: "failed",
        });
      }
      setTransactionDetails({
        finalMessage:
          result?.code === "000" &&
          result?.content?.transactions?.status === "delivered"
            ? `Your have successfully bought ₦${amount} ${selectedNetwork}'s airtime for ${mobileNumber}`
            : result?.code === "000" &&
              result?.content?.transactions?.status === "pending"
            ? `₦${amount} ${selectedNetwork}'s airtime for ${mobileNumber} is pending. Please check your transaction history after few minutes.`
            : result?.code === "016" &&
              result?.content?.transactions?.status === "failed"
            ? `Airtime Purchase failed due to an issue with the transaction. Please try again.`
            : result?.code === "018" ||
              result?.content?.transactions?.status === "failed"
            ? `Payment failed due to issue from admin side please inform admin. Please try again.`
            : `Payment status unknown. Please contact support.`,
        amount: amount,
        recipient: mobileNumber,
        date: new Date().toLocaleString(),
        status:
          result?.code === "000" &&
          result?.content?.transactions?.status === "delivered"
            ? "success"
            : result?.code === "000" &&
              result?.content?.transactions?.status === "pending"
            ? "pending"
            : result?.code === "016" &&
              result?.content?.transactions?.status === "failed"
            ? "failed"
            : result?.code === "018" ||
              result?.content?.transactions?.status === "failed"
            ? "failed"
            : "failed",
      });

      setSnackbarMessage(
        result?.code === "000" &&
          result?.content?.transactions?.status === "delivered"
          ? "Payment successful."
          : "Payment failed."
      );
    } catch (error) {
      setTransactionDetails({
        finalMessage: "Payment processing error. Please Contact Admin.",
        amount: amount,
        recipient: mobileNumber,
        date: new Date().toLocaleString(),
        status: "failed",
      });
      setSnackbarMessage("Payment processing error. Please Try again.");
    } finally {
      setIsTransactionModalOpen(true);
      setIsLoading(false);
      setIsBackdropOpen(false);
      setSnackbarOpen(true);
    }
  };

  const handleTransactionModalClose = () => {
    setIsTransactionModalOpen(false);
    window.location.reload();
  };

  return (
    <Container maxWidth="md" sx={{ py: 3 }}>
      {/* Backdrop for Loading */}
      <Backdrop
        open={isBackdropOpen}
        sx={{ color: "#fff", zIndex: (theme) => theme.zIndex.drawer + 1 }}
      >
        <LoadingComponent />
      </Backdrop>

      <Card sx={{ mb: 3, boxShadow: 3 }}>
        <CardContent>
          <Typography variant="h4" gutterBottom>
            Buy Airtime
          </Typography>
          <Typography variant="body1" color="text.secondary">
            Select your preferred network and airtime type
          </Typography>
        </CardContent>
      </Card>

      {/* Network Selection */}
      <Card sx={{ mb: 3, boxShadow: 2 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            Select Network
          </Typography>
          <Grid container spacing={2}>
            {["MTN", "Airtel", "Glo", "9Mobile"].map((network) => (
              <Grid size={{ xs: 6, sm: 3 }} key={network}>
                <ToggleButton
                  value={network}
                  selected={selectedNetwork === network}
                  onChange={() => handleNetworkSelect(network as NetworkKeys)}
                  sx={{
                    width: "100%",
                    height: isMobile ? "80px" : "100px",
                    p: 1,
                    border: `1px solid ${theme.palette.divider}`,
                    "&.Mui-selected": {
                      backgroundColor: theme.palette.action.selected,
                      borderColor: theme.palette.primary.main,
                    },
                  }}
                >
                  <Box
                    sx={{
                      position: "relative",
                      width: "100%",
                      height: "100%",
                    }}
                  >
                    <Image
                      src={
                        network === "MTN"
                          ? mtnLogo
                          : network === "Airtel"
                          ? airtelLogo
                          : network === "Glo"
                          ? gloLogo
                          : mobile9Logo
                      }
                      alt={network}
                      fill
                      sizes="100%"
                      priority
                      style={{ objectFit: "contain" }}
                    />
                  </Box>
                </ToggleButton>
              </Grid>
            ))}
          </Grid>
        </CardContent>
      </Card>

      {/* Airtime Type Selection */}
      {selectedNetwork && (
        <Card sx={{ mb: 3, boxShadow: 2 }}>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Select Airtime Type
            </Typography>
            <Grid container spacing={2}>
              {airtimeTypes.map((type) => (
                <Grid size={{ xs: 6 }} key={type}>
                  <ToggleButton
                    value={type}
                    selected={selectedAirtimeType === type}
                    onChange={() =>
                      handleAirtimeTypeSelect(type as AirtimeType)
                    }
                    sx={{
                      width: "100%",
                      height: "50px",
                      textTransform: "none",
                      "&.Mui-selected": {
                        backgroundColor: theme.palette.action.selected,
                      },
                    }}
                  >
                    {type}
                  </ToggleButton>
                </Grid>
              ))}
            </Grid>
          </CardContent>
        </Card>
      )}

      {/* Amount and Phone Number Input */}
      {selectedNetwork && selectedAirtimeType && (
        <Card sx={{ mb: 3, boxShadow: 2 }}>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Enter Details
            </Typography>
            <TextField
              fullWidth
              label="Airtime Amount (₦)"
              placeholder="Enter amount"
              value={amount}
              onChange={(e) => {
                const input = e.target.value;
                if (parseFloat(input) >= 0 || input === "") {
                  setAmount(input);
                }
              }}
              inputProps={{ min: 0 }}
              sx={{ mb: 2 }}
              type="number"
            />
            <TextField
              fullWidth
              label="Phone Number"
              placeholder="Enter phone number"
              value={mobileNumber}
              onChange={(e) => setMobileNumber(e.target.value)}
              sx={{ mb: 2 }}
            />
            <FormControlLabel
              control={
                <Switch
                  checked={bypass}
                  onChange={(e) => setBypass(e.target.checked)}
                />
              }
              label="Bypass Phone Number"
              sx={{ mb: 2 }}
            />
            <Button
              variant="contained"
              color="primary"
              fullWidth
              size="large"
              onClick={handleSubmit}
              disabled={isLoading}
            >
              {isLoading ? "Processing..." : "Buy Airtime"}
            </Button>
          </CardContent>
        </Card>
      )}

      <ConfirmModal
        open={confirmOpen}
        onClose={() => setConfirmOpen(false)}
        onConfirm={handleConfirm}
        transactionDetails={{
          message: transactionDetails.finalMessage,
          amount: amount,
          recipient: mobileNumber,
          date: new Date().toLocaleDateString(),
        }}
      />
      <AuthModal
        open={authOpen}
        onClose={() => setAuthOpen(false)}
        onVerify={handleVerify}
      />
      <TransactionModal
        open={isTransactionModalOpen}
        onClose={handleTransactionModalClose}
        transactionDetails={transactionDetails}
        isLoading={isLoading}
      />
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert
          onClose={() => setSnackbarOpen(false)}
          severity={
            transactionDetails.status === "success" ? "success" : "error"
          }
          sx={{ width: "100%" }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default BuyAirtime;
