import { useAppForm } from '@hooks/use-app-form';
import { m } from '@paraglide/messages';
import { usersQueries } from '@service/queries';
import { setUserRole } from '@service/user.api';
import {
  userUpdateRoleBESchema,
  userUpdateRoleSchema,
} 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 SetRoleFormProps = {
  data: UserWithRole;
  onSubmit: (open: boolean) => void;
};

const AdminSetUserRoleForm = ({ data, onSubmit }: SetRoleFormProps) => {
  const queryClient = useQueryClient();

  const defaultFormValues = {
    id: data.id,
    role: data.role,
  };

  const { mutate: updateRoleMutation, isPending } = useMutation({
    mutationFn: setUserRole,
    onSuccess: () => {
      queryClient.refetchQueries({
        queryKey: usersQueries.all,
      });
      onSubmit(false);
      toast.success(m.users_page_message_set_role_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: userUpdateRoleSchema.parse(defaultFormValues),
    validators: {
      onChange: userUpdateRoleSchema,
      onSubmit: userUpdateRoleSchema,
    },
    onSubmit: async ({ value }) => {
      updateRoleMutation({ data: userUpdateRoleBESchema.parse(value) });
    },
  });

  return (
    <form
      id="admin-set-user-role-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="id">
          {(field) => <field.HiddenField />}
        </form.AppField>
        <form.AppField name="role">
          {(field) => (
            <field.Select
              label={m.profile_form_role()}
              placeholder={m.users_page_ui_select_placeholder_role()}
              values={[
                { value: 'admin', label: m.role_tags({ role: 'admin' }) },
                { value: 'user', label: m.role_tags({ role: 'user' }) },
              ]}
            />
          )}
        </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 AdminSetUserRoleForm;
