import useDebounced from '@/hooks/use-debounced';
import { m } from '@/paraglide/messages';
import { createBox } from '@/service/box.api';
import { createBoxSchema } from '@/service/box.schema';
import { boxQueries, housesQueries } from '@/service/queries';
import { useAppForm } from '@hooks/use-app-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 { useState } from 'react';
import { toast } from 'sonner';

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

const defaultValues: {
  name: string;
  description: string;
  color: string;
  houseId: string;
  tags: string[];
} = {
  name: '',
  description: '',
  color: '#000000',
  houseId: '',
  tags: [],
};

const CreateNewBoxForm = ({ onSubmit }: CreateBoxProp) => {
  const [houseKeyword, setHouseKeyword] = useState('');
  const debouncedHouseKeyword = useDebounced(houseKeyword, 300);
  const { data: house } = useQuery(
    housesQueries.select({ keyword: debouncedHouseKeyword }),
  );

  const queryClient = useQueryClient();

  const { mutate: createBoxMutation, isPending } = useMutation({
    mutationFn: createBox,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...boxQueries.all, 'list'],
      });
      onSubmit(false);
      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,
    validators: {
      onSubmit: createBoxSchema,
      onChange: createBoxSchema,
    },
    onSubmit: ({ value }) => {
      createBoxMutation({ data: value });
    },
  });

  return (
    <form
      id="admin-create-box-form"
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        form.handleSubmit();
      }}
    >
      <FieldGroup>
        <form.AppField name="name">
          {(field) => <field.TextField label={m.boxes_page_form_name()} />}
        </form.AppField>
        <form.AppField name="description">
          {(field) => (
            <field.TextArea label={m.boxes_page_form_description()} />
          )}
        </form.AppField>
        <form.AppField name="color">
          {(field) => (
            <field.TextField type="color" label={m.boxes_page_form_color()} />
          )}
        </form.AppField>
        <form.AppField name="houseId">
          {(field) => (
            <field.SelectHouse
              label={m.boxes_page_form_house()}
              values={house || []}
              placeholder={m.boxes_page_form_house_select_placeholder()}
              searchPlaceholder={m.boxes_page_form_house_select_placeholder()}
              keyword={houseKeyword}
              onKeywordChange={setHouseKeyword}
            />
          )}
        </form.AppField>
        <form.AppField name="tags">
          {(field) => (
            <field.TagInput
              label={m.boxes_page_form_tag()}
              placeholder={m.boxes_page_form_tag_placeholder()}
            />
          )}
        </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 CreateNewBoxForm;
