'use client';

import { useSearchParams } from 'next/navigation';
import React, { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
import useToggle from '@/hooks/helpers/useToggle';
import { useAuthStore } from '@/zustand/authStore';
import { MarkerData, NominatimReverseGeocodingResponse } from '../types/Types';
import { ConfirmPositionModal } from './components/ConfirmPositionModal';
import { AddressDetailsModal } from './components/AddressDetailsModal';
import { useAddressForm } from './hooks/useAddressForm';
import { fetchAddressFromCoordinates } from './utils/fetchAddress';
import { useGetAddressById } from '../hooks/useAddressData';
import { useGetAbout } from '@/app/[name]/(Main)/about/hooks/useAboutData';

const CustomMap = dynamic(
    () => import('@/components/map/CustomMap'),
    { ssr: false }
);

function OrderTrackingPage() {

    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 [selectedPosition, setSelectedPosition] = useState<[number, number] | null>(null);
    const [selectedAddress, setSelectedAddress] = useState<NominatimReverseGeocodingResponse | null>(null);
    const [markers, setMarkers] = useState<MarkerData[]>([]);
    const [initialPositionSet, setInitialPositionSet] = useState(false);

    const restaurant = aboutData?.data;

    const [mapCenter, setMapCenter] = useState<[number, number]>(() => [
        Number(params?.get('lat')) || 35.6892,
        Number(params?.get('lon')) || 51.3890
    ]);
    const { state: confirmModal, toggle: toggleConfirmModal, set: setConfirmModal } = useToggle();
    const { state: detailsModal, toggle: _toggleDetailsModal, set: setDetailsModal } = useToggle();

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

    useEffect(() => {
        if (editMode && address) {
            setMapCenter([address.latitude, address.longitude]);
        } else if (restaurant?.latitude && restaurant?.longitude) {
            setMapCenter([restaurant.latitude, restaurant.longitude]);
        }
    }, [editMode, address, restaurant]);

    useEffect(() => {
        if (editMode && address && !initialPositionSet) {
            const position: [number, number] = [address.latitude, address.longitude];
            setSelectedPosition(position);
            setInitialPositionSet(true);

            fetchAddressFromCoordinates(address.latitude, address.longitude).then((addr) => {
                if (addr) {
                    setSelectedAddress(addr);
                    setDetailsModal(true);
                }
            });
        }
    }, [editMode, address, initialPositionSet, setDetailsModal]);


    useEffect(() => {
        const initializeMarkers = async () => {
            const L = (await import('leaflet')).default;

            const iconHtml = `
                <div style="display: flex; flex-direction: column; align-items: center; text-align: center;">
                    <img src="/icons/restaurant-marker.svg" alt="موقعیت رستوران" style="width: 32px; height: 40px; display: block;" />
                </div>
            `;

            const restaurantPosition: [number, number] | null =
                restaurant?.latitude && restaurant?.longitude
                    ? [restaurant.latitude, restaurant.longitude]
                    : null;

            const markersToSet: MarkerData[] = [];

            if (restaurantPosition) {
                markersToSet.push({
                    position: restaurantPosition,
                    title: 'موقعیت رستوران',
                    icon: L.divIcon({
                        html: iconHtml,
                        className: 'custom-restaurant-marker',
                        iconSize: [40, 40],
                        iconAnchor: [20, 40],
                        popupAnchor: [0, -40],
                    })
                });
            }

            setMarkers(markersToSet);
        };

        initializeMarkers();
    }, [restaurant]);

    const handlePositionSelect = (position: [number, number]) => {
        setSelectedPosition((prev) => {
            if (prev && prev[0] === position[0] && prev[1] === position[1]) {
                return prev;
            }
            setSelectedAddress(null);
            return position;
        });
        if (editMode && detailsModal) {
            setDetailsModal(false);
        }
        setConfirmModal(position && true);
    };

    const handleZoomChange = (zoom: number) => {
        console.log('Zoom level:', zoom);
    };

    const handleMapClick = (e: L.LeafletMouseEvent) => {
        console.log('Map clicked at:', e.latlng);
    };

    const toggleDetailsModal = async () => {
        if (!selectedPosition) {
            setConfirmModal(false);
            setDetailsModal(false);
            return;
        }
        setConfirmModal(false);
        _toggleDetailsModal();
        if (!detailsModal) {
            const address = await fetchAddressFromCoordinates(
                selectedPosition[0],
                selectedPosition[1]
            );
            setSelectedAddress(address);
        }
    };

    const handleChangePosition = () => {
        setDetailsModal(false);
        setSelectedPosition(null);
        setSelectedAddress(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
    }

    const hasServiceArea = restaurant?.serviceArea &&
        restaurant.serviceArea.coordinates &&
        restaurant.serviceArea.coordinates.length > 0;

    return (
        <div className="fixed inset-0 bg-gray-50">
            <div className="absolute inset-0">
                <CustomMap
                    initialPosition={mapCenter}
                    zoom={14}
                    markers={markers}
                    serviceArea={restaurant?.serviceArea || null}
                    onPositionSelect={handlePositionSelect}
                    onZoomChange={handleZoomChange}
                    onClick={handleMapClick}
                />
            </div>

            {hasServiceArea && (
                <div className="absolute top-4 left-4 right-4 z-1000 max-w-sm">
                    <div className="bg-blue-50/90 border border-blue-200 rounded-lg p-3 shadow-sm">
                        <p className="text-xs text-blue-800">
                            محدوده سرویس‌دهی روی نقشه با رنگ آبی مشخص شده است
                        </p>
                    </div>
                </div>
            )}

            <div className="absolute bottom-0 left-0 right-0 z-1000">
                <div className='relative w-full h-full'>
                    <ConfirmPositionModal
                        visible={confirmModal}
                        onConfirm={toggleDetailsModal}
                        onCancel={toggleConfirmModal}
                    />

                    <AddressDetailsModal
                        visible={detailsModal}
                        selectedAddress={selectedAddress}
                        formData={formData}
                        isPending={isPending}
                        editMode={editMode}
                        onClose={toggleDetailsModal}
                        onChangePosition={handleChangePosition}
                        onFormDataChange={handleFormDataChange}
                        onSubmit={submitAddress}
                    />
                </div>
            </div>
        </div>
    );
}

export default OrderTrackingPage;