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 { ReturnError } from '@/types/common';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { UserWithRole } from 'better-auth/plugins';
import { toast } from 'sonner';
import { Button } from '../ui/button';
import { DialogClose, DialogFooter } from '../ui/dialog';
import { Field, FieldGroup } from '../ui/field';

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

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

  const setUserPasswordMutation = 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);
      toast.error(m.backend_message({ code: error.code }), {
        richColors: true,
      });
    },
  });

  const form = useAppForm({
    defaultValues: {
      id: data.id,
      password: '',
    },
    validators: {
      onSubmit: userSetPasswordSchema,
    },
    onSubmit: async ({ value }) => {
      setUserPasswordMutation.mutate({ 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()} />
            </form.AppForm>
          </DialogFooter>
        </Field>
      </FieldGroup>
    </form>
  );
};

export default AdminSetPasswordForm;
