import {
  Box,
  Center,
  HStack,
  Image,
  Input,
  Text,
  VStack,
} from "@chakra-ui/react";
import axios from "axios";
import { useContext, useState } from "react";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import GlobalStateContext from "../Contexts/GlobalStateContext";
import { setToken } from "../Redux/Service/authSlice";
import logo from "../assets/logo.svg";
import { Button } from "../components/ui/button";
import { Field } from "../components/ui/field";
import { toaster, Toaster } from "../components/ui/toaster";
import { PasswordInput } from "../components/ui/password-input";
import { Link, useNavigate } from "react-router-dom";
// import ForgetPassword from "./ForgetPassword";

interface FormValues {
  mobileNumber: number;
  password: string;
}

const Login = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const context = useContext(GlobalStateContext);
  if (!context) {
    throw new Error("App must be used within a GlobalStateProvider");
  }
  const { setIsAuthenticate, setUserAccess } = context;
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>();

  const onSubmit = handleSubmit(async (data) => {
    setIsLoading(true);

    const username = import.meta.env.VITE_USER_NAME || "";
    const password = import.meta.env.VITE_PASSWORD || "";
    const basicAuth = `${username}:${password}`;

    try {
      const res = await axios.post(
        `${import.meta.env.VITE_API_URL}/login`,
        {
          mobile_number: Number(data.mobileNumber),
          password: data.password,
        },
        {
          headers: {
            Authorization: `Basic ${basicAuth}`,
            "Content-Type": "application/json",
          },
        }
      );

      const loginData = res.data?.data;
      const { principal_type_xid, role_permission } = loginData;

      const isAdmin = principal_type_xid === 1;

      const allowedTitles = isAdmin
        ? ['*']
        : role_permission?.get_resource_action_link
          ?.filter((link: unknown) => (link as any).is_active)
          .map((link: unknown) => (link as any).app_resource.app_resource_title) ?? [];

      setIsAuthenticate(true);
      setUserAccess(allowedTitles);
      dispatch(setToken(String(loginData["access-token"])));
      sessionStorage.setItem('userAccess', JSON.stringify(allowedTitles));
      navigate("/dashboard");
      setIsLoading(false);

    } catch (error: any) {
      console.log('error', error?.response?.data?.message);
      toaster.create({
        title: "Error",
        description: error?.response?.data?.message || "Login failed",
        type: "error",
      });
      setIsLoading(false);
    }
  });
  // console.log("User Access in Context:", userAccess);

  return (

    <VStack appearance={'light'} w={"100%"} h={"100vh"} bg={"#ffffff"}>
      <HStack
        boxShadow={"rgba(99, 99, 99, 0.2) 0px 2px 8px 0px"}
        w={"100%"}
        ps={8}
        h={"7%"}
        justifyContent={"flex-start"}
      >
        <Image w={50} src={logo} />
      </HStack>

      <HStack w={"100%"} h={"93%"} p={8} gap={8}>
        <Center
          display={{ base: "none", md: "flex" }}
          bg={"#02A0A033"}
          w={"50%"}
          h={"100%"}
          rounded={"3xl"}
        >
          <Image w={250} src={logo} />
        </Center>

        <Box
          as={"form"}
          onSubmit={onSubmit}
          p={{ base: 4, md: 16 }}
          w={{ base: "100%", md: "50%" }}
          h={"100%"}
        >
          <VStack gap={2} w={"100%"}>
            <Text
              w={"100%"}
              textAlign={"center"}
              fontSize={"24px"}
              fontWeight={"normal"}
              color={"#313039"}
            >
              LOGIN
            </Text>

            <Box mt={6} gap={4} w={"full"}>
              <Field
                color={"#313039"}
                label={"Enter Mobile Number"}
                w={"100%"}
                invalid={!!errors.mobileNumber}
                errorText={errors.mobileNumber?.message}
                mb={4}
              >
                <Input
                  type="number"
                  ps={3}
                  {...register("mobileNumber", {
                    required: "Mobile Number address is required",
                  })}
                  placeholder="Mobile Number Address"
                />
                {/* <Text as={'span'} w={'100%'} fontSize={'xs'} fontWeight={'normal'} color={'#686677'}>Forget password</Text>  */}
              </Field>
              <Field
                color={"#313039"}
                label={"Enter password."}
                w={"100%"}
                invalid={!!errors.password}
                errorText={errors.password?.message}
                mb={2}
              >
                <PasswordInput
                  ps={3}
                  {...register("password", { required: "Pasword is required" })}
                  placeholder="Enter password"
                />
                {/* <Text as={'span'} w={'100%'} fontSize={'xs'} fontWeight={'normal'} color={'#686677'}>Forget password</Text>  */}
              </Field>
              <Button
                loading={isLoading}
                mt={4}
                size={"sm"}
                bg={"#02A0A0"}
                rounded={"md"}
                w={"100%"}
                color={"#ffffff"}
                type="submit"
              >
                Login
              </Button>

              {/* <ForgetPassword /> */}
              <Box textAlign={"center"} mt={4}>
                <Link
                  to={'/forgot-password'}
                  style={{ color: "black", fontSize: "16px" }}
                >
                  Forgot Password
                </Link>
              </Box>
            </Box>
          </VStack>
        </Box>
        <Toaster />
      </HStack>
    </VStack>
  );
};

export default Login;
