"use client";

import {
  Box,
  Flex,
  Heading,
  Input,
  Link as ChakraLink,
  Text,
  ClientOnly,
} from "@chakra-ui/react";
import { Button } from "@/components/ui/buttons/button";
import { Switch } from "@/components/ui/forms/switch";
import { Field } from "@/components/ui/forms/field";
import { useTranslations } from "next-intl";
import signInImage from "../../../../../public/assets/img/sign-in-image.png";
import { InputGroup } from "@/components/ui/forms/input-group";
import { BiLock } from "react-icons/bi";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Link, useRouter } from "@/i18n/navigation";
import { MdMail } from "react-icons/md";
import { PasswordInput } from "@/components/ui/forms/password-input";
import { Skeleton } from "@/components/ui/feedback/skeleton";
import { signIn } from "next-auth/react";
import { toaster } from "@/components/ui/feedback/toaster";
import { useState } from "react";

const schema = yup.object({
  email: yup.string().email().required(),
  password: yup.string().required(),
});

type SignInForm = yup.InferType<typeof schema>;

const defaultValues = {
  email: "test@test.com.tr",
  password: "test1234",
};

export default function SignInForm() {
  const t = useTranslations();
  const router = useRouter();

  const [loading, setLoading] = useState(false);

  const {
    handleSubmit,
    register,
    formState: { errors },
  } = useForm<SignInForm>({
    resolver: yupResolver(schema),
    mode: "onChange",
    defaultValues,
  });

  const onSubmit = async (formData: SignInForm) => {
    try {
      setLoading(true);
      const res = await signIn("credentials", {
        redirect: false,
        email: formData.email,
        password: formData.password,
      });

      if (res?.error) {
        throw new Error(res.error);
      }

      router.replace("/home");
    } catch (error) {
      toaster.error({
        title: (error as Error).message || t("auth.login-error"),
        type: "error",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box position="relative">
      <Flex
        h={{ sm: "initial", md: "75vh", lg: "85vh" }}
        w="100%"
        maxW="1044px"
        mx="auto"
        justifyContent="space-between"
        mb="30px"
        pt={{ sm: "100px", md: "0px" }}
      >
        <Flex
          as="form"
          onSubmit={handleSubmit(onSubmit)}
          alignItems="center"
          justifyContent="start"
          style={{ userSelect: "none" }}
          w={{ base: "100%", md: "50%", lg: "42%" }}
        >
          <Flex
            direction="column"
            w="100%"
            background="transparent"
            p="10"
            mt={{ md: "150px", lg: "80px" }}
          >
            <Heading
              color={{ base: "primary.400", _dark: "primary.200" }}
              fontSize="32px"
              mb="10px"
              fontWeight="bold"
            >
              {t("auth.welcome-back")}
            </Heading>
            <Text
              mb="36px"
              ms="4px"
              color={{ base: "gray.400", _dark: "white" }}
              fontWeight="bold"
              fontSize="14px"
            >
              {t("auth.subtitle")}
            </Text>
            <Field
              mb="24px"
              label={t("email")}
              errorText={errors.email?.message}
              invalid={!!errors.email}
            >
              <InputGroup w="full" startElement={<MdMail size="1rem" />}>
                <Input
                  borderRadius="15px"
                  fontSize="sm"
                  type="text"
                  placeholder={t("email")}
                  size="lg"
                  {...register("email")}
                />
              </InputGroup>
            </Field>
            <Field
              mb="24px"
              label={t("password")}
              errorText={errors.password?.message}
              invalid={!!errors.password}
            >
              <InputGroup w="full" startElement={<BiLock size="1rem" />}>
                <PasswordInput
                  borderRadius="15px"
                  fontSize="sm"
                  placeholder={t("password")}
                  size="lg"
                  {...register("password")}
                />
              </InputGroup>
            </Field>
            <Field mb="24px">
              <Switch colorPalette="teal" label={t("auth.remember-me")}>
                {t("auth.remember-me")}
              </Switch>
            </Field>
            <Field mb="24px">
              <ClientOnly fallback={<Skeleton height="45px" width="100%" />}>
                <Button
                  loading={loading}
                  type="submit"
                  bg="primary.400"
                  w="100%"
                  h="45px"
                  color="white"
                  _hover={{
                    bg: "primary.500",
                  }}
                  _active={{
                    bg: "primary.400",
                  }}
                >
                  {t("auth.sign-in")}
                </Button>
              </ClientOnly>
            </Field>
            <Flex
              flexDirection="column"
              justifyContent="center"
              alignItems="center"
              maxW="100%"
            >
              <Text
                color={{ base: "gray.400", _dark: "white" }}
                fontWeight="medium"
              >
                {t("auth.dont-have-account")}
                <ChakraLink
                  as={Link}
                  href="/signup"
                  color={{ base: "primary.400", _dark: "primary.200" }}
                  ms="5px"
                  fontWeight="bold"
                  focusRing="none"
                >
                  {t("auth.sign-up")}
                </ChakraLink>
              </Text>
            </Flex>
          </Flex>
        </Flex>
        <Box
          display={{ base: "none", md: "block" }}
          overflowX="hidden"
          h="100%"
          w="40vw"
          position="absolute"
          right="0px"
        >
          <Box
            bgImage={`url(${signInImage.src})`}
            w="100%"
            h="100%"
            bgSize="cover"
            bgPos="50%"
            position="absolute"
            borderBottomLeftRadius="20px"
          />
        </Box>
      </Flex>
    </Box>
  );
}
