import { Button } from '@/components/ui/button';
import { useAppForm } from '@hooks/use-app-form';
import { m } from '@paraglide/messages';
import { usersQueries } from '@service/queries';
import { setUserPassword } from '@service/user.api';
import { userSetPasswordSchema } from '@service/user.schema';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { DialogClose, DialogFooter } from '@ui/dialog';
import { Field, FieldGroup } from '@ui/field';
import { UserWithRole } from 'better-auth/plugins';
import { toast } from 'sonner';

type FormProps = {
  data: UserWithRole;
  onSubmit: (open: boolean) => void;
};

const AdminSetPasswordForm = ({ data, onSubmit }: FormProps) => {
  const queryClient = useQueryClient();

  const { mutate: setUserPasswordMutation, isPending } = useMutation({
    mutationFn: setUserPassword,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...usersQueries.all, 'list'],
      });
      onSubmit(false);
      toast.success(m.users_page_message_set_password_success(), {
        richColors: true,
      });
    },
    onError: (error: ReturnError) => {
      console.error(error);
      const code = error.code as Parameters<
        typeof m.backend_message
      >[0]['code'];
      toast.error(m.backend_message({ code }), {
        richColors: true,
      });
    },
  });

  const form = useAppForm({
    defaultValues: {
      id: data.id,
      password: '',
    },
    validators: {
      onSubmit: userSetPasswordSchema,
    },
    onSubmit: async ({ value }) => {
      setUserPasswordMutation({ data: value });
    },
  });

  return (
    <form
      id="admin-set-password-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="id">
          {(field) => <field.HiddenField />}
        </form.AppField>
        <form.AppField name="password">
          {(field) => (
            <field.TextField
              label={m.change_password_form_new_password()}
              type="password"
            />
          )}
        </form.AppField>
        <Field>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline" type="button">
                {m.ui_cancel_btn()}
              </Button>
            </DialogClose>
            <form.AppForm>
              <form.SubscribeButton
                label={m.ui_save_btn()}
                disabled={isPending}
              />
            </form.AppForm>
          </DialogFooter>
        </Field>
      </FieldGroup>
    </form>
  );
};

export default AdminSetPasswordForm;
