import { useAppForm } from '@hooks/use-app-form';
import { m } from '@paraglide/messages';
import { usersQueries } from '@service/queries';
import { createUser } from '@service/user.api';
import { userCreateBESchema, userCreateFESchema } 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 { toast } from 'sonner';

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

const AdminCreateUserForm = ({ onSubmit }: FormProps) => {
  const queryClient = useQueryClient();

  const { mutate: createUserMutation, isPending } = useMutation({
    mutationFn: createUser,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...usersQueries.all, 'list'],
      });
      onSubmit(false);
      toast.success(m.users_page_message_created_user_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: {
      email: '',
      password: '',
      name: '',
      role: '',
    },
    validators: {
      onChange: userCreateFESchema,
      onSubmit: userCreateFESchema,
    },
    onSubmit: ({ value }) => {
      createUserMutation({ data: userCreateBESchema.parse(value) });
    },
  });

  return (
    <form
      id="admin-create-user-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="email">
          {(field) => <field.TextField label={m.login_page_form_email()} />}
        </form.AppField>
        <form.AppField name="password">
          {(field) => (
            <field.TextField
              label={m.login_page_form_password()}
              type="password"
            />
          )}
        </form.AppField>
        <form.AppField name="name">
          {(field) => <field.TextField label={m.profile_form_name()} />}
        </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_signup_btn()}
                disabled={isPending}
              />
            </form.AppForm>
          </DialogFooter>
        </Field>
      </FieldGroup>
    </form>
  );
};

export default AdminCreateUserForm;
