"use client";

import { Box, Heading, Input, Text, VStack } from "@chakra-ui/react";
import { Button } from "@/components/ui/buttons/button";
import { Field } from "@/components/ui/forms/field";
import { InputGroup } from "@/components/ui/forms/input-group";
import { PasswordInput } from "@/components/ui/forms/password-input";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogHeader,
  DialogRoot,
  DialogTitle,
} from "@/components/ui/overlays/dialog";
import { useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { signIn } from "next-auth/react";
import { toaster } from "@/components/ui/feedback/toaster";
import { useState } from "react";
import { MdMail } from "react-icons/md";
import { BiLock } from "react-icons/bi";
import { Link } from "@/i18n/navigation";
import { useQueryClient } from "@tanstack/react-query";

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

type LoginForm = yup.InferType<typeof schema>;

interface LoginModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function LoginModal({ open, onOpenChange }: LoginModalProps) {
  const t = useTranslations();
  const [loading, setLoading] = useState(false);
  const queryClient = useQueryClient();

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

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

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

      queryClient.clear();
      onOpenChange(false);
      toaster.success({
        title: t("auth.login-success") || "Login successful!",
        type: "success",
      });
    } catch (error) {
      toaster.error({
        title: (error as Error).message || "Login failed!",
        type: "error",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <DialogRoot open={open} onOpenChange={(e) => onOpenChange(e.open)}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            <Heading size="lg" color="primary.500">
              {t("auth.sign-in")}
            </Heading>
          </DialogTitle>
          <DialogCloseTrigger />
        </DialogHeader>
        <DialogBody>
          <Box as="form" onSubmit={handleSubmit(onSubmit)}>
            <VStack gap={4}>
              <Field
                label={t("email")}
                errorText={errors.email?.message}
                invalid={!!errors.email}
              >
                <InputGroup w="full" startElement={<MdMail size="1rem" />}>
                  <Input
                    borderRadius="md"
                    fontSize="sm"
                    type="text"
                    placeholder={t("email")}
                    {...register("email")}
                  />
                </InputGroup>
              </Field>

              <Field
                label={t("password")}
                errorText={errors.password?.message}
                invalid={!!errors.password}
              >
                <InputGroup w="full" startElement={<BiLock size="1rem" />}>
                  <PasswordInput
                    borderRadius="md"
                    fontSize="sm"
                    placeholder={t("password")}
                    {...register("password")}
                  />
                </InputGroup>
              </Field>

              <Button
                loading={loading}
                type="submit"
                bg="primary.400"
                w="100%"
                color="white"
                _hover={{ bg: "primary.500" }}
              >
                {t("auth.sign-in")}
              </Button>

              <Text fontSize="sm" color="fg.muted">
                {t("auth.dont-have-account")}{" "}
                <Link
                  href="/signup"
                  style={{
                    color: "var(--chakra-colors-primary-500)",
                    fontWeight: "bold",
                  }}
                >
                  {t("auth.sign-up")}
                </Link>
              </Text>
            </VStack>
          </Box>
        </DialogBody>
      </DialogContent>
    </DialogRoot>
  );
}
