"use client";

import * as Yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import Card from "@mui/material/Card";
import Stack from "@mui/material/Stack";
import IconButton from "@mui/material/IconButton";
import LoadingButton from "@mui/lab/LoadingButton";
import InputAdornment from "@mui/material/InputAdornment";
import { paths } from "@/routes/paths";
import { useRouter } from "@/hooks";
import { useBoolean } from "@/hooks";
import Iconify from "@/shared/components/iconify";
import FormProvider, { RHFTextField } from "@/shared/components/hook-form";
import { useSnackbar } from "@/components/snackbar";
import axiosInstance, { axiosInstancee } from "@/utils/axios";
import { useEffect, useState } from "react";

export default function UpdatePassword() {
  const router = useRouter();
  const oldPasswordVisible = useBoolean();
  const newPasswordVisible = useBoolean();
  const confirmPasswordVisible = useBoolean();
  const { enqueueSnackbar } = useSnackbar();
  const [userId, setUserId] = useState(null);

  // Fetch `userId` by email
  useEffect(() => {
    async function fetchUserId() {
      try {
        const email = localStorage.getItem("email"); // Assuming you store the email in localStorage
        if (!email) {
          enqueueSnackbar("User email is missing. Please log in again.", { variant: "error" });
          router.push(paths.auth.jwt.login);
          return;
        }
        const response = await axiosInstancee.get(`/api/user/user-id?email=${email}`);
        setUserId(response.data); // Set the retrieved `userId`
      } catch (error) {
        console.error("Failed to fetch user ID:", error);
        enqueueSnackbar("Unable to retrieve user ID. Please try again.", { variant: "error" });
        router.push(paths.auth.jwt.login);
      }
    }
    fetchUserId();
  }, [enqueueSnackbar, router]);

  const UpdatePasswordSchema = Yup.object().shape({
    oldPassword: Yup.string().min(6, "Password must be at least 6 characters").required("Old Password is required"),
    password: Yup.string().min(6, "Password must be at least 6 characters").required("New Password is required"),
    confirmPassword: Yup.string()
      .required("Confirm Password is required")
      .oneOf([Yup.ref("password")], "Passwords must match"),
  });

  const defaultValues = {
    oldPassword: "",
    password: "",
    confirmPassword: "",
  };

  const methods = useForm({
    resolver: yupResolver(UpdatePasswordSchema),
    defaultValues,
  });

  const { handleSubmit, formState: { isSubmitting } } = methods;

  const onSubmit = handleSubmit(async (data) => {
    if (!userId) {
      enqueueSnackbar("User ID is missing. Cannot update password.", { variant: "error" });
      return;
    }

    const payload = {
      oldPassword: data.oldPassword,
      newPassword: data.password,
    };

    try {
      await axiosInstance.put(`/api/user/${userId}/updatePassword`, payload);
      enqueueSnackbar("Password updated successfully!", { variant: "success" });
      router.push(paths.dashboard.root);
    } catch (error) {
      enqueueSnackbar("Failed to update password. Please try again.", { variant: "error" });
      console.error("Error updating password:", error);
    }
  });

  return (
    <FormProvider methods={methods} onSubmit={onSubmit}>
      <Stack component={Card} spacing={3} sx={{ p: 3 }}>
        <RHFTextField
          name="oldPassword"
          label="Old Password"
          type={oldPasswordVisible.value ? "text" : "password"}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={oldPasswordVisible.onToggle} edge="end">
                  <Iconify icon={oldPasswordVisible.value ? "eva:eye-fill" : "eva:eye-off-fill"} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
        <RHFTextField
          name="password"
          label="New Password"
          type={newPasswordVisible.value ? "text" : "password"}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={newPasswordVisible.onToggle} edge="end">
                  <Iconify icon={newPasswordVisible.value ? "eva:eye-fill" : "eva:eye-off-fill"} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
        <RHFTextField
          name="confirmPassword"
          label="Confirm New Password"
          type={confirmPasswordVisible.value ? "text" : "password"}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={confirmPasswordVisible.onToggle} edge="end">
                  <Iconify icon={confirmPasswordVisible.value ? "eva:eye-fill" : "eva:eye-off-fill"} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
        <LoadingButton
          type="submit"
          variant="contained"
          loading={isSubmitting}
          sx={{ ml: "auto" }}
        >
          Update Password
        </LoadingButton>
      </Stack>
    </FormProvider>
  );
}