import { useState } from "react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Grid,
  IconButton,
  TextField,
  Typography,
  Snackbar,
  Alert,
} from "@mui/material";
import axios from "axios";

interface AuthModalProps {
  open: boolean;
  onClose: () => void;
  onVerify: (pin?: string) => void;
}

const AuthModal: React.FC<AuthModalProps> = ({ open, onClose, onVerify }) => {
  const [pin, setPin] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [isVerifying, setIsVerifying] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "success"
  );

  const handleKeyPress = (num: string) => {
    if (pin.length < 6) {
      setPin((prev) => prev + num);
    }
  };

  const handleBackspace = () => {
    setPin((prev) => prev.slice(0, -1));
  };

  const handleVerify = async () => {
    if (pin.length >= 5) {
      setIsVerifying(true); // Disable button
      try {
        const response = await axios.post("/api/verifyTransactionPIN", { pin });

        if (response.status === 200) {
          setSnackbarMessage("Transaction Verified Successfully!");
          setSnackbarSeverity("success");
          setSnackbarOpen(true);
          onVerify(pin);
        }
      } catch (error) {
        setSnackbarMessage("Invalid PIN");
        setSnackbarSeverity("error");
        setSnackbarOpen(true);
      } finally {
        setIsVerifying(false); // Re-enable button after request completes
      }
    }
  };

  const handleBiometricAuth = async () => {
    try {
      // Step 1: Fetch authentication options from the server
      const optionsResponse = await axios.get(
        "/api/auth/webauthn/authenticate"
      );
      if (optionsResponse.status !== 200) {
        throw new Error("Failed to fetch authentication options");
      }

      const options = optionsResponse.data;

      // Step 2: Initiate WebAuthn authentication using the browser's WebAuthn API
      const credential = await navigator.credentials.get({
        publicKey: {
          challenge: Uint8Array.from(options.challenge, (c: string) =>
            c.charCodeAt(0)
          ),
          allowCredentials: options.allowCredentials.map((cred: any) => ({
            id: Uint8Array.from(cred.id, (c: string) => c.charCodeAt(0)),
            type: cred.type,
            transports: cred.transports,
          })),
          userVerification: options.userVerification,
        },
      });

      if (!credential) {
        throw new Error("No credential received from the authenticator");
      }

      // Step 3: Send the authentication response to the server for verification
      const verificationResponse = await axios.post(
        "/api/auth/webauthn/authenticate",
        {
          credential: {
            id: credential.id,
            response: {
              authenticatorData: Buffer.from(
                (credential as any).response.authenticatorData
              ).toString("base64"),
              clientDataJSON: Buffer.from(
                (credential as any).response.clientDataJSON
              ).toString("base64"),
              signature: Buffer.from(
                (credential as any).response.signature
              ).toString("base64"),
              userHandle: Buffer.from(
                (credential as any).response.userHandle || ""
              ).toString("base64"),
            },
          },
        }
      );

      if (verificationResponse.status === 200) {
        setSnackbarMessage("Biometric Authentication Successful!");
        setSnackbarSeverity("success");
        setSnackbarOpen(true);
        onVerify(); // Call the onVerify callback to proceed with the transaction
      } else {
        throw new Error("Biometric authentication failed");
      }
    } catch (error) {
      setSnackbarMessage("Error with Biometric Authentication");
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      console.error("Error with biometric authentication:", error);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="xs">
      <DialogTitle>Verify Transaction</DialogTitle>
      <DialogContent>
        <TextField
          value={pin}
          variant="outlined"
          fullWidth
          inputProps={{ readOnly: true, style: { textAlign: "center" } }}
          sx={{ mb: 2, mt: 1, fontSize: "1.5rem" }}
        />
        <Grid container spacing={1} justifyContent="center">
          {[...Array(10).keys()].map((num) => (
            <Grid sx={{ xs: 4 }} key={num}>
              <Button
                variant="contained"
                fullWidth
                onClick={() => handleKeyPress(num.toString())}
                sx={{ height: 60 }}
              >
                {num}
              </Button>
            </Grid>
          ))}
          <Grid sx={{ x: 4 }}>
            <Button
              variant="outlined"
              fullWidth
              onClick={handleBackspace}
              sx={{ height: 60 }}
            >
              ⌫
            </Button>
          </Grid>
          <Grid sx={{ x: 4 }}>
            <Button
              variant="contained"
              fullWidth
              onClick={handleVerify}
              disabled={isVerifying} // Disable button during request
              sx={{ height: 60 }}
            >
              ✔
            </Button>
          </Grid>
          <Grid sx={{ x: 4 }}>
            <IconButton
              onClick={handleBiometricAuth}
              sx={{ height: 60, width: "100%" }}
            >
              {/* <FingerprintIcon fontSize="large" color="primary" /> */}
            </IconButton>
          </Grid>
        </Grid>
      </DialogContent>
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
      >
        <Alert
          onClose={() => setSnackbarOpen(false)}
          severity={snackbarSeverity}
          sx={{ width: "100%" }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Dialog>
  );
};

interface ConfirmModalProps {
  open: boolean;
  onClose: () => void;
  onConfirm: () => void;
  transactionDetails: {
    amount: string;
    recipient: string;
    date: string;
    message: string;
  };
}

const ConfirmModal: React.FC<ConfirmModalProps> = ({
  open,
  onClose,
  onConfirm,
  transactionDetails,
}) => {
  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="xs">
      <DialogTitle>Confirm Transaction</DialogTitle>
      <DialogContent>
        <Typography variant="body1">{transactionDetails.message}</Typography>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="secondary">
          Cancel
        </Button>
        <Button onClick={onConfirm} color="primary" variant="contained">
          Confirm
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export { AuthModal, ConfirmModal };
