import { useAppForm } from '@hooks/use-app-form';
import { authClient } from '@lib/auth-client';
import { m } from '@paraglide/messages';
import { updateHouse } from '@service/house.api';
import { houseEditSchema } from '@service/house.schema';
import { housesQueries } from '@service/queries';
import { uuid } from '@tanstack/react-form';
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 { slugify } from '@utils/helper';
import { toast } from 'sonner';

type EditHouseFormProps = {
  data: HouseWithMembers;
  onSubmit: (open: boolean) => void;
  mutateKey: string;
};

const EditHouseForm = ({ data, onSubmit, mutateKey }: EditHouseFormProps) => {
  const { refetch } = authClient.useActiveOrganization();
  const queryClient = useQueryClient();

  const { mutate: updateHouseMutation, isPending } = useMutation({
    mutationFn: updateHouse,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [...housesQueries.all, mutateKey],
      });
      onSubmit(false);
      refetch();
      toast.success(m.houses_page_message_update_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: {
      id: data.id,
      name: data.name,
      color: data.color || '#000000',
    },
    validators: {
      onChange: houseEditSchema,
      onSubmit: houseEditSchema,
    },
    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) {
        updateHouseMutation({ data: { ...value, slug } });
      }
    },
  });

  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>
        <div className="flex flex-row items-center gap-2">
          <span className="font-medium">{m.houses_page_form_user()}:</span>
          <span>
            {
              data.members.filter((member) => member.role === 'owner')[0].user
                .name
            }
          </span>
        </div>
        <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 EditHouseForm;
