'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 { useGetAddresses } 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: addressesResponse, isLoading: isLoadingAddresses } = useGetAddresses();
    const { data: aboutData } = useGetAbout();

    const address = useMemo(() => {
        if (!editMode || !id) return null;
        return addressesResponse?.data?.find((item) => item.id === id) ?? null;
    }, [editMode, id, addressesResponse?.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 && isLoadingAddresses) {
        return (
            <div className="fixed inset-0 bg-gray-50 flex items-center justify-center">
                <p className="text-sm2 text-disabled-text">در حال بارگذاری...</p>
            </div>
        );
    }

    if (editMode && !address) {
        return (
            <div className="fixed inset-0 bg-gray-50 flex flex-col items-center justify-center gap-4 px-4">
                <p className="text-sm2 text-disabled-text text-center">آدرس مورد نظر یافت نشد</p>
                <button
                    onClick={() => router.back()}
                    className="p-2 rounded-full bg-container shadow-sm"
                >
                    <ArrowLeft size={24} className="stroke-foreground" />
                </button>
            </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}
                    existingAddress={address}
                    formData={formData}
                    isPending={isPending}
                    editMode={editMode}
                    onClose={() => router.back()}
                    onFormDataChange={handleFormDataChange}
                    onSubmit={submitAddress}
                />
            </div>
        </div>
    );
}

export default OrderTrackingPage;
