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

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

export const useAddressForm = ({
    selectedPosition,
    selectedAddress,
    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: '',
        city: '',
        province: '',
        isDefault: false,
    });

    useEffect(() => {
        if (editMode && addressData) {
            setFormData({
                title: addressData.title || '',
                addressDetails: addressData.address || '',
                city: addressData.city || '',
                province: addressData.province || '',
                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();

        if (!selectedPosition || !selectedAddress) {
            toast('لطفا موقعیت را روی نقشه انتخاب کنید', 'error');
            return;
        }

        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,
            city: formData.city || selectedAddress.address.city || selectedAddress.address.district || '',
            province: formData.province || selectedAddress.address.province || selectedAddress.address.state || '',
            postalCode: formData.postalCode || selectedAddress.address.postcode || '',
            latitude: selectedPosition[0],
            longitude: selectedPosition[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,
    };
};

