import { useAuth } from '@/components/auth/auth-provider';
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 { createHouse } from '@service/house.api';
import { houseCreateSchema } from '@service/house.schema';
import { housesQueries, usersQueries } from '@service/queries';
import { uuid } from '@tanstack/react-form';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Button } from '@ui/button';
import { DialogClose, DialogFooter } from '@ui/dialog';
import { Field, FieldGroup } from '@ui/field';
import { slugify } from '@utils/helper';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

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

const CreateNewHouseForm = ({ onSubmit, isPersonal = false }: FormProps) => {
  const { session } = useAuth();
  const [userKeyword, setUserKeyword] = useState('');
  const debouncedUserKeyword = useDebounced(userKeyword, 300);
  const { data: users } = useQuery(
    usersQueries.select({ keyword: debouncedUserKeyword }),
  );

  const queryClient = useQueryClient();

  const queryKey = isPersonal ? 'currentUser' : 'list';

  const { mutate: createHouseMutation, isPending } = useMutation({
    mutationFn: createHouse,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...housesQueries.all, queryKey],
      });
      onSubmit(false);
      toast.success(m.houses_page_message_create_house_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: {
      name: '',
      userId: '',
      color: '#000000',
    },
    validators: {
      onChange: houseCreateSchema,
      onSubmit: houseCreateSchema,
    },
    onSubmit: async ({ value }) => {
      const slug = `${slugify(value.name)}-${uuid().slice(0, 5)}`;
      const { data, error } = await authClient.organization.checkSlug({
        slug,
      });
      if (error) {
        toast.error(error.message, {
          richColors: true,
        });
      }
      if (data?.status) {
        createHouseMutation({ data: { ...value, slug } });
      }
    },
  });

  useEffect(() => {
    if (isPersonal) {
      form.setFieldValue('userId', session.user.id);
    }
  }, []);

  return (
    <form
      id="admin-create-house-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="name">
          {(field) => <field.TextField label={m.houses_page_form_name()} />}
        </form.AppField>
        <form.AppField name="color">
          {(field) => (
            <field.TextField type="color" label={m.houses_page_form_color()} />
          )}
        </form.AppField>
        {!isPersonal && (
          <form.AppField name="userId">
            {(field) => (
              <field.SelectUser
                label={m.houses_page_form_create_for()}
                values={users ?? []}
                placeholder={m.houses_page_form_user_select_placeholder()}
                searchPlaceholder={m.houses_page_form_user_select_search_placeholder()}
                keyword={userKeyword}
                onKeywordChange={setUserKeyword}
              />
            )}
          </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 CreateNewHouseForm;
