import { Button } from '@/components/ui/button';
import { DialogClose, DialogFooter } from '@/components/ui/dialog';
import { useAppForm } from '@/hooks/use-app-form';
import useDebounced from '@/hooks/use-debounced';
import { authClient } from '@/lib/auth-client';
import { m } from '@/paraglide/messages';
import { invitationMember } from '@/service/house.api';
import {
  invitationCreateBESchema,
  invitationCreateFESchema,
} from '@/service/house.schema';
import { housesQueries, usersQueries } from '@/service/queries';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Field, FieldGroup, FieldLabel } from '@ui/field';
import { useState } from 'react';
import { toast } from 'sonner';

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

const UserInviteMemberForm = ({ onSubmit }: FormProps) => {
  const { data: activeHouse, refetch } = authClient.useActiveOrganization();
  const [userKeyword, setUserKeyword] = useState('');
  const debouncedUserKeyword = useDebounced(userKeyword, 300);
  const { data: users } = useQuery(
    usersQueries.select({ keyword: debouncedUserKeyword }, true),
  );
  const queryClient = useQueryClient();

  if (!activeHouse) return null;

  const { mutate: invitationMemberMutation, isPending } = useMutation({
    mutationFn: invitationMember,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...housesQueries.all, 'currentUser'],
      });
      onSubmit(false);
      refetch();
      toast.success(m.houses_page_message_invite_member_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: '',
      houseId: activeHouse.id,
      role: '',
    },
    validators: {
      onChange: invitationCreateFESchema,
      onSubmit: invitationCreateFESchema,
    },
    onSubmit: async ({ value }) => {
      invitationMemberMutation({ data: invitationCreateBESchema.parse(value) });
    },
  });
  return (
    <form
      id="user-invite-member-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <Field>
          <FieldLabel htmlFor="house_name">
            {m.houses_page_form_name()}:
          </FieldLabel>
          <div className="flex gap-2">{activeHouse.name}</div>
        </Field>
        <form.AppField name="email">
          {(field) => (
            <field.SelectUser
              label={m.houses_page_form_user()}
              values={users ?? []}
              placeholder={m.houses_page_form_user_select_placeholder()}
              searchPlaceholder={m.houses_page_form_user_select_search_placeholder()}
              keyword={userKeyword}
              onKeywordChange={setUserKeyword}
              selectKey="email"
            />
          )}
        </form.AppField>
        <form.AppField name="role">
          {(field) => (
            <field.Select
              label={m.profile_form_role()}
              placeholder={m.users_page_ui_select_placeholder_role()}
              values={[
                { value: 'owner', label: m.role_tags({ role: 'owner' }) },
                { value: 'admin', label: m.role_tags({ role: 'admin' }) },
                { value: 'member', label: m.role_tags({ role: 'member' }) },
              ]}
            />
          )}
        </form.AppField>
        <Field>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline" type="button">
                {m.ui_cancel_btn()}
              </Button>
            </DialogClose>
            <form.AppForm>
              <form.SubscribeButton
                label={m.ui_confirm_btn()}
                disabled={isPending}
              />
            </form.AppForm>
          </DialogFooter>
        </Field>
      </FieldGroup>
    </form>
  );
};

export default UserInviteMemberForm;
