import toast from "react-hot-toast";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/custom_ui/form";
import Input from "~/components/custom_ui/input";
import { z } from "zod";
import { customErrorMapWrapper } from "~/hooks/locale";
import { useZodForm } from "~/lib/zodForm";
import { api } from "~/utils/api";
import { useTranslation } from "~/providers/I18nProvider";
import { cn } from "~/lib/utils";
import { Eye, EyeOff } from "lucide-react";
import { useRouter } from "next/router";
import { useState } from "react";

export const FormRstPwFromToken = (props: { token: string }) => {
  const { locale, t } = useTranslation();
  const router = useRouter();
  const [strengthScore, setStrengthScore] = useState(0);
  const [isVisible, setIsVisible] = useState<boolean>(false);
  const toggleVisibility = () => setIsVisible((prevState) => !prevState);

  const checkStrength = (pass: string) => {
    const requirements = [
      { regex: /.{8,}/, text: t.auth.signup.pw.lenght },
      { regex: /[0-9]/, text: t.auth.signup.pw.number },
      { regex: /[a-z]/, text: t.auth.signup.pw.lowercase },
      { regex: /[A-Z]/, text: t.auth.signup.pw.uppercase },
    ];

    return requirements.map((req) => ({
      met: req.regex.test(pass),
      text: req.text,
    }));
  };

  const getStrengthColor = (score: number) => {
    if (score === 0) return "bg-border";
    if (score <= 1) return "bg-red-500";
    if (score <= 2) return "bg-orange-500";
    if (score === 3) return "bg-amber-500";
    return "bg-emerald-500";
  };
  const getStrengthTxt = (score: number) => {
    if (score === 0) return "text-border";
    if (score <= 1) return "text-red-500";
    if (score <= 2) return "text-orange-500";
    if (score === 3) return "text-amber-500";
    return "text-emerald-500";
  };

  const ResetFormSchema = z
    .object({
      password: z.string(),
      repeat_password: z.string(),
    })
    .superRefine(({ password, repeat_password }, refinementContext) => {
      const complexity = checkStrength(password);

      if (complexity.filter((req) => req.met).length !== complexity.length) {
        refinementContext.addIssue({
          code: z.ZodIssueCode.custom,
          message: complexity
            .filter((req) => !req.met)
            .map((req) => req.text)
            .join("\n"),
          path: ["password"],
        });
      }
      setStrengthScore(complexity.filter((req) => req.met).length);

      if (password !== repeat_password) {
        refinementContext.addIssue({
          message: t.pwReset.pwDiverse,
          code: z.ZodIssueCode.custom,
          path: ["repeat_password"],
        });
      }
    });

  const { mutate } = api.auth.resetPasswordFromToken.useMutation({
    onSuccess: async () => {
      toast.success(t.pwReset.pwAggiornata);
      await router.push("/login");
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const form = useZodForm({
    schema: ResetFormSchema,
    defaultValues: {
      password: "",
      repeat_password: "",
    },
  });
  const onSubmit = (data: z.infer<typeof ResetFormSchema>) => {
    mutate({
      newpassword: data.password,
      resetToken: props.token,
    });
  };
  z.setErrorMap(customErrorMapWrapper(locale));

  return (
    <>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-8 px-0.5"
        >
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <div className="flex flex-col gap-x-2">
                  <FormLabel htmlFor="password" className="text-neutral-600">
                    {t.auth.signup.password}
                  </FormLabel>

                  <FormMessage
                    className={cn(
                      "whitespace-pre-wrap",
                      getStrengthTxt(strengthScore),
                    )}
                  />
                </div>

                <FormControl>
                  <div className="relative">
                    <Input
                      {...field}
                      id="password"
                      className="pe-9"
                      placeholder="Password"
                      type={isVisible ? "text" : "password"}
                      onChange={async (e) => {
                        field.onChange(e);
                        await form.trigger("password");
                      }}
                      aria-invalid={form.getFieldState("password").invalid}
                      aria-describedby="password-strength"
                    />
                    <button
                      className="text-muted-foreground/80 hover:text-foreground focus-visible:border-ring focus-visible:text-foreground focus-visible:ring-ring/30 absolute end-0 top-1 flex size-9 items-center justify-center rounded-e-lg transition-shadow focus-visible:border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
                      type="button"
                      onClick={toggleVisibility}
                      aria-label={isVisible ? "Hide password" : "Show password"}
                      aria-pressed={isVisible}
                      aria-controls="password"
                    >
                      {isVisible ? (
                        <EyeOff size={16} strokeWidth={2} aria-hidden="true" />
                      ) : (
                        <Eye size={16} strokeWidth={2} aria-hidden="true" />
                      )}
                    </button>
                    <div
                      className="bg-border mt-3 mb-4 h-1 w-full overflow-hidden rounded-full"
                      role="progressbar"
                      aria-valuenow={strengthScore}
                      aria-valuemin={0}
                      aria-valuemax={4}
                      aria-label="Password strength"
                    >
                      <div
                        className={cn(
                          "h-full transition-all duration-500 ease-out",
                          getStrengthColor(strengthScore),
                        )}
                        style={{ width: `${(strengthScore / 4) * 100}%` }}
                      />
                    </div>
                  </div>
                </FormControl>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="repeat_password"
            render={({ field }) => (
              <FormItem>
                <div className="flex flex-wrap items-center gap-x-2">
                  <FormLabel
                    className="text-base font-medium"
                    htmlFor="password2"
                  >
                    {t.pwReset.ripetiPw}
                  </FormLabel>

                  <FormMessage />
                </div>
                <FormControl>
                  <Input
                    placeholder=""
                    {...field}
                    type="password"
                    id="password2"
                  />
                </FormControl>
              </FormItem>
            )}
          />
          <button className="w-full rounded-lg bg-red-600 px-4 py-2 font-medium text-white duration-150 hover:bg-red-500 active:bg-red-600">
            {t.pwReset.aggiorna}
          </button>
        </form>
      </Form>
    </>
  );
};
