import React, { useState, useCallback, useRef, useEffect } from 'react';
import { UploadCloudIcon, TypeIcon, ScaleIcon, MapPinIcon, TagIcon, DollarSignIcon, PhoneIcon, XIcon, ChevronDownIcon, CrosshairIcon, HomeIcon, ListIcon, PackageIcon, PlaneIcon, CrmIcon, SearchIcon } from '../Icons';
import { API_BASE_URL } from '@/src/config.js';
declare const L: any;

type ShipmentMode = 'send' | 'carry';
type PriceType = 'fixed' | 'negotiable';
type Currency = 'IRT' | 'USD' | 'CAD' | 'IQD';
type LocationField = 'origin' | 'destination';

interface ImageFile {
    id: number;
    url: string;
    file: File;
}

interface RegisterShipmentPageProps {
    showError: (message: string) => void;
    showSuccess: (message: string) => void;
}

// سرویس API (برای تطبیق با کنترلر لاراول)
const shipmentAPI = {
    registerShipment: (data: any, images: File[] = []) => {
        const formData = new FormData();

        // اضافه کردن فیلدهای اصلی
        Object.keys(data).forEach(key => {
            if (typeof data[key] === 'object' && data[key] !== null) {
                // برای فیلدهای تو در تو مانند origin و destination
                Object.keys(data[key]).forEach(subKey => {
                    formData.append(`${key}[${subKey}]`, data[key][subKey]);
                });
            } else {
                formData.append(key, data[key]);
            }
        });

        // اضافه کردن تصاویر
        images.forEach((image, index) => {
            formData.append(`images[${index}]`, image);
        });

        return fetch(`${API_BASE_URL}/shipments/register`, {
            method: 'POST',
            headers: {
                'X-Auth-Token': localStorage.getItem('auth_token')
            },
            body: formData
        });
    },

    registerCarryTrip: (data: any) => {
        const formData = new FormData();

        // اضافه کردن فیلدهای اصلی
        Object.keys(data).forEach(key => {
            if (typeof data[key] === 'object' && data[key] !== null) {
                // برای فیلدهای تو در تو مانند origin و destination
                Object.keys(data[key]).forEach(subKey => {
                    formData.append(`${key}[${subKey}]`, data[key][subKey]);
                });
            } else {
                formData.append(key, data[key]);
            }
        });

        return fetch(`${API_BASE_URL}/shipments/carry`, {
            method: 'POST',
            headers: {
                'X-Auth-Token': localStorage.getItem('auth_token')
            },
            body: formData
        });
    },
};

const RegisterShipmentPage: React.FC<RegisterShipmentPageProps> = ({ showError, showSuccess }) => {
    const [shipmentMode, setShipmentMode] = useState<ShipmentMode>('send');
    const [priceType, setPriceType] = useState<PriceType>('fixed');
    const [currency, setCurrency] = useState<Currency>('IRT');
    const [showPhoneNumber, setShowPhoneNumber] = useState(false);
    const [images, setImages] = useState<ImageFile[]>([]);
    const [modalState, setModalState] = useState<{ isOpen: boolean; field: LocationField | null }>({ isOpen: false, field: null });
    const [origin, setOrigin] = useState<{ lat: number; lng: number } | null>(null);
    const [destination, setDestination] = useState<{ lat: number; lng: number } | null>(null);
    const [originCountry, setOriginCountry] = useState('');
    const [originCity, setOriginCity] = useState('');
    const [originAddress, setOriginAddress] = useState('');
    const [destinationCountry, setDestinationCountry] = useState('');
    const [destinationCity, setDestinationCity] = useState('');
    const [destinationAddress, setDestinationAddress] = useState('');
    const [departureDate, setDepartureDate] = useState('');
    const [arrivalDate, setArrivalDate] = useState('');
    const [tripDescription, setTripDescription] = useState('');
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [weight, setWeight] = useState('');
    const [category, setCategory] = useState('');
    const [amount, setAmount] = useState('');
    const [carryWeight, setCarryWeight] = useState('');
    const [carryAmount, setCarryAmount] = useState('');
    const [loading, setLoading] = useState(false);

    const originText = origin ? `${origin.lat.toFixed(5)}, ${origin.lng.toFixed(5)}` : '';
    const destinationText = destination ? `${destination.lat.toFixed(5)}, ${destination.lng.toFixed(5)}` : '';

    const currencies = [
        { value: 'IRT', label: 'تومان' },
        { value: 'USD', label: 'دلار آمریکا' },
        { value: 'CAD', label: 'دلار کانادا' },
        { value: 'IQD', label: 'دینار' },
    ];

    // Reset form on mode change
    useEffect(() => {
        setOrigin(null);
        setDestination(null);
        setOriginCountry('');
        setOriginCity('');
        setOriginAddress('');
        setDestinationCountry('');
        setDestinationCity('');
        setDestinationAddress('');
        setTitle('');
        setDescription('');
        setWeight('');
        setCategory('');
        setAmount('');
        setDepartureDate('');
        setArrivalDate('');
        setTripDescription('');
        setCarryWeight('');
        setCarryAmount('');
        setImages([]);
        setPriceType('fixed');
        setCurrency('IRT');
        setShowPhoneNumber(false);
    }, [shipmentMode]);

    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files) {
            const newImages: ImageFile[] = Array.from(files).map((file) => ({
                id: Date.now() + Math.random(),
                url: URL.createObjectURL(file),
                file,
            }));
            setImages(prev => [...prev, ...newImages]);
        }
    };

    const removeImage = (id: number) => {
        setImages(prev => prev.filter(img => img.id !== id));
    };

    const onDrop = useCallback((event: React.DragEvent<HTMLLabelElement>) => {
        event.preventDefault();
        event.stopPropagation();
        const files = event.dataTransfer.files;
        if (files && files.length > 0) {
            const newImages: ImageFile[] = Array.from(files)
                .filter((file: File) => file.type.startsWith('image/'))
                .map((file) => ({
                    id: Date.now() + Math.random(),
                    url: URL.createObjectURL(file),
                    file,
                }));
            setImages(prev => [...prev, ...newImages]);
        }
    }, []);

    const onDragOver = (event: React.DragEvent<HTMLLabelElement>) => {
        event.preventDefault();
        event.stopPropagation();
    };

    const openModal = (field: LocationField) => {
        setModalState({ isOpen: true, field });
    };

    const closeModal = () => {
        setModalState({ isOpen: false, field: null });
    };

    const confirmLocation = (location: { lat: number; lng: number }) => {
        if (modalState.field === 'origin') {
            setOrigin(location);
        } else if (modalState.field === 'destination') {
            setDestination(location);
        }
        closeModal();
    };

    // تابع برای تبدیل تاریخ شمسی به میلادی
    const convertJalaliToGregorian = (jalaliDate: string): string => {
        if (!jalaliDate) return '';

        const [year, month, day] = jalaliDate.split('/').map(Number);

        // تبدیل ساده شمسی به میلادی (برای دقت بیشتر از کتابخانه jalali-moment استفاده کنید)
        const gregorianYear = year + 621;
        const gregorianDate = new Date(gregorianYear, month - 1, day);

        // فرمت YYYY-MM-DD
        return gregorianDate.toISOString().split('T')[0];
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);

        try {
            const commonData = {
                origin: {
                    country: originCountry,
                    city: originCity,
                    address: originAddress,
                    coordinates: origin ? `${origin.lat},${origin.lng}` : ""
                },
                destination: {
                    country: destinationCountry,
                    city: destinationCity,
                    address: destinationAddress,
                    coordinates: destination ? `${destination.lat},${destination.lng}` : ""
                },
                price_type: priceType,
                show_phone: showPhoneNumber ? 1 : 0, // مهم: boolean + اسم درست
            };

            // فقط وقتی قیمت ثابت بود، ارز و مبلغ بفرست
            if (priceType === 'fixed') {
                commonData.currency = currency;
                if (shipmentMode === 'send') {
                    commonData.amount = amount;
                } else {
                    commonData.amount = carryAmount;
                }
            }

            let response;
            if (shipmentMode === 'send') {
                const sendData = {
                    ...commonData,
                    title,
                    description,
                    weight,
                    category,
                };

                // فقط در حالت send تصاویر بفرست
                response = await shipmentAPI.registerShipment(sendData, images.map(img => img.file));
            } else {
                // تبدیل تاریخ شمسی به میلادی (بهتر و دقیق‌تر)
                const toGregorian = (jalali: string) => {
                    if (!jalali) return null;
                    const [y, m, d] = jalali.split('/').map(Number);
                    const gd = new Date(y + 621, m - 1, d);
                    return gd.toISOString().split('T')[0];
                };

                const carryData = {
                    ...commonData,
                    departure_date: toGregorian(departureDate),
                    arrival_date: arrivalDate ? toGregorian(arrivalDate) : null,
                    carry_weight_capacity: carryWeight,
                    trip_description: tripDescription || '', // ⬅️ اینجا,
                };

                response = await shipmentAPI.registerCarryTrip(carryData); // بدون تصاویر
            }

            const result = await response.json();

            if (!response.ok) {
                const firstError = result.errors
                    ? Object.values(result.errors)[0]
                    : result.message;
                showError(Array.isArray(firstError) ? firstError[0] : firstError);
                return;
            }

            showSuccess("با موفقیت ثبت شد!");
            resetForm();

        } catch (err: any) {
            showError("خطای اتصال به سرور");
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    // تابع ریست فرم
    const resetForm = () => {
        setOrigin(null);
        setDestination(null);
        setOriginCountry('');
        setOriginCity('');
        setOriginAddress('');
        setDestinationCountry('');
        setDestinationCity('');
        setDestinationAddress('');
        setTitle('');
        setDescription('');
        setWeight('');
        setCategory('');
        setAmount('');
        setDepartureDate('');
        setArrivalDate('');
        setTripDescription('');
        setCarryWeight('');
        setCarryAmount('');
        setImages([]);
        setShowPhoneNumber(false);
        setPriceType('fixed');
        setCurrency('IRT');
    };

    return (
        <div className="flex flex-col space-y-8">
            <div>
                <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
                    {shipmentMode === 'send' ? 'ثبت مرسوله جدید' : 'ثبت سفر جدید'}
                </h1>
                <p className="text-gray-500 dark:text-gray-400 mt-1">
                    {shipmentMode === 'send'
                        ? 'اطلاعات مرسوله خود را برای حمل وارد کنید.'
                        : 'اطلاعات سفر خود را برای حمل مرسوله وارد کنید.'}
                </p>
            </div>

            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                <h3 className="text-lg font-semibold mb-4 text-center text-gray-800 dark:text-gray-200">
                    نوع فعالیت خود را انتخاب کنید
                </h3>
                <div className="max-w-sm mx-auto">
                    <div className="bg-custom-light-bg dark:bg-custom-dark-blue rounded-xl shadow-inner p-1">
                        <div className="relative flex rounded-lg overflow-hidden">
                            <span
                                className={`absolute top-0 bottom-0 right-0 w-1/2 bg-custom-purple rounded-lg shadow-md transition-transform duration-300 ease-in-out ${shipmentMode === 'carry' ? '-translate-x-full' : 'translate-x-0'
                                    }`}
                                aria-hidden="true"
                            />
                            <button
                                type="button"
                                onClick={() => setShipmentMode('send')}
                                className={`relative z-10 flex w-1/2 items-center justify-center gap-2 rounded-lg py-2.5 text-md font-semibold transition-colors duration-300 ${shipmentMode === 'send' ? 'text-white' : 'text-gray-600 dark:text-gray-300'
                                    }`}
                                aria-label="ارسال مرسوله"
                            >
                                <PackageIcon className="h-5 w-5" />
                                <span>ارسال مرسوله</span>
                            </button>
                            <button
                                type="button"
                                onClick={() => setShipmentMode('carry')}
                                className={`relative z-10 flex w-1/2 items-center justify-center gap-2 rounded-lg py-2.5 text-md font-semibold transition-colors duration-300 ${shipmentMode === 'carry' ? 'text-white' : 'text-gray-600 dark:text-gray-300'
                                    }`}
                                aria-label="حمل مرسوله"
                            >
                                <PlaneIcon className="h-5 w-5" />
                                <span>حمل مرسوله</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            {shipmentMode === 'send' ? (
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div className="lg:col-span-1 space-y-8">
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-lg font-semibold mb-4">تصاویر مرسوله</h3>
                            <label
                                htmlFor="file-upload"
                                className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer bg-custom-light-bg dark:bg-custom-dark-blue hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                                onDrop={onDrop}
                                onDragOver={onDragOver}
                            >
                                <div className="flex flex-col items-center justify-center pt-5 pb-6">
                                    <UploadCloudIcon className="w-10 h-10 mb-3 text-gray-400" />
                                    <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                                        <span className="font-semibold">برای آپلود کلیک کنید</span> یا بکشید و رها کنید
                                    </p>
                                    <p className="text-xs text-gray-500 dark:text-gray-400">PNG, JPG or GIF (MAX. 800x400px)</p>
                                </div>
                                <input
                                    id="file-upload"
                                    type="file"
                                    className="hidden"
                                    multiple
                                    accept="image/*"
                                    onChange={handleImageUpload}
                                />
                            </label>
                        </div>
                        {images.length > 0 && (
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-lg font-semibold mb-4">پیش‌نمایش</h3>
                                <div className="grid grid-cols-3 gap-4">
                                    {images.map((image) => (
                                        <div key={image.id} className="relative group">
                                            <img
                                                src={image.url}
                                                alt="Preview"
                                                className="w-full h-24 object-cover rounded-md"
                                            />
                                            <button
                                                onClick={() => removeImage(image.id)}
                                                className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                                            >
                                                <XIcon className="w-4 h-4" />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                    <div className="lg:col-span-2">
                        <form onSubmit={handleSubmit} className="space-y-8">
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                    ۱. اطلاعات اصلی مرسوله
                                </h3>
                                <div className="mt-6 space-y-6">
                                    <InputWithIcon
                                        icon={TypeIcon}
                                        id="title"
                                        placeholder="مثال: کتاب‌های درسی"
                                        label="عنوان مرسوله"
                                        value={title}
                                        onChange={(e) => setTitle(e.target.value)}
                                    />
                                    <TextareaWithIcon
                                        icon={ListIcon}
                                        id="description"
                                        placeholder="جزئیات بیشتر در مورد مرسوله، شرایط نگهداری و..."
                                        label="توضیحات (اختیاری)"
                                        value={description}
                                        onChange={(e) => setDescription(e.target.value)}
                                    />
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <InputWithIcon
                                            icon={ScaleIcon}
                                            id="weight"
                                            placeholder="به کیلوگرم"
                                            label="وزن تقریبی"
                                            type="number"
                                            value={weight}
                                            onChange={(e) => setWeight(e.target.value)}
                                           //step="0.1"
                                           
                                        />
                                        <div>
                                            <label htmlFor="category" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                                دسته‌بندی
                                            </label>
                                            <div className="relative">
                                                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                                    <TagIcon className="w-5 h-5 text-gray-400" />
                                                </div>
                                                <select
                                                    id="category"
                                                    value={category}
                                                    onChange={(e) => setCategory(e.target.value)}
                                                    className="w-full appearance-none pr-10 pl-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                                                >
                                                    <option value="">انتخاب کنید</option>
                                                    <option value="documents">مدارک و اسناد</option>
                                                    <option value="electronics">لوازم الکترونیکی</option>
                                                    <option value="clothing">پوشاک</option>
                                                    <option value="furniture">اثاثیه منزل</option>
                                                    <option value="miscellaneous">متفرقه</option>
                                                </select>
                                                <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                                    <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                    ۲. مبدأ و مقصد
                                </h3>
                                <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                                        <h3 className="font-semibold text-lg text-gray-800 dark:text-gray-200">مبدأ</h3>
                                        <InputWithLocationButton
                                            onButtonClick={() => openModal('origin')}
                                            value={originText}
                                            id="origin"
                                            placeholder="موقعیت ثبت نشده"
                                            label="انتخاب از روی نقشه"
                                        />
                                        <div className="text-center text-sm text-gray-500 dark:text-gray-400">یا</div>
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <InputWithIcon
                                                icon={CrmIcon}
                                                id="origin_country"
                                                placeholder="مثال: ایران"
                                                label="کشور"
                                                value={originCountry}
                                                onChange={(e) => setOriginCountry(e.target.value)}
                                            />
                                            <InputWithIcon
                                                icon={MapPinIcon}
                                                id="origin_city"
                                                placeholder="مثال: تهران"
                                                label="شهر"
                                                value={originCity}
                                                onChange={(e) => setOriginCity(e.target.value)}
                                            />
                                        </div>
                                        <InputWithIcon
                                            icon={HomeIcon}
                                            id="origin_address"
                                            placeholder="آدرس کامل، پلاک و واحد"
                                            label="آدرس دستی"
                                            value={originAddress}
                                            onChange={(e) => setOriginAddress(e.target.value)}
                                        />
                                    </div>
                                    <div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                                        <h3 className="font-semibold text-lg text-gray-800 dark:text-gray-200">مقصد</h3>
                                        <InputWithLocationButton
                                            onButtonClick={() => openModal('destination')}
                                            value={destinationText}
                                            id="destination"
                                            placeholder="موقعیت ثبت نشده"
                                            label="انتخاب از روی نقشه"
                                        />
                                        <div className="text-center text-sm text-gray-500 dark:text-gray-400">یا</div>
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <InputWithIcon
                                                icon={CrmIcon}
                                                id="destination_country"
                                                placeholder="مثال: کانادا"
                                                label="کشور"
                                                value={destinationCountry}
                                                onChange={(e) => setDestinationCountry(e.target.value)}
                                            />
                                            <InputWithIcon
                                                icon={MapPinIcon}
                                                id="destination_city"
                                                placeholder="مثال: تورنتو"
                                                label="شهر"
                                                value={destinationCity}
                                                onChange={(e) => setDestinationCity(e.target.value)}
                                            />
                                        </div>
                                        <InputWithIcon
                                            icon={HomeIcon}
                                            id="destination_address"
                                            placeholder="آدرس کامل، پلاک و واحد"
                                            label="آدرس دستی"
                                            value={destinationAddress}
                                            onChange={(e) => setDestinationAddress(e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>

                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                    ۳. قیمت‌گذاری و اطلاعات تماس
                                </h3>
                                <div className="mt-6 space-y-6">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            قیمت
                                        </label>
                                        <div className="flex flex-col md:flex-row gap-4">
                                            <div className="flex-1 grid grid-cols-2 gap-2 bg-custom-light-bg dark:bg-custom-dark-blue p-1 rounded-lg">
                                                <button
                                                    type="button"
                                                    onClick={() => setPriceType('fixed')}
                                                    className={`px-4 py-2 rounded-md text-sm font-semibold transition ${priceType === 'fixed'
                                                        ? 'bg-custom-purple text-white shadow'
                                                        : 'text-gray-600 dark:text-gray-300'
                                                        }`}
                                                >
                                                    قیمت ثابت
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => setPriceType('negotiable')}
                                                    className={`px-4 py-2 rounded-md text-sm font-semibold transition ${priceType === 'negotiable'
                                                        ? 'bg-custom-purple text-white shadow'
                                                        : 'text-gray-600 dark:text-gray-300'
                                                        }`}
                                                >
                                                    توافقی
                                                </button>
                                            </div>
                                            {priceType === 'fixed' && (
                                                <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-6">
                                                    <div>
                                                        <label htmlFor="currency" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                                            واحد پولی
                                                        </label>
                                                        <div className="relative">
                                                            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                                                <DollarSignIcon className="w-5 h-5 text-gray-400" />
                                                            </div>
                                                            <select
                                                                id="currency"
                                                                value={currency}
                                                                onChange={(e) => setCurrency(e.target.value as Currency)}
                                                                className="w-full appearance-none pr-10 pl-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                                                            >
                                                                {currencies.map(({ value, label }) => (
                                                                    <option key={value} value={value}>
                                                                        {label}
                                                                    </option>
                                                                ))}
                                                            </select>
                                                            <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                                                <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <label htmlFor="amount" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                                            مبلغ
                                                        </label>
                                                        <div className="relative">
                                                            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                                                <DollarSignIcon className="w-5 h-5 text-gray-400" />
                                                            </div>
                                                            <input
                                                                id="amount"
                                                                type="number"
                                                                placeholder="مبلغ"
                                                                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                                                                value={amount}
                                                                onChange={(e) => setAmount(e.target.value)}
                                                                //step="1000"
                                                             
                                                            />
                                                        </div>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                    <div className="flex items-center justify-between bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-lg">
                                        <div className="flex items-center">
                                            <PhoneIcon className="w-5 h-5 text-gray-500 dark:text-gray-400 ml-3" />
                                            <div>
                                                <p className="font-medium text-gray-800 dark:text-gray-200">
                                                    نمایش شماره تماس
                                                </p>
                                                <p className="text-xs text-gray-500 dark:text-gray-400">
                                                    برای هماهنگی شماره شما نمایش داده شود؟
                                                </p>
                                            </div>
                                        </div>
                                        <ToggleSwitch enabled={showPhoneNumber} setEnabled={setShowPhoneNumber} />
                                    </div>
                                </div>
                            </div>

                            <button
                                type="submit"
                                disabled={loading}
                                className="w-full bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-3 px-4 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center"
                            >
                                {loading ? (
                                    <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                ) : (
                                    'ثبت و انتشار مرسوله'
                                )}
                            </button>
                        </form>
                    </div>
                </div>
            ) : (
                <div className="w-full max-w-4xl mx-auto">
                    <form onSubmit={handleSubmit} className="space-y-8">
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                ۱. مبدأ و مقصد سفر
                            </h3>
                            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                                    <h3 className="font-semibold text-lg text-gray-800 dark:text-gray-200">مبدأ</h3>
                                    <InputWithLocationButton
                                        onButtonClick={() => openModal('origin')}
                                        value={originText}
                                        id="origin_carry"
                                        placeholder="موقعیت ثبت نشده"
                                        label="انتخاب از روی نقشه"
                                    />
                                    <div className="text-center text-sm text-gray-500 dark:text-gray-400">یا</div>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <InputWithIcon
                                            icon={CrmIcon}
                                            id="origin_country_carry"
                                            placeholder="مثال: ایران"
                                            label="کشور"
                                            value={originCountry}
                                            onChange={(e) => setOriginCountry(e.target.value)}
                                        />
                                        <InputWithIcon
                                            icon={MapPinIcon}
                                            id="origin_city_carry"
                                            placeholder="مثال: تهران"
                                            label="شهر"
                                            value={originCity}
                                            onChange={(e) => setOriginCity(e.target.value)}
                                        />
                                    </div>
                                    <InputWithIcon
                                        icon={HomeIcon}
                                        id="origin_address_carry"
                                        placeholder="آدرس کامل، پلاک و واحد"
                                        label="آدرس دستی"
                                        value={originAddress}
                                        onChange={(e) => setOriginAddress(e.target.value)}
                                    />
                                </div>
                                <div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                                    <h3 className="font-semibold text-lg text-gray-800 dark:text-gray-200">مقصد</h3>
                                    <InputWithLocationButton
                                        onButtonClick={() => openModal('destination')}
                                        value={destinationText}
                                        id="destination_carry"
                                        placeholder="موقعیت ثبت نشده"
                                        label="انتخاب از روی نقشه"
                                    />
                                    <div className="text-center text-sm text-gray-500 dark:text-gray-400">یا</div>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <InputWithIcon
                                            icon={CrmIcon}
                                            id="destination_country_carry"
                                            placeholder="مثال: کانادا"
                                            label="کشور"
                                            value={destinationCountry}
                                            onChange={(e) => setDestinationCountry(e.target.value)}
                                        />
                                        <InputWithIcon
                                            icon={MapPinIcon}
                                            id="destination_city_carry"
                                            placeholder="مثال: تورنتو"
                                            label="شهر"
                                            value={destinationCity}
                                            onChange={(e) => setDestinationCity(e.target.value)}
                                        />
                                    </div>
                                    <InputWithIcon
                                        icon={HomeIcon}
                                        id="destination_address_carry"
                                        placeholder="آدرس کامل، پلاک و واحد"
                                        label="آدرس دستی"
                                        value={destinationAddress}
                                        onChange={(e) => setDestinationAddress(e.target.value)}
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                ۲. جزئیات سفر
                            </h3>
                            <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                                <PersianDateSelector
                                    id="departure_date"
                                    label="تاریخ حرکت"
                                    value={departureDate}
                                    onChange={setDepartureDate}
                                />
                                <PersianDateSelector
                                    id="arrival_date"
                                    label="تاریخ رسیدن"
                                    value={arrivalDate}
                                    onChange={setArrivalDate}
                                />
                            </div>
                            <div className="mt-6">
                                <InputWithIcon
                                    icon={ScaleIcon}
                                    id="carry_weight"
                                    label="ظرفیت حمل"
                                    placeholder="حداکثر وزن قابل حمل به کیلوگرم"
                                    type="number"
                                    value={carryWeight}
                                    onChange={(e) => setCarryWeight(e.target.value)}
                                    //step="0.1"
                                    
                                />
                            </div>
                            <div className="mt-6">
                                <TextareaWithIcon
                                    icon={ListIcon}
                                    id="trip_description"
                                    label="توضیحات (اختیاری)"
                                    placeholder="توضیحات بیشتر در مورد سفر، نوع وسیله نقلیه، اقلام ممنوعه و..."
                                    value={tripDescription}
                                    onChange={(e) => setTripDescription(e.target.value)}
                                />
                            </div>
                        </div>

                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                                ۳. قیمت‌گذاری و اطلاعات تماس
                            </h3>
                            <div className="mt-6 space-y-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        قیمت
                                    </label>
                                    <div className="flex flex-col md:flex-row gap-4">
                                        <div className="flex-1 grid grid-cols-2 gap-2 bg-custom-light-bg dark:bg-custom-dark-blue p-1 rounded-lg">
                                            <button
                                                type="button"
                                                onClick={() => setPriceType('fixed')}
                                                className={`px-4 py-2 rounded-md text-sm font-semibold transition ${priceType === 'fixed'
                                                    ? 'bg-custom-purple text-white shadow'
                                                    : 'text-gray-600 dark:text-gray-300'
                                                    }`}
                                            >
                                                قیمت ثابت
                                            </button>
                                            <button
                                                type="button"
                                                onClick={() => setPriceType('negotiable')}
                                                className={`px-4 py-2 rounded-md text-sm font-semibold transition ${priceType === 'negotiable'
                                                    ? 'bg-custom-purple text-white shadow'
                                                    : 'text-gray-600 dark:text-gray-300'
                                                    }`}
                                            >
                                                توافقی
                                            </button>
                                        </div>
                                        {priceType === 'fixed' && (
                                            <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-6">
                                                <div>
                                                    <label htmlFor="currency_carry" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                                        واحد پولی
                                                    </label>
                                                    <div className="relative">
                                                        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                                            <DollarSignIcon className="w-5 h-5 text-gray-400" />
                                                        </div>
                                                        <select
                                                            id="currency_carry"
                                                            value={currency}
                                                            onChange={(e) => setCurrency(e.target.value as Currency)}
                                                            className="w-full appearance-none pr-10 pl-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                                                        >
                                                            {currencies.map(({ value, label }) => (
                                                                <option key={value} value={value}>
                                                                    {label}
                                                                </option>
                                                            ))}
                                                        </select>
                                                        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                                            <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                                                        </div>
                                                    </div>
                                                </div>
                                                <div>
                                                    <label htmlFor="amount_carry" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                                        مبلغ به ازای هر کیلوگرم
                                                    </label>
                                                    <div className="relative">
                                                        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                                            <DollarSignIcon className="w-5 h-5 text-gray-400" />
                                                        </div>
                                                        <input
                                                            id="amount_carry"
                                                            type="number"
                                                            placeholder="مبلغ"
                                                            className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                                                            value={carryAmount}
                                                            onChange={(e) => setCarryAmount(e.target.value)}
                                                            // step="1000"
                                                        
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className="flex items-center justify-between bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-lg">
                                    <div className="flex items-center">
                                        <PhoneIcon className="w-5 h-5 text-gray-500 dark:text-gray-400 ml-3" />
                                        <div>
                                            <p className="font-medium text-gray-800 dark:text-gray-200">
                                                نمایش شماره تماس
                                            </p>
                                            <p className="text-xs text-gray-500 dark:text-gray-400">
                                                برای هماهنگی شماره شما نمایش داده شود؟
                                            </p>
                                        </div>
                                    </div>
                                    <ToggleSwitch enabled={showPhoneNumber} setEnabled={setShowPhoneNumber} />
                                </div>
                            </div>
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-3 px-4 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center"
                        >
                            {loading ? (
                                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                            ) : (
                                'ثبت و اعلام سفر'
                            )}
                        </button>
                    </form>
                </div>
            )}

            <LocationModal
                isOpen={modalState.isOpen}
                onClose={closeModal}
                onConfirm={confirmLocation}
                field={modalState.field}
            />
        </div>
    );
};

// --- Helper Components ---

const isJalaliLeap = (year: number): boolean => {
    const remainders = [1, 5, 9, 13, 17, 22, 26, 30];
    return remainders.includes(year % 33);
};

const getDaysInJalaliMonth = (year: number, month: number): number => {
    if (month < 7) return 31;
    if (month < 12) return 30;
    if (month === 12) return isJalaliLeap(year) ? 30 : 29;
    return 0;
};

const getJalaliToday = (): { year: number; month: number; day: number } => {
    const today = new Date().toLocaleDateString('fa-IR-u-nu-latn');
    const [year, month, day] = today.split('/').map(Number);
    return { year, month, day };
};

const persianMonths = [
    "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
    "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"
];

interface PersianDateSelectorProps {
    id: string;
    label: string;
    value: string;
    onChange: (value: string) => void;
}

const PersianDateSelector: React.FC<PersianDateSelectorProps> = ({ id, label, value, onChange }) => {
    const today = getJalaliToday();
    const currentYear = today.year;
    const [selectedYear, setSelectedYear] = useState<number | undefined>();
    const [selectedMonth, setSelectedMonth] = useState<number | undefined>();
    const [selectedDay, setSelectedDay] = useState<number | undefined>();
    const years = Array.from({ length: 4 }, (_, i) => currentYear + i);
    const daysInMonth = selectedYear && selectedMonth ? getDaysInJalaliMonth(selectedYear, selectedMonth) : 31;

    useEffect(() => {
        if (value) {
            const [y, m, d] = value.split('/').map(Number);
            setSelectedYear(y);
            setSelectedMonth(m);
            setSelectedDay(d);
        } else {
            setSelectedYear(undefined);
            setSelectedMonth(undefined);
            setSelectedDay(undefined);
        }
    }, [value]);

    useEffect(() => {
        if (selectedYear && selectedMonth && selectedDay) {
            onChange(`${selectedYear}/${selectedMonth}/${selectedDay}`);
        } else {
            onChange('');
        }
    }, [selectedYear, selectedMonth, selectedDay, onChange]);

    useEffect(() => {
        if (selectedDay && selectedDay > daysInMonth) {
            setSelectedDay(daysInMonth);
        }
    }, [daysInMonth, selectedDay]);

    const handleYearChange = (e: React.ChangeEvent<HTMLSelectElement>) => setSelectedYear(Number(e.target.value));
    const handleMonthChange = (e: React.ChangeEvent<HTMLSelectElement>) => setSelectedMonth(Number(e.target.value));
    const handleDayChange = (e: React.ChangeEvent<HTMLSelectElement>) => setSelectedDay(Number(e.target.value));

    const commonSelectClasses = "w-full appearance-none pr-4 pl-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition";

    return (
        <div>
            <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
            <div className="grid grid-cols-3 gap-2">
                <div className="relative">
                    <select id={`${id}_day`} value={selectedDay || ''} onChange={handleDayChange} className={commonSelectClasses}>
                        <option value="" disabled>روز</option>
                        {Array.from({ length: daysInMonth }, (_, i) => i + 1).map(day => (
                            <option key={day} value={day}>{day}</option>
                        ))}
                    </select>
                    <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                        <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                    </div>
                </div>
                <div className="relative">
                    <select id={`${id}_month`} value={selectedMonth || ''} onChange={handleMonthChange} className={commonSelectClasses}>
                        <option value="" disabled>ماه</option>
                        {persianMonths.map((month, index) => (
                            <option key={index} value={index + 1}>{month}</option>
                        ))}
                    </select>
                    <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                        <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                    </div>
                </div>
                <div className="relative">
                    <select id={`${id}_year`} value={selectedYear || ''} onChange={handleYearChange} className={commonSelectClasses}>
                        <option value="" disabled>سال</option>
                        {years.map(year => (
                            <option key={year} value={year}>{year}</option>
                        ))}
                    </select>
                    <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                        <ChevronDownIcon className="w-5 h-5 text-gray-400" />
                    </div>
                </div>
            </div>
        </div>
    );
};

interface InputWithIconProps {
    id: string;
    icon?: React.FC<{ className?: string }>;
    label: string;
    placeholder: string;
    type?: string;
    value?: string;
    onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
    step?: string;
    min?: string;
}

const InputWithIcon: React.FC<InputWithIconProps> = ({ id, icon: Icon, label, placeholder, type = 'text', value, onChange, step, min }) => (
    <div>
        <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
        <div className="relative">
            {Icon && (
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                    <Icon className="w-5 h-5 text-gray-400" />
                </div>
            )}
            <input
                type={type}
                id={id}
                className={`w-full ${Icon ? 'pr-10' : 'pr-4'} pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition`}
                placeholder={placeholder}
                value={value}
                onChange={onChange}
                step={step}
                min={min}
            />
        </div>
    </div>
);

interface TextareaWithIconProps {
    id: string;
    icon: React.FC<{ className?: string }>;
    label: string;
    placeholder: string;
    value?: string;
    onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
}

const TextareaWithIcon: React.FC<TextareaWithIconProps> = ({ id, icon: Icon, label, placeholder, value, onChange }) => (
    <div>
        <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
        <div className="relative">
            <div className="absolute top-3.5 right-0 flex items-center pr-3 pointer-events-none">
                <Icon className="w-5 h-5 text-gray-400" />
            </div>
            <textarea
                id={id}
                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition min-h-[100px] resize-y"
                placeholder={placeholder}
                value={value}
                onChange={onChange}
            />
        </div>
    </div>
);

interface InputWithLocationButtonProps {
    id: string;
    label: string;
    placeholder: string;
    value: string;
    onButtonClick: () => void;
}

const InputWithLocationButton: React.FC<InputWithLocationButtonProps> = ({ id, label, placeholder, value, onButtonClick }) => (
    <div>
        <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
        <div className="relative flex items-center">
            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <MapPinIcon className="w-5 h-5 text-gray-400" />
            </div>
            <input
                type="text"
                id={id}
                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                placeholder={placeholder}
                value={value}
                readOnly
                onClick={onButtonClick}
                style={{ cursor: 'pointer' }}
            />
            <button
                type="button"
                onClick={onButtonClick}
                className="absolute left-2 text-sm bg-custom-purple text-white px-3 py-1 rounded-md hover:bg-custom-light-purple transition-colors"
            >
                ثبت
            </button>
        </div>
    </div>
);

interface ToggleSwitchProps {
    enabled: boolean;
    setEnabled: (enabled: boolean) => void;
}

const ToggleSwitch: React.FC<ToggleSwitchProps> = ({ enabled, setEnabled }) => {
    return (
        <button
            type="button"
            dir="ltr"
            className={`${enabled ? 'bg-custom-purple' : 'bg-gray-200 dark:bg-gray-600'}
              relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent 
              transition-colors duration-200 ease-in-out 
              focus:outline-none focus:ring-2 focus:ring-custom-purple focus:ring-offset-2`}
            onClick={() => setEnabled(!enabled)}
        >
            <span
                aria-hidden="true"
                className={`${enabled ? 'translate-x-5' : 'translate-x-0'}
                pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white 
                shadow-lg ring-0 transition duration-200 ease-in-out`}
            />
        </button>
    );
};

interface LocationModalProps {
    isOpen: boolean;
    onClose: () => void;
    onConfirm: (location: { lat: number; lng: number }) => void;
    field: LocationField | null;
}

const LocationModal: React.FC<LocationModalProps> = ({ isOpen, onClose, onConfirm, field }) => {
    const mapRef = useRef<any>(null);
    const markerRef = useRef<any>(null);
    const mapContainerRef = useRef<HTMLDivElement>(null);
    const [selectedLocation, setSelectedLocation] = useState<{ lat: number; lng: number } | null>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [isSearching, setIsSearching] = useState(false);

    useEffect(() => {
        if (!isOpen) return;
        const cleanup = () => {
            if (mapRef.current) {
                mapRef.current.remove();
                mapRef.current = null;
            }
            markerRef.current = null;
            setSelectedLocation(null);
            setSearchQuery('');
        };
        if (mapContainerRef.current && !mapRef.current) {
            const map = L.map(mapContainerRef.current).setView([35.6892, 51.3890], 10);
            mapRef.current = map;
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
            map.on('click', (e: any) => {
                const { lat, lng } = e.latlng;
                setSelectedLocation({ lat, lng });
                if (markerRef.current) {
                    markerRef.current.setLatLng(e.latlng);
                } else {
                    markerRef.current = L.marker(e.latlng).addTo(mapRef.current);
                }
            });
            setTimeout(() => map.invalidateSize(), 100);
        }
        return cleanup;
    }, [isOpen]);

    const handleSearch = async () => {
        if (!searchQuery.trim()) return;
        setIsSearching(true);
        try {
            const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchQuery)}&accept-language=fa`);
            if (!response.ok) throw new Error('Network response was not ok');
            const data = await response.json();
            if (data && data.length > 0) {
                const { lat, lon } = data[0];
                const newLat = parseFloat(lat);
                const newLng = parseFloat(lon);
                const latlng = { lat: newLat, lng: newLng };
                setSelectedLocation(latlng);
                if (mapRef.current) {
                    mapRef.current.setView(latlng, 15);
                    if (markerRef.current) {
                        markerRef.current.setLatLng(latlng);
                    } else {
                        markerRef.current = L.marker(latlng).addTo(mapRef.current);
                    }
                }
            } else {
                console.log('مکان مورد نظر یافت نشد.');
            }
        } catch (error) {
            console.error("Geocoding error:", error);
            console.log('خطایی در جستجوی مکان رخ داد.');
        } finally {
            setIsSearching(false);
        }
    };

    const handleUseCurrentLocation = async () => {
        if (!navigator.geolocation) {
            console.log("مرورگر شما از موقعیت‌یابی جغرافیایی پشتیبانی نمی‌کند.");
            return;
        }
        if (navigator.permissions && navigator.permissions.query) {
            try {
                const permissionStatus = await navigator.permissions.query({ name: 'geolocation' });
                if (permissionStatus.state === 'denied') {
                    console.log("شما دسترسی به موقعیت مکانی را مسدود کرده‌اید.");
                    return;
                }
            } catch (error) {
                console.warn("Could not check permission status:", error);
            }
        }
        navigator.geolocation.getCurrentPosition(
            (position) => {
                const { latitude: lat, longitude: lng } = position.coords;
                const latlng = { lat, lng };
                setSelectedLocation(latlng);
                if (mapRef.current) {
                    mapRef.current.setView(latlng, 15);
                    if (markerRef.current) {
                        markerRef.current.setLatLng(latlng);
                    } else {
                        markerRef.current = L.marker(latlng).addTo(mapRef.current);
                    }
                }
            },
            (error) => {
                console.error("Geolocation error:", error.message);
                let message = "امکان دسترسی به موقعیت مکانی شما وجود ندارد.";
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        message = "شما اجازه دسترسی به موقعیت مکانی را نداده‌اید.";
                        break;
                    case error.POSITION_UNAVAILABLE:
                        message = "اطلاعات موقعیت مکانی در دسترس نیست.";
                        break;
                    case error.TIMEOUT:
                        message = "درخواست برای دریافت موقعیت مکانی بیش از حد طول کشید.";
                        break;
                }
                console.log(message);
            }
        );
    };

    const handleConfirm = () => {
        if (selectedLocation) {
            onConfirm(selectedLocation);
        } else {
            console.log('لطفاً یک موقعیت روی نقشه انتخاب کنید.');
        }
    };

    if (!isOpen) return null;

    const title = field === 'origin' ? 'ثبت موقعیت مبدأ' : 'ثبت موقعیت مقصد';

    return (
        <div
            className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4 backdrop-blur-sm"
            onClick={onClose}
        >
            <div
                className="bg-custom-light-card dark:bg-custom-dark-blue-light w-full max-w-2xl rounded-2xl shadow-2xl border border-gray-200 dark:border-gray-700/50 transform transition-all duration-300 ease-out scale-95 opacity-0 animate-fade-in-scale overflow-hidden"
                onClick={(e) => e.stopPropagation()}
            >
                <div className="flex justify-between items-center p-5 bg-custom-light-bg dark:bg-custom-dark-blue">
                    <h2 className="text-xl font-bold flex items-center gap-3">
                        <MapPinIcon className="w-6 h-6 text-custom-purple" /> {title}
                    </h2>
                    <button onClick={onClose} className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors">
                        <XIcon className="w-6 h-6 text-gray-500 dark:text-gray-400" />
                    </button>
                </div>
                <div className="p-6 space-y-5">
                    <div className="flex items-center gap-2">
                        <div className="relative flex-grow">
                            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                <SearchIcon className="w-5 h-5 text-gray-400" />
                            </div>
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                onKeyDown={(e) => { if (e.key === 'Enter') handleSearch(); }}
                                placeholder="جستجوی آدرس یا مکان..."
                                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                            />
                        </div>
                        <button
                            onClick={handleSearch}
                            disabled={isSearching}
                            className="flex-shrink-0 flex items-center justify-center w-28 py-2.5 px-4 rounded-lg bg-custom-purple text-white font-semibold hover:bg-custom-light-purple transition-colors disabled:bg-gray-400 disabled:cursor-wait"
                        >
                            {isSearching ? (
                                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                            ) : (
                                <span>جستجو</span>
                            )}
                        </button>
                    </div>
                    <button
                        onClick={handleUseCurrentLocation}
                        className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl bg-gradient-to-br from-custom-cyan to-teal-400 text-white font-semibold hover:shadow-lg hover:shadow-custom-cyan/30 transition-all duration-300 transform hover:-translate-y-0.5"
                    >
                        <CrosshairIcon className="w-5 h-5" />
                        <span>استفاده از موقعیت فعلی من</span>
                    </button>
                    <div className="relative my-4">
                        <div className="absolute inset-0 flex items-center" aria-hidden="true">
                            <div className="w-full border-t border-gray-300 dark:border-gray-600" />
                        </div>
                        <div className="relative flex justify-center">
                            <span className="bg-custom-light-card dark:bg-custom-dark-blue-light px-3 text-sm text-gray-500 dark:text-gray-400">یا</span>
                        </div>
                    </div>
                    <p className="text-center text-sm text-gray-500 dark:text-gray-400 -mt-2 mb-2">
                        برای انتخاب، روی نقشه کلیک کنید.
                    </p>
                    <div
                        ref={mapContainerRef}
                        className="w-full h-80 bg-gray-200 dark:bg-gray-700 rounded-lg cursor-pointer z-0 border border-gray-300 dark:border-gray-600 shadow-inner"
                    />
                </div>
                <div className="px-6 py-4 bg-custom-light-bg dark:bg-custom-dark-blue border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
                    <button
                        onClick={onClose}
                        className="py-2 px-5 rounded-lg text-gray-700 dark:text-gray-300 font-semibold hover:bg-gray-200 dark:hover:bg-gray-700/50 transition-colors"
                    >
                        انصراف
                    </button>
                    <button
                        onClick={handleConfirm}
                        disabled={!selectedLocation}
                        className="py-2.5 px-6 rounded-xl bg-gradient-to-br from-custom-purple to-custom-light-purple text-white font-semibold hover:shadow-lg hover:shadow-custom-purple/30 transition-all duration-300 disabled:from-gray-400 disabled:to-gray-500 disabled:shadow-none disabled:cursor-not-allowed transform disabled:transform-none hover:-translate-y-0.5"
                    >
                        تایید موقعیت
                    </button>
                </div>
            </div>
            <style>{`
                @keyframes fade-in-scale {
                    from { transform: scale(0.95); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
                .animate-fade-in-scale {
                    animation: fade-in-scale 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
                }
                .leaflet-container {
                    font-family: 'Vazirmatn', sans-serif;
                }
            `}</style>
        </div>
    );
};

export default RegisterShipmentPage;