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

export const ChangePasswordForm = () => {
  const {
    isVisible,
    getStrengthColor,
    passwordRefine,
    getStrengthTxt,
    strengthScore,
    toggleVisibility,
  } = useStrongPassword();

  const ChangePasswordFormSchema = z
    .object({
      oldpassword: z.string(),
      newpassword: z.string(),
    })
    .superRefine(({ newpassword }, refinementContext) => {
      passwordRefine({
        password: newpassword,
        refinementContext,
        path: "newpassword",
      });
    });

  type ChangePasswordFormValues = z.infer<typeof ChangePasswordFormSchema>;

  const { locale, t } = useTranslation();

  z.setErrorMap(customErrorMapWrapper(locale));

  const form = useZodForm({
    schema: ChangePasswordFormSchema,
    defaultValues: {
      oldpassword: "",
      newpassword: "",
    },
  });

  const { mutate } = api.auth.ChangePassword.useMutation({
    onSuccess: () => {
      toast.success(t.pwReset.pwAggiornata);
      form.reset();
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  function onSubmit(fields: ChangePasswordFormValues) {
    mutate({
      oldpassword: fields.oldpassword,
      newpassword: fields.newpassword,
    });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 px-0.5">
        <FormField
          control={form.control}
          name="oldpassword"
          render={({ field }) => (
            <FormItem>
              <div className="flex flex-wrap items-center gap-x-2">
                <FormLabel htmlFor="oldpw">{t.pwReset.oldPw}</FormLabel>
                <FormMessage />
              </div>
              <FormControl>
                <Input
                  placeholder=""
                  {...field}
                  id="oldpw"
                  autoComplete="current-password"
                />
              </FormControl>
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="newpassword"
          render={({ field }) => (
            <FormItem>
              <div className="flex flex-col gap-x-2">
                <FormLabel htmlFor="newpassword" className="text-neutral-600">
                  {t.pwReset.newPw}
                </FormLabel>

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

              <FormControl>
                <div className="relative">
                  <Input
                    {...field}
                    id="newpassword"
                    autoComplete="new-password"
                    className="pe-9"
                    placeholder="Password"
                    type={isVisible ? "text" : "password"}
                    onChange={async (e) => {
                      field.onChange(e);
                      await form.trigger("newpassword");
                    }}
                    aria-invalid={form.getFieldState("newpassword").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>
          )}
        />
        <Button type="submit">{t.pwReset.aggiorna}</Button>
      </form>
    </Form>
  );
};
