"use client";

// React Imports
import { useMemo, useState } from "react";

// Next Imports
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";

// MUI Imports
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Checkbox from "@mui/material/Checkbox";
import Button from "@mui/material/Button";
import FormControlLabel from "@mui/material/FormControlLabel";
import Alert from "@mui/material/Alert";
import CircularProgress from "@mui/material/CircularProgress";

// Third-party Imports
import { Controller, useForm } from "react-hook-form";
import { valibotResolver } from "@hookform/resolvers/valibot";
import { object, minLength, string, pipe, nonEmpty } from "valibot";
import type { SubmitHandler } from "react-hook-form";

// Component Imports
import Logo from "@components/layout/shared/Logo";
import CustomTextField from "@core/components/mui/TextField";
import AuthIllustrationWrapper from "@views/pages/auth/AuthIllustrationWrapper";

// Context Imports
import { useAuth } from "@/contexts/authContext";

// Config Imports
import themeConfig from "@configs/themeConfig";

type LoginFormData = {
  identifier: string;
  password: string;
};

const getErrorMessage = (error: unknown, fallbackMessage: string) => {
  if (error instanceof Error) return error.message;

  if (typeof error === "object" && error !== null && "message" in error) {
    return String(error.message);
  }

  return fallbackMessage;
};

const Login = () => {
  const t = useTranslations("login");
  const router = useRouter();
  const searchParams = useSearchParams();
  const { login } = useAuth();

  const [isPasswordShown, setIsPasswordShown] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const loginSchema = useMemo(
    () =>
      object({
        identifier: pipe(
          string(),
          nonEmpty(String(t("validation.identifierRequired"))),
        ),
        password: pipe(
          string(),
          nonEmpty(String(t("validation.passwordRequired"))),
          minLength(8, String(t("validation.passwordMinLength"))),
        ),
      }),
    [t],
  );

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: valibotResolver(loginSchema) as never,
    defaultValues: {
      identifier: "",
      password: "",
    },
  });

  const handleClickShowPassword = () => setIsPasswordShown((show) => !show);

  const onSubmit: SubmitHandler<LoginFormData> = async (data) => {
    setIsSubmitting(true);
    setErrorMessage(null);

    try {
      await login(data.identifier.trim(), data.password);

      const redirectURL = searchParams.get("redirectTo") ?? "/";

      router.replace(redirectURL);
    } catch (error) {
      setErrorMessage(getErrorMessage(error, String(t("errors.loginFailed"))));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <AuthIllustrationWrapper>
      <Card className="flex flex-col sm:is-[450px]">
        <CardContent className="sm:!p-12">
          <Link href="/" className="flex justify-center mbe-6">
            <Logo />
          </Link>
          <div className="flex flex-col gap-1 mbe-6">
            <Typography variant="h4">
              {t("welcome", { templateName: themeConfig.templateName })}
            </Typography>
            <Typography>{t("subtitle")}</Typography>
          </div>

          {errorMessage && (
            <Alert
              severity="error"
              onClose={() => setErrorMessage(null)}
              className="mbe-6"
            >
              {errorMessage}
            </Alert>
          )}

          <form
            noValidate
            autoComplete="off"
            onSubmit={handleSubmit(onSubmit)}
            className="flex flex-col gap-6"
          >
            <Controller
              name="identifier"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  autoFocus
                  fullWidth
                  label={t("identifier")}
                  placeholder={t("placeholderIdentifier")}
                  onChange={(event) => {
                    field.onChange(event.target.value);
                    if (errorMessage) setErrorMessage(null);
                  }}
                  {...(errors.identifier && {
                    error: true,
                    helperText: errors.identifier.message,
                  })}
                />
              )}
            />

            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  label={t("password")}
                  placeholder="············"
                  type={isPasswordShown ? "text" : "password"}
                  onChange={(event) => {
                    field.onChange(event.target.value);
                    if (errorMessage) setErrorMessage(null);
                  }}
                  slotProps={{
                    input: {
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            edge="end"
                            onClick={handleClickShowPassword}
                            onMouseDown={(event) => event.preventDefault()}
                          >
                            <i
                              className={
                                isPasswordShown
                                  ? "tabler-eye-off"
                                  : "tabler-eye"
                              }
                            />
                          </IconButton>
                        </InputAdornment>
                      ),
                    },
                  }}
                  {...(errors.password && {
                    error: true,
                    helperText: errors.password.message,
                  })}
                />
              )}
            />

            <div className="flex justify-between items-center gap-x-3 gap-y-1 flex-wrap">
              <FormControlLabel
                control={<Checkbox />}
                label={t("rememberMe")}
              />
              <Typography
                className="text-end"
                color="primary.main"
                component={Link}
                href="/forgot-password"
              >
                {t("forgotPassword")}
              </Typography>
            </div>

            <Button
              fullWidth
              variant="contained"
              type="submit"
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <CircularProgress size={24} color="inherit" />
              ) : (
                t("submit")
              )}
            </Button>

            <div className="flex justify-center items-center flex-wrap gap-2">
              <Typography>{t("newUser")}</Typography>
              <Typography
                component={Link}
                href="/register"
                color="primary.main"
              >
                {t("createAccount")}
              </Typography>
            </div>
          </form>
        </CardContent>
      </Card>
    </AuthIllustrationWrapper>
  );
};

export default Login;
