"use client";

import * as Yup from "yup";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import Link from "@mui/material/Link";
import Alert from "@mui/material/Alert";
import Stack from "@mui/material/Stack";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import LoadingButton from "@mui/lab/LoadingButton";
import InputAdornment from "@mui/material/InputAdornment";
import { paths } from "@/routes/paths";
import RouterLink from "@/routes/router-link";
import { useRouter, useSearchParams } from "@/hooks";
import { useBoolean } from "@/hooks";
import { useAuthContext } from "@/hooks";
import { useSnackbar } from "@/components/snackbar"; // Import Snackbar hook
import Iconify from "@/shared/components/iconify";
import FormProvider, { RHFTextField } from "@/shared/components/hook-form";
import { getTokenInfo } from "@/utils/token"; // Import token handling utility
import axiosInstance, { axiosInstancee } from "@/utils/axios";
import { AuthenticationRequest } from "@/shared/types/user";
import axios from "axios";
import { PATH_AFTER_LOGIN } from "@/config-global";
import { loginUser } from "@/shared/api/user";

// ----------------------------------------------------------------------

export default function JwtLoginView() {
  const { login } = useAuthContext();
  const { enqueueSnackbar } = useSnackbar(); // Initialize Snackbar

  const router = useRouter();
  const [errorMsg, setErrorMsg] = useState("");
  const searchParams = useSearchParams();
  const password = useBoolean();
  const returnTo = searchParams.get("returnTo") || paths.dashboard.root;
  const passwordVisibility = useBoolean();

  const LoginSchema = Yup.object().shape({
    username: Yup.string()
      .required("Email is required")
      .email("Email must be a valid email address"),
    password: Yup.string().required("Password is required"),
  });

  const defaultValues = {
    username: "",
    password: "",
  };

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

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

  const onSubmit = handleSubmit(async (data) => {
    try {
      const response = await loginUser(data);

      if (response.status === 200) {
        const token = response.data.authResponse.token;
        const chatToken = response.data.chatAuthResponse.token;
        const userInfo = getTokenInfo(token);
        const chatUserInfo = getTokenInfo(chatToken);

        if (userInfo) {
          localStorage.setItem("user", JSON.stringify(userInfo));
        }

        if (chatUserInfo) {
          localStorage.setItem("chatUser", JSON.stringify(chatUserInfo));
        }

        // Proceed with login only if roles are valid
        if (!userInfo.realm_access.roles.includes("CLIENTT")) {
          const refreshToken = response.data.authResponse.refreshToken;
          const expirationDurationInSec = response.data.authResponse.expirationDurationInSec;

          localStorage.setItem("token", token);
          localStorage.setItem("refreshToken", refreshToken);
          localStorage.setItem(
            "expirationDurationInSec",
            expirationDurationInSec
          );

          localStorage.setItem("chatToken", chatToken);
          localStorage.setItem('chatRefreshToken', response.data.chatAuthResponse.refreshToken);
          localStorage.setItem("chatTokenExpiration", response.data.chatAuthResponse.expirationDurationInSec);

          const roles = userInfo.realm_access.roles;
          localStorage.setItem("role", JSON.stringify(roles));
          localStorage.setItem("email", userInfo.email);

          const agencyRoles = userInfo.agency_role || {};
          localStorage.setItem("agency_role", JSON.stringify(agencyRoles));

          const agencyId = (userInfo as any).agencyId || null;
          const objectWithAgencyId = { agencyId };

          router.push(returnTo || paths.dashboard.root);
        } else {
          enqueueSnackbar(
            "You are not authorized to access this application.",
            { variant: "warning" }
          );
          reset();
        }
      }
    } catch (error: any) {
      console.error("Login error:", error);
      reset();
      
      // Enhanced error handling
      if (error.response) {
        // Check for specific error message about email verification
        const errorMessage = error.response.data?.message || 
                           error.response.data?.error || 
                           error.response.data || 
                           "Something went wrong";
        
        if (errorMessage.includes("verify your email")) {
          enqueueSnackbar("Please verify your email before logging in", { variant: "error" });
          setErrorMsg("Please verify your email before logging in");
        } else if (error.response.status === 401) {
          // Handle general unauthorized errors
          enqueueSnackbar("Invalid email or password", { variant: "error" });
          setErrorMsg("Invalid email or password");
        } else {
          // Generic error handling
          enqueueSnackbar(errorMessage, { variant: "error" });
          setErrorMsg(errorMessage);
        }
      } else {
        // Network or other errors
        enqueueSnackbar("Cannot connect to the server", { variant: "error" });
        setErrorMsg("Cannot connect to the server");
      }
    }
  });

  const renderHead = (
    <Stack spacing={2} sx={{ mb: 2 }}>
      <Typography variant="h4">Sign in to Stunar</Typography>

      <Stack direction="row" spacing={0.5}>
        <Typography variant="body2">New user?</Typography>

        <Link
          component={RouterLink}
          href={paths.auth.jwt.register}
          variant="subtitle2"
        >
          Create an account
        </Link>
      </Stack>
    </Stack>
  );

  const renderForm = (
    <Stack spacing={2.5}>
      <RHFTextField name="username" label="Email address" />

      <RHFTextField
        name="password"
        label="Password"
        type={password.value ? "text" : "password"}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={password.onToggle} edge="end">
                <Iconify
                  icon={
                    password.value ? "solar:eye-bold" : "solar:eye-closed-bold"
                  }
                />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />
      <LoadingButton
        fullWidth
        color="inherit"
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
        sx={{
                backgroundColor: '#144dd5',
                '&:hover': {
                  backgroundColor: '#144dd5',
                },
                
                textTransform: 'none',
                px: 2,
              }}
      >
        Login
      </LoadingButton>
      <Link
        component={RouterLink}
        href={paths.auth.forgotPassword}
        variant="body2"
        color="inherit"
        underline="always"
        sx={{ alignSelf: "flex-end" }}
      >
        Forgot password?
      </Link>
    </Stack>
  );

  return (
    <>
      {renderHead}

      <Alert severity="info" sx={{ mb: 1 }}>
        <strong>1.Manager Agency </strong> <br /> Email :{" "}
        <strong>manageragency@stunar.com</strong> /Password :
        <strong> manageragency1234</strong> <br />
        <strong>2.Employee</strong> <br /> Email :{" "}
        <strong>employee@stunar.com</strong> /Password :
        <strong> employee1234</strong>
        <br />
        <strong>3.Client</strong> <br /> Email :{" "}
        <strong>client@stunar.com</strong> /Password :
        <strong> client1234</strong>
        <br />
        <strong>4.User </strong>
        <br /> Email :<strong>user@stunar.com</strong> /Password :
        <strong> user1234</strong>
        <br />
        <strong>5.Admin</strong> <br />
        Email : <strong>admin@stunar.com</strong> /Password :
        <strong> admin1234</strong>
        <br />
      </Alert>

      {!!errorMsg && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {errorMsg}
        </Alert>
      )}

      <FormProvider methods={methods} onSubmit={onSubmit}>
        {renderForm}
      </FormProvider>
    </>
  );
}