"use client";

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

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

// 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 Button from "@mui/material/Button";
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,
  string,
  pipe,
  nonEmpty,
  minLength,
  maxLength,
  email,
  custom,
} 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";

type RegisterFormData = {
  username: string;
  email: string;
  phone_number: string;
  password: string;
  first_name: string;
  last_name: 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 Register = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { register } = useAuth();

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

  const registerSchema = useMemo(
    () =>
      object({
        first_name: string(),
        last_name: string(),
        username: pipe(string(), nonEmpty("نام کاربری الزامی است")),
        email: pipe(
          string(),
          nonEmpty("ایمیل الزامی است"),
          email("ایمیل معتبر وارد کنید"),
        ),
        phone_number: pipe(
          string(),
          nonEmpty("شماره موبایل الزامی است"),
          minLength(10, "شماره موبایل باید حداقل ۱۰ رقم باشد"),
          maxLength(15, "شماره موبایل باید حداکثر ۱۵ رقم باشد"),
          custom(
            (input) => /^[0-9]+$/.test(String(input)),
            "شماره موبایل باید فقط شامل عدد باشد",
          ),
        ),
        password: pipe(
          string(),
          nonEmpty("رمز عبور الزامی است"),
          minLength(8, "رمز عبور باید حداقل ۸ کاراکتر باشد"),
        ),
      }),
    [],
  );

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterFormData>({
    resolver: valibotResolver(registerSchema) as never,
    defaultValues: {
      first_name: "",
      last_name: "",
      username: "",
      email: "",
      phone_number: "",
      password: "",
    },
  });

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

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

    try {
      await register({
        first_name: data.first_name.trim(),
        last_name: data.last_name.trim(),
        username: data.username.trim(),
        email: data.email.trim(),
        phone_number: data.phone_number.trim(),
        password: data.password,
      });

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

      router.replace(redirectURL);
    } catch (error) {
      setErrorMessage(getErrorMessage(error, "ثبت نام ناموفق بود"));
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <AuthIllustrationWrapper>
      <Card className="flex flex-col sm:is-[480px]">
        <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">ایجاد حساب کاربری</Typography>
            <Typography>برای شروع، اطلاعات حساب خود را وارد کنید.</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"
          >
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Controller
                name="first_name"
                control={control}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    autoFocus
                    fullWidth
                    label="نام"
                    placeholder="نام خود را وارد کنید"
                    onChange={(event) => {
                      field.onChange(event.target.value);
                      if (errorMessage) setErrorMessage(null);
                    }}
                  />
                )}
              />

              <Controller
                name="last_name"
                control={control}
                render={({ field }) => (
                  <CustomTextField
                    {...field}
                    fullWidth
                    label="نام خانوادگی"
                    placeholder="نام خانوادگی خود را وارد کنید"
                    onChange={(event) => {
                      field.onChange(event.target.value);
                      if (errorMessage) setErrorMessage(null);
                    }}
                  />
                )}
              />
            </div>

            <Controller
              name="username"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  label="نام کاربری"
                  placeholder="نام کاربری خود را وارد کنید"
                  onChange={(event) => {
                    field.onChange(event.target.value);
                    if (errorMessage) setErrorMessage(null);
                  }}
                  {...(errors.username && {
                    error: true,
                    helperText: errors.username.message,
                  })}
                />
              )}
            />

            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  type="email"
                  label="ایمیل"
                  placeholder="ایمیل خود را وارد کنید"
                  onChange={(event) => {
                    field.onChange(event.target.value);
                    if (errorMessage) setErrorMessage(null);
                  }}
                  {...(errors.email && {
                    error: true,
                    helperText: errors.email.message,
                  })}
                />
              )}
            />

            <Controller
              name="phone_number"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  type="tel"
                  label="شماره موبایل"
                  placeholder="شماره موبایل خود را وارد کنید"
                  onChange={(event) => {
                    field.onChange(event.target.value.replace(/\D/g, ""));
                    if (errorMessage) setErrorMessage(null);
                  }}
                  {...(errors.phone_number && {
                    error: true,
                    helperText: errors.phone_number.message,
                  })}
                />
              )}
            />

            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  fullWidth
                  label="رمز عبور"
                  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,
                  })}
                />
              )}
            />

            <Button
              fullWidth
              variant="contained"
              type="submit"
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <CircularProgress size={24} color="inherit" />
              ) : (
                "ثبت نام"
              )}
            </Button>

            <div className="flex justify-center items-center flex-wrap gap-2">
              <Typography>قبلاً حساب کاربری دارید؟</Typography>
              <Typography component={Link} href="/login" color="primary.main">
                وارد شوید
              </Typography>
            </div>
          </form>
        </CardContent>
      </Card>
    </AuthIllustrationWrapper>
  );
};

export default Register;
