import InputGroup from "@/components/auth/InputGroup";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { showToast } from "@/utils/toast";
import { useForm } from "react-hook-form";
import { View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
type ChangePasswordType = {
  current_password: string;
  new_password: string;
  new_password_confirmation: string;
};

export default function ChangePassword() {
  const {
    control,
    formState: { errors: formErrors },
    handleSubmit,
    reset,
    getValues,
  } = useForm<ChangePasswordType>();

  const {
    mutate: changePasswordMutate,
    isLoading: changePasswordMutateLoading,
    backendErrors: errors,
  } = useQueryMutation({
    url: "/client/profile/password",
    isUpdateMethod: true,
  });

  const onSubmit = handleSubmit((data) => {
    changePasswordMutate(data, {
      onSuccess: () => {
        showToast({
          type: "success",
          text: "Password changed successfully",
        });
        reset();
      },
      onError: (error: any) => {
        showToast({
          type: "error",
          text: error?.message || "Failed to change password",
        });
      },
    });
  });
  return (
    <SafeAreaView className="px-4 bg-white flex-1">
      <BackButtonTitle title="Change Password" />

      <View className="gap-y-6 pt-12">
        <InputGroup
          control={control}
          label="Old Password"
          name="current_password"
          error={formErrors.current_password}
          backendError={errors?.current_password}
          secureTextEntry={true}
          rules={{ required: "Old Password is required" }}
        />

        <InputGroup
          control={control}
          label="New Password"
          name="new_password"
          error={formErrors.new_password}
          backendError={errors?.new_password}
          secureTextEntry={true}
        />
        <InputGroup
          control={control}
          label="Confirm New Password"
          name="new_password_confirmation"
          error={formErrors.new_password_confirmation}
          backendError={errors?.new_password_confirmation}
          secureTextEntry={true}
          rules={{
            required: "Confirm Password is required",
            validate: (value) =>
              value === getValues("new_password") || "Passwords do not match",
          }}
        />

        <Button
          onPress={onSubmit}
          isLoading={changePasswordMutateLoading}
          text="Change Password"
        />
      </View>
    </SafeAreaView>
  );
}
