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

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

const AdminUpdateUserInfoForm = ({ data, onSubmit }: UpdateUserFormProps) => {
  const queryClient = useQueryClient();

  const { mutate: updateUserMutation, isPending } = useMutation({
    mutationFn: updateUserInformation,
    onSuccess: () => {
      queryClient.refetchQueries({
        queryKey: usersQueries.all,
      });
      onSubmit(false);
      toast.success(m.users_page_message_update_info_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,
      name: data.name,
    },
    validators: {
      onChange: userUpdateInfoSchema,
    },
    onSubmit: async ({ value }) => {
      updateUserMutation({ data: value });
    },
  });

  return (
    <form
      id="admin-update-user-info-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="id">
          {(field) => <field.HiddenField />}
        </form.AppField>
        <form.AppField name="name">
          {(field) => <field.TextField label={m.profile_form_name()} />}
        </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 AdminUpdateUserInfoForm;
