import { useState } from "react";
import { set, useForm } from "react-hook-form";
import * as ImagePicker from "expo-image-picker";

export type EditProfileFormValues = {
  name: string;
  lastName: string;
  profileImage?: File | null;
};

export const useEditProfile = () => {
  const { control, handleSubmit, setValue } = useForm<EditProfileFormValues>();
  const [profileImage, setProfileImage] = useState<string | null>(null);

  const pickProfileImage = async () => {
    const permissions = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (!permissions.granted) {
      return;
    }
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
    });

    if (!result.canceled) {
      console.log(result.assets[0].uri);
      setProfileImage(result.assets[0].uri);
    }
  };

  const onValidSubmit = async (data: EditProfileFormValues) => {
    if (profileImage) {
      data.profileImage = new File([profileImage], "profileImage");
      setValue("profileImage", data.profileImage);
    }
    //TODO: Send data to the server
    console.log(data);
  };

  const onInvalidSubmit = (errors: any) => {
    console.log(errors);
  };

  const onSubmit = async () => {
    await handleSubmit(onValidSubmit, onInvalidSubmit)();
  };
  return { onSubmit, control, pickProfileImage, profileImage };
};
