"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { ZUserPassword } from "@formbricks/types/user";
import { getFormattedErrorMessage } from "@/lib/utils/error-message";
import { setupTwoFactorAuthAction } from "@/modules/ee/two-factor-auth/actions";
import { Button } from "@/modules/ui/components/button";
import { FormControl, FormError, FormField, FormItem } from "@/modules/ui/components/form";
import { PasswordInput } from "@/modules/ui/components/password-input";
import { EnableTwoFactorModalStep } from "./enable-two-factor-modal";

const ZConfirmPasswordFormState = z.object({
  password: ZUserPassword,
});
type TConfirmPasswordFormState = z.infer<typeof ZConfirmPasswordFormState>;

interface ConfirmPasswordFormProps {
  readonly setCurrentStep: (step: EnableTwoFactorModalStep) => void;
  readonly setBackupCodes: (codes: string[]) => void;
  readonly setDataUri: (dataUri: string) => void;
  readonly setSecret: (secret: string) => void;
  readonly setOpen: (open: boolean) => void;
}
export const ConfirmPasswordForm = ({
  setBackupCodes,
  setCurrentStep,
  setDataUri,
  setSecret,
  setOpen,
}: ConfirmPasswordFormProps) => {
  const form = useForm<TConfirmPasswordFormState>({
    defaultValues: {
      password: "",
    },
    resolver: zodResolver(ZConfirmPasswordFormState),
  });
  const { handleSubmit } = form;
  const { t } = useTranslation();

  const onSubmit: SubmitHandler<TConfirmPasswordFormState> = async (data) => {
    const setupTwoFactorAuthResponse = await setupTwoFactorAuthAction({ password: data.password });
    if (setupTwoFactorAuthResponse?.data) {
      const { backupCodes, dataUri, secret } = setupTwoFactorAuthResponse.data;
      setBackupCodes(backupCodes);
      setDataUri(dataUri);
      setSecret(secret);
      setCurrentStep("scanQRCode");
    } else {
      // Always surface something: getFormattedErrorMessage can resolve to an empty string for some
      // action errors, which would show a blank toast (the "spinner then nothing" symptom).
      const errorMessage = getFormattedErrorMessage(setupTwoFactorAuthResponse);
      toast.error(errorMessage || t("common.something_went_wrong_please_try_again"));
    }
  };

  return (
    <FormProvider {...form}>
      <form className="flex flex-col gap-y-4" onSubmit={handleSubmit(onSubmit)}>
        <div className="flex flex-col gap-2">
          <label htmlFor="password" className="text-sm font-medium text-slate-700">
            {t("common.password")}
          </label>
          <FormField
            control={form.control}
            name="password"
            render={({ field, fieldState: { error } }) => (
              <FormItem className="w-full">
                <FormControl>
                  <FormItem>
                    <PasswordInput
                      id="password"
                      autoComplete="current-password"
                      placeholder="*******"
                      aria-placeholder="password"
                      required
                      onChange={(password) => field.onChange(password)}
                      value={field.value}
                      className="block w-full rounded-md border-slate-300 shadow-xs focus:border-brand-dark focus:ring-brand-dark sm:text-sm"
                    />
                    {error?.message && <FormError className="text-left">{error.message}</FormError>}
                  </FormItem>
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        <div className="flex w-full items-center justify-end gap-x-2">
          <Button variant="secondary" size="sm" type="button" onClick={() => setOpen(false)}>
            {t("common.cancel")}
          </Button>

          <Button size="sm" loading={form.formState.isSubmitting}>
            {t("common.confirm")}
          </Button>
        </div>
      </form>
    </FormProvider>
  );
};
