import { toast } from "@/components/Toast";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useCreateAddress, useUpdateAddress } from "../../hooks/useAddressData";
import { Address, CreateAddressType, NominatimReverseGeocodingResponse, UpdateAddressType } from "../../types/Types";

interface UseAddressFormProps {
  selectedPosition: [number, number] | null;
  selectedAddress: NominatimReverseGeocodingResponse | null;
  fallbackPosition?: [number, number] | null;
  initialPhone?: string;
  editMode?: boolean;
  addressData?: Address | null;
}

export const useAddressForm = ({ selectedPosition, selectedAddress, fallbackPosition = [0, 0], initialPhone = "", editMode = false, addressData = null }: UseAddressFormProps) => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get("redirect");
  const { mutate: createAddress, isPending: isCreating } = useCreateAddress();
  const { mutate: updateAddress, isPending: isUpdating } = useUpdateAddress();
  const isPending = isCreating || isUpdating;

  const [formData, setFormData] = useState({
    title: "",
    addressDetails: "",
    phone: initialPhone,
    postalCode: "",
    isDefault: false,
  });

  useEffect(() => {
    if (editMode && addressData) {
      setFormData({
        title: addressData.title || "",
        addressDetails: addressData.address || "",
        phone: addressData.phone || initialPhone,
        postalCode: addressData.postalCode || "",
        isDefault: addressData.isDefault || false,
      });
    }
  }, [editMode, addressData, initialPhone]);

  const handleFormDataChange = (data: Partial<typeof formData>) => {
    setFormData((prev) => ({ ...prev, ...data }));
  };

  const submitAddress = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const positionToUse: [number, number] = selectedPosition || fallbackPosition || [0, 0];

    if (!formData.title.trim()) {
      toast("لطفا عنوان آدرس را وارد کنید", "error");
      return;
    }

    if (!formData.addressDetails.trim()) {
      toast("لطفا جزئیات آدرس را وارد کنید", "error");
      return;
    }

    if (!formData.phone.trim()) {
      toast("لطفا شماره تلفن را وارد کنید", "error");
      return;
    }

    const baseAddressData = {
      title: formData.title,
      address: formData.addressDetails,
      postalCode: formData.postalCode || selectedAddress?.address?.postcode || addressData?.postalCode || "",
      latitude: positionToUse[0],
      longitude: positionToUse[1],
      phone: formData.phone,
      isDefault: formData.isDefault,
    };

    if (editMode && addressData) {
      const updateData: UpdateAddressType = {
        ...baseAddressData,
        id: addressData.id,
      };

      updateAddress(updateData, {
        onSuccess: () => {
          toast("آدرس با موفقیت به‌روزرسانی شد", "success");
          if (redirect) {
            router.replace(redirect);
          } else {
            router.back();
          }
        },
        onError: (error) => {
          const errorMessage = error instanceof Error ? error.message : "خطا در به‌روزرسانی آدرس";
          toast(errorMessage, "error");
        },
      });
    } else {
      const createData: CreateAddressType = baseAddressData;

      createAddress(createData, {
        onSuccess: () => {
          toast("آدرس با موفقیت ثبت شد", "success");
          if (redirect) {
            router.replace(redirect);
          } else {
            router.back();
          }
        },
        onError: (error) => {
          const errorMessage = error instanceof Error ? error.message : "خطا در ثبت آدرس";
          toast(errorMessage, "error");
        },
      });
    }
  };

  return {
    formData,
    isPending,
    handleFormDataChange,
    submitAddress,
  };
};
