import { CommunityRepository } from '@amityco/ts-sdk-react-native';
import { useToast } from '../../../../../core/stores/slices/toastSlice';
import useImagePicker from '../../../../hooks/useImagePicker';
import { useForm } from 'react-hook-form';
import { useNavigation } from '@react-navigation/native';
import * as z from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { AmityCommunityPrivacyEnum } from '../../shared/types';
import { useStyles } from '../styles';
import { useMutation } from '@tanstack/react-query';
const schema = z.object({
  image: z.custom().optional(),
  displayName: z.string().trim().min(1).max(30),
  description: z.string().trim().max(180).optional(),
  categories: z.array(z.custom()),
  privacy: z.enum(AmityCommunityPrivacyEnum),
  members: z.array(z.custom())
});
export const useCreateCommunity = () => {
  const {
    showToast
  } = useToast();
  const {
    styles,
    theme
  } = useStyles();
  const {
    watch,
    formState: {
      isDirty,
      isSubmitting,
      isValid
    },
    handleSubmit,
    setValue,
    control
  } = useForm({
    resolver: zodResolver(schema),
    mode: 'onChange',
    defaultValues: {
      image: null,
      displayName: '',
      description: '',
      categories: [],
      privacy: AmityCommunityPrivacyEnum.PUBLIC,
      members: []
    }
  });
  const navigation = useNavigation();
  const {
    openImageGallery,
    progress,
    openCamera
  } = useImagePicker();
  const values = watch();
  const {
    mutateAsync
  } = useMutation({
    mutationFn: CommunityRepository.createCommunity,
    onSuccess: ({
      data
    }) => {
      navigation.navigate('CommunityProfilePage', {
        pop: 2,
        communityId: data === null || data === void 0 ? void 0 : data.communityId
      });
      showToast({
        type: 'success',
        message: 'Successfully created community.'
      });
    },
    onError: () => {
      showToast({
        type: 'failed',
        message: 'Failed to create community. Please try again.'
      });
    }
  });
  const onSubmit = async () => {
    var _values$image;
    const isPublic = values.privacy === AmityCommunityPrivacyEnum.PUBLIC;
    const userIds = isPublic ? [] : values.members.map(item => item.userId);
    await mutateAsync({
      userIds,
      isPublic,
      isDiscoverable: isPublic,
      requiresJoinApproval: false,
      description: values.description,
      displayName: values.displayName,
      avatarFileId: (_values$image = values.image) === null || _values$image === void 0 ? void 0 : _values$image.fileId,
      categoryIds: values.categories.map(category => category.categoryId)
    });
  };
  return {
    isDirty,
    isSubmitting,
    isValid,
    handleSubmit,
    setValue,
    control,
    onSubmit,
    openImageGallery,
    progress,
    openCamera,
    styles,
    theme,
    navigation,
    values
  };
};
//# sourceMappingURL=useCreateCommunity.js.map