"use client";

import React, { useState } from "react";
import { useSession } from "next-auth/react";
import axios from "axios";
import {
  TextField,
  Button,
  Typography,
  Grid,
  Container,
  Paper,
  Snackbar,
  Alert,
} from "@mui/material";
import { useForm, Controller } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import LoadingComponent from "@/app/components/loadingcomponent";

// Update the schema to include the referral code field
const schema = yup.object().shape({
  nin: yup
    .string()
    .required("NIN is required")
    .length(11, "NIN must be 11 digits"),
  bvn: yup
    .string()
    .required("BVN is required")
    .length(11, "BVN must be 11 digits"),
  referralCode: yup
    .string()
    .optional() // Optional referral code field
    .test(
      "len",
      "Referral code must be exactly 8 characters",
      (value) => !value || value.length === 8
    ),
});

interface KycFormProps {
  handleCloseModal: () => void;
}

const KycForm: React.FC<KycFormProps> = ({ handleCloseModal }) => {
  const { data: session } = useSession();
  const [loading, setLoading] = useState(false);
  const [verified, setVerified] = useState(false);
  const [openSnackbar, setOpenSnackbar] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "success"
  );

  const {
    control,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      nin: "",
      bvn: "",
      referralCode: "", // Default value for referral code
    },
  });

  const ninValue = watch("nin");

  const handleNinVerification = async () => {
    setLoading(true);
    try {
      const response = await axios.post("/api/verifynin", { nin: ninValue });
      if (response.data.requestSuccessful) {
        setVerified(true);
        setSnackbarMessage("Information Verified");
        setSnackbarSeverity("success");
      } else {
        setVerified(false);
        setSnackbarMessage("Invalid NIN or BVN");
        setSnackbarSeverity("error");
      }
    } catch (error) {
      console.error("Error verifying NIN:", error);
      setSnackbarMessage("Error verifying NIN. Please try again later.");
      setSnackbarSeverity("error");
    } finally {
      setLoading(false);
      setOpenSnackbar(true);
    }
  };

  const onSubmit = async (data: any) => {
    try {
      // Include the referral code in the data sent to the backend
      await axios.put("/api/users/updateuser", {
        ...data,
        email: session?.user?.email, // Include the user's email from the session
      });
      setSnackbarMessage("KYC details updated successfully!");
      setSnackbarSeverity("success");
      handleCloseModal();
    } catch (error) {
      console.error("Error updating KYC details:", error);
      setSnackbarMessage("Failed to update KYC details.");
      setSnackbarSeverity("error");
    } finally {
      setOpenSnackbar(true);
    }
  };

  return (
    <Container maxWidth="sm">
      <Paper elevation={3} sx={{ p: 2 }}>
        <Typography variant="body1" gutterBottom sx={{ textAlign: "justify" }}>
          Central Bank of Nigeria (CBN) requires all Customer to provide their
          BVN & NIN to enable them use virtual account(s) for funding your
          online Wallet. Ignore if you don't need a Static Account for your
          wallet{" "}
        </Typography>

        <form onSubmit={handleSubmit(onSubmit)}>
          <Grid container spacing={2}>
            <Grid sx={{ xs: 12, alignItems: "center" }}>
              <Controller
                name="nin"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label="NIN Number"
                    error={!!errors.nin}
                    helperText={errors.nin?.message}
                  />
                )}
              />
            </Grid>
            <Grid sx={{ xs: 12 }}>
              <Controller
                name="bvn"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label="BVN Number"
                    error={!!errors.bvn}
                    helperText={errors.bvn?.message}
                  />
                )}
              />
            </Grid>
            {/* Add a new field for the referral code */}
            <Grid sx={{ xs: 12 }}>
              <Controller
                name="referralCode"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    fullWidth
                    label="Referral Code (Optional)"
                    error={!!errors.referralCode}
                    helperText={errors.referralCode?.message}
                  />
                )}
              />
            </Grid>
            <Grid sx={{ xs: 12 }}>
              <Button
                variant="contained"
                color="primary"
                fullWidth
                onClick={
                  verified ? handleSubmit(onSubmit) : handleNinVerification
                }
                disabled={loading}
              >
                {loading ? (
                  <LoadingComponent />
                ) : verified ? (
                  "Submit KYC"
                ) : (
                  "Verify NIN"
                )}
              </Button>
            </Grid>
          </Grid>
        </form>
      </Paper>
      <Snackbar
        open={openSnackbar}
        autoHideDuration={6000}
        onClose={() => setOpenSnackbar(false)}
      >
        <Alert
          onClose={() => setOpenSnackbar(false)}
          severity={snackbarSeverity}
          sx={{ width: "100%" }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default KycForm;
