'use client';

import { useSearchParams, useRouter } from 'next/navigation';
import React, { useMemo } from 'react';
import { ArrowLeft } from 'iconsax-react';
import { useAuthStore } from '@/zustand/authStore';
import { AddressDetailsModal } from './components/AddressDetailsModal';
import { useAddressForm } from './hooks/useAddressForm';
import { useGetAddressById } from '../hooks/useAddressData';
import { useGetAbout } from '@/app/[name]/(Main)/about/hooks/useAboutData';

function OrderTrackingPage() {
    const router = useRouter();
    const params = useSearchParams();
    const id = params.get('id');
    const editMode = !!id;

    const { data: addressResponse, isLoading: isLoadingAddress } = useGetAddressById(id);
    const { data: aboutData } = useGetAbout();
    const address = addressResponse?.data;
    const user = useAuthStore((state) => state.user);
    const restaurant = aboutData?.data;

    const fallbackPosition = useMemo<[number, number] | null>(() => {
        if (editMode && address?.latitude && address?.longitude) {
            return [address.latitude, address.longitude];
        }

        const latFromQuery = Number(params?.get('lat'));
        const lonFromQuery = Number(params?.get('lon'));
        if (!Number.isNaN(latFromQuery) && !Number.isNaN(lonFromQuery) && latFromQuery !== 0 && lonFromQuery !== 0) {
            return [latFromQuery, lonFromQuery];
        }

        if (restaurant?.latitude && restaurant?.longitude) {
            return [restaurant.latitude, restaurant.longitude];
        }

        return null;
    }, [
        editMode,
        address?.latitude,
        address?.longitude,
        params,
        restaurant?.latitude,
        restaurant?.longitude
    ]);

    const { formData, isPending, handleFormDataChange, submitAddress } = useAddressForm({
        selectedPosition: null,
        selectedAddress: null,
        fallbackPosition,
        initialPhone: user?.number || '',
        editMode,
        addressData: address || null,
    });

    if (editMode && isLoadingAddress) {
        return (
            <div className="fixed inset-0 bg-gray-50 flex items-center justify-center">
                <p className="text-sm2 text-disabled-text">در حال بارگذاری...</p>
            </div>
        );
    }

    if (!restaurant) {
        return null
    }

    return (
        <div className="fixed inset-0 bg-gray-50 flex flex-col">
            <div className="px-4 pt-4">
                <button
                    onClick={() => router.back()}
                    className="p-2 rounded-full bg-container shadow-sm"
                >
                    <ArrowLeft size={24} className="stroke-foreground" />
                </button>
            </div>

            <div className="flex-1 relative">
                <AddressDetailsModal
                    visible
                    selectedAddress={null}
                    formData={formData}
                    isPending={isPending}
                    editMode={editMode}
                    onClose={() => router.back()}
                    onFormDataChange={handleFormDataChange}
                    onSubmit={submitAddress}
                />
            </div>
        </div>
    );
}

export default OrderTrackingPage;