// src/components/pages/ShipmentDetailPage.tsx
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
    ArrowRightIcon, ScaleIcon, TagIcon, MapPinIcon,
    DollarSignIcon, ChatIcon, PencilIcon, Trash2Icon,
    CheckIcon, XIcon, CalendarIcon, UserIcon, UploadCloudIcon,
    TypeIcon, ListIcon, HomeIcon, ChevronDownIcon, PhoneIcon,
    CrosshairIcon, SearchIcon
} from '../Icons';
import { authFetch } from '../../App';
import moment from 'moment-jalaali';
import { API_BASE_URL } from '@/src/config.js';
// تعریف نوع‌ها (بدون تغییر)
interface ShipmentData {
    id: number;
    type: 'send' | 'carry';
    title: string;
    description: string;
    status: string | null;
    is_active: boolean;
    origin: {
        country: string;
        city: string;
        address?: string;
        coordinates?: string;
    };
    destination: {
        country: string;
        city: string;
        address?: string;
        coordinates?: string;
    };
    weight?: string;
    carry_weight_capacity?: string;
    category?: string;
    departure_date?: string | null;
    arrival_date?: string | null;
    price_type: 'fixed' | 'negotiable';
    currency?: string | null;
    amount?: string | null;
    show_phone: boolean;
    created_at: string;
    images: { id: number; url: string }[];
    user: {
        id: number;
        name: string | null;
        phone?: string;
    };
}

interface ShipmentDetailPageProps {
    shipmentId: string | null;
    onNavigate: (page: string, payload?: any, options?: { isOwnerView?: boolean }) => void;
    showSuccess: (message: string) => void;
    showError: (message: string) => void;
    isOwnerView?: boolean;
}

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

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

// ⭐ ۱. تابع تبدیل تاریخ میلادی به شمسی (با استفاده از moment-jalaali)
function convertGregorianToJalali(gDateStr: string): string {
    if (!gDateStr) return '';
    return moment(gDateStr, 'YYYY-MM-DD').format('jYYYY/jMM/jDD');
}

// ⭐ ۲. تابع تبدیل تاریخ شمسی به میلادی (با استفاده از moment-jalaali برای دقت بیشتر)
const convertJalaliToGregorian = (jalaliDate: string): string => {
    if (!jalaliDate) return '';
    return moment(jalaliDate, 'jYYYY/jMM/jDD').format('YYYY-MM-DD');
};

const ShipmentDetailPage: React.FC<ShipmentDetailPageProps> = ({
    shipmentId,
    onNavigate,
    showSuccess,
    showError,
    isOwnerView = false
}) => {
    const [shipment, setShipment] = useState<ShipmentData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [deleting, setDeleting] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);
    const [saving, setSaving] = useState(false);
    
    // Form states
    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [weight, setWeight] = useState('');
    const [category, setCategory] = useState('');
    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 [priceType, setPriceType] = useState<PriceType>('fixed');
    const [currency, setCurrency] = useState<Currency>('IRT');
    const [amount, setAmount] = useState('');
    const [showPhoneNumber, setShowPhoneNumber] = useState(false);
    const [carryWeight, setCarryWeight] = useState('');
    const [departureDate, setDepartureDate] = useState('');
    const [arrivalDate, setArrivalDate] = useState('');
    const [tripDescription, setTripDescription] = useState('');
    const [images, setImages] = useState<ImageFile[]>([]);
    const [newImages, setNewImages] = useState<ImageFile[]>([]);
    
    // State for location modal
    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 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: 'دینار' },
    ];

    useEffect(() => {
        if (!shipmentId) return;
        let isMounted = true; // ✅ جلوگیری از setState بعد از unmount
        const fetchShipment = async () => {
            try {
                setLoading(true);
                setError(null);
                const response = await authFetch(
                    `${API_BASE_URL}/shipments/${shipmentId}`
                );
                if (!response.ok) {
                    throw new Error('خطا در دریافت اطلاعات مرسوله');
                }
                const result = await response.json();
                const data = result.data;
                if (!isMounted) return;
                setShipment(data);
                // ✅ تبدیل تاریخ‌ها فقط یک‌بار
                const jalaliDepartureDate = data.departure_date
                    ? convertGregorianToJalali(data.departure_date)
                    : '';
                const jalaliArrivalDate = data.arrival_date
                    ? convertGregorianToJalali(data.arrival_date)
                    : '';
                // ✅ پر کردن فرم – بدون loop
                setTitle(data.title ?? '');
                setDescription(data.description ?? '');
                setWeight(data.weight ?? '');
                setCategory(data.category ?? '');
                setOriginCountry(data.origin?.country ?? '');
                setOriginCity(data.origin?.city ?? '');
                setOriginAddress(data.origin?.address ?? '');
                setDestinationCountry(data.destination?.country ?? '');
                setDestinationCity(data.destination?.city ?? '');
                setDestinationAddress(data.destination?.address ?? '');
                setPriceType(data.price_type ?? 'fixed');
                setCurrency((data.currency as Currency) ?? 'IRT');
                setAmount(data.amount ?? '');
                setShowPhoneNumber(Boolean(data.show_phone));
                setCarryWeight(data.carry_weight_capacity ?? '');
                setDepartureDate(jalaliDepartureDate);
                setArrivalDate(jalaliArrivalDate);
                setTripDescription(data.trip_description ?? '');
                setImages(data.images ?? []);
                // ✅ استخراج مختصات
                if (data.origin?.coordinates) {
                    const [lat, lng] = data.origin.coordinates
                        .split(',')
                        .map(Number);
                    if (!Number.isNaN(lat) && !Number.isNaN(lng)) {
                        setOrigin({ lat, lng });
                    }
                }
                if (data.destination?.coordinates) {
                    const [lat, lng] = data.destination.coordinates
                        .split(',')
                        .map(Number);
                    if (!Number.isNaN(lat) && !Number.isNaN(lng)) {
                        setDestination({ lat, lng });
                    }
                }
            } catch (err: any) {
                console.error('خطا در دریافت جزئیات:', err);
                if (isMounted) {
                    setError(err.message || 'خطا در بارگذاری اطلاعات');
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };
        fetchShipment();
        return () => {
            isMounted = false;
        };
    }, [shipmentId]);

    // حذف مرسوله
    const handleDelete = async () => {
        if (!shipmentId || !window.confirm('آیا از حذف این مرسوله مطمئن هستید؟')) return;
        setDeleting(true);
        try {
            const response = await authFetch(`${API_BASE_URL}/shipments/${shipmentId}`, {
                method: 'DELETE',
            });
            if (!response.ok) {
                throw new Error('خطا در حذف مرسوله');
            }
            showSuccess('مرسوله با موفقیت حذف شد');
            onNavigate('my-shipment-requests');
        } catch (err: any) {
            showError(err.message || 'خطا در حذف مرسوله');
        } finally {
            setDeleting(false);
        }
    };

    // آپلود تصاویر جدید
    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files) {
            const uploaded: ImageFile[] = Array.from(files).map((file) => ({
                id: Date.now() + Math.random(),
                url: URL.createObjectURL(file),
                file,
            }));
            setNewImages(prev => [...prev, ...uploaded]);
        }
    };

    // حذف تصویر جدید
    const removeNewImage = (id: number) => {
        setNewImages(prev => prev.filter(img => img.id !== id));
    };

    // حذف تصویر قدیمی از سرور
    const removeOldImage = async (imageId: number) => {
        if (!window.confirm('آیا از حذف این تصویر مطمئن هستید؟')) return;
        try {
            const response = await authFetch(`${API_BASE_URL}/shipments/${shipmentId}/images/${imageId}`, {
                method: 'DELETE',
            });
            if (!response.ok) {
                throw new Error('خطا در حذف تصویر');
            }
            setImages(prev => prev.filter(img => img.id !== imageId));
            showSuccess('تصویر حذف شد');
        } catch (err: any) {
            showError(err.message || 'خطا در حذف تصویر');
        }
    };

    // قابلیت کشیدن و رها کردن تصاویر
    const onDrop = useCallback((event: React.DragEvent<HTMLLabelElement>) => {
        event.preventDefault();
        event.stopPropagation();
        const files = event.dataTransfer.files;
        if (files && files.length > 0) {
            const uploaded: ImageFile[] = Array.from(files)
                .filter((file: File) => file.type.startsWith('image/'))
                .map((file) => ({
                    id: Date.now() + Math.random(),
                    url: URL.createObjectURL(file),
                    file,
                }));
            setNewImages(prev => [...prev, ...uploaded]);
        }
    }, []);

    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 handleSave = async () => {
        if (!shipmentId || !shipment) return;
        setSaving(true);
        try {
            const formData = new FormData();
            formData.append('_method', 'PUT');
            // داده‌های مشترک
            formData.append('origin[country]', originCountry);
            formData.append('origin[city]', originCity);
            formData.append('origin[address]', originAddress);
            formData.append('origin[coordinates]', origin ? `${origin.lat},${origin.lng}` : "");
            formData.append('destination[country]', destinationCountry);
            formData.append('destination[city]', destinationCity);
            formData.append('destination[address]', destinationAddress);
            formData.append('destination[coordinates]', destination ? `${destination.lat},${destination.lng}` : "");
            formData.append('price_type', priceType);
            formData.append('show_phone', showPhoneNumber ? '1' : '0');
            if (priceType === 'fixed') {
                formData.append('currency', currency);
                formData.append('amount', amount);
            }
            // داده‌های خاص type
            if (shipment.type === 'send') {
                formData.append('title', title);
                formData.append('description', description);
                formData.append('weight', weight);
                formData.append('category', category);
                // افزودن تصاویر جدید
                newImages.forEach((img, index) => {
                    if (img.file) {
                        formData.append(`images[${index}]`, img.file);
                    }
                });
            } else {
                formData.append('departure_date', departureDate ? convertJalaliToGregorian(departureDate) : '');
                formData.append('arrival_date', arrivalDate ? convertJalaliToGregorian(arrivalDate) : '');
                formData.append('carry_weight_capacity', carryWeight);
                formData.append('trip_description', tripDescription);
            }
            const response = await authFetch(`${API_BASE_URL}/shipments/${shipmentId}`, {
                method: 'POST',
                body: formData,
            });
            if (!response.ok) {
                const result = await response.json();
                const firstError = result.errors ? Object.values(result.errors)[0] : result.message;
                throw new Error(Array.isArray(firstError) ? firstError[0] : firstError);
            }
            showSuccess('تغییرات با موفقیت ذخیره شد');
            setIsEditMode(false);
            // رفرش داده‌ها
            window.location.reload();
        } catch (err: any) {
            showError(err.message || 'خطا در ذخیره تغییرات');
        } finally {
            setSaving(false);
        }
    };

    // ⭐ ۳. اصلاح تابع لغو ویرایش برای بازگردانی صحیح تاریخ‌ها
    const handleCancelEdit = () => {
        setIsEditMode(false);
        setNewImages([]);
        if (shipment) {
            setTitle(shipment.title || '');
            setDescription(shipment.description || '');
            setWeight(shipment.weight || '');
            setCategory(shipment.category || '');
            setOriginCountry(shipment.origin.country || '');
            setOriginCity(shipment.origin.city || '');
            setOriginAddress(shipment.origin.address || '');
            setDestinationCountry(shipment.destination.country || '');
            setDestinationCity(shipment.destination.city || '');
            setDestinationAddress(shipment.destination.address || '');
            setPriceType(shipment.price_type || 'fixed');
            setCurrency((shipment.currency as Currency) || 'IRT');
            setAmount(shipment.amount || '');
            setShowPhoneNumber(shipment.show_phone || false);
            // بازگردانی تاریخ‌ها به حالت اولیه با تبدیل صحیح
            const jalaliDepartureDate = shipment.departure_date ? convertGregorianToJalali(shipment.departure_date) : '';
            const jalaliArrivalDate = shipment.arrival_date ? convertGregorianToJalali(shipment.arrival_date) : '';
            setDepartureDate(jalaliDepartureDate);
            setArrivalDate(jalaliArrivalDate);
            setCarryWeight(shipment.carry_weight_capacity || '');
            setTripDescription(shipment.trip_description || '');
        }
    };

    // فرمت قیمت
    const formatPrice = () => {
        if (!shipment) return '—';
        if (shipment.price_type === 'negotiable') return 'توافقی';
        if (shipment.amount && shipment.currency) {
            const currencyLabels: Record<string, string> = {
                IRT: 'تومان',
                USD: 'دلار',
                CAD: 'دلار کانادا',
                IQD: 'دینار'
            };
            const numAmount = parseFloat(shipment.amount);
            return `${numAmount.toLocaleString('fa-IR')} ${currencyLabels[shipment.currency] || shipment.currency}`;
        }
        return '—';
    };

    // ترجمه دسته‌بندی
    const translateCategory = (category: string) => {
        const categories: Record<string, string> = {
            furniture: 'مبلمان',
            electronics: 'الکترونیکی',
            clothing: 'پوشاک',
            food: 'غذایی',
            documents: 'اسناد',
            miscellaneous: 'متفرقه',
            other: 'سایر'
        };
        return categories[category] || category;
    };

    // Loading State
    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center py-12">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-custom-purple"></div>
                <p className="mt-4 text-gray-500 dark:text-gray-400">در حال بارگذاری...</p>
            </div>
        );
    }

    // Error State
    if (error || !shipment) {
        return (
            <div className="text-center py-12">
                <div className="text-red-500 mb-4 text-4xl">⚠️</div>
                <h2 className="text-xl font-bold text-red-600 dark:text-red-400">خطا در بارگذاری</h2>
                <p className="text-gray-500 dark:text-gray-400 mt-2">{error || 'مرسوله یافت نشد'}</p>
                <button
                    onClick={() => onNavigate(isOwnerView ? 'my-shipment-requests' : 'accept-shipment')}
                    className="mt-4 text-custom-purple hover:underline"
                >
                    بازگشت به لیست
                </button>
            </div>
        );
    }

    return (
        <div className="flex flex-col space-y-6">
            {/* Header */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
                        {isEditMode ? 'ویرایش مرسوله' : shipment.title}
                    </h1>
                    <p className="text-gray-500 dark:text-gray-400 mt-1">
                        {shipment.type === 'send' ? '📦 ارسال مرسوله' : '✈️ سفر حمل مرسوله'}
                    </p>
                </div>
                <button
                    onClick={() => onNavigate(isOwnerView ? 'my-shipment-requests' : 'accept-shipment')}
                    className="flex items-center gap-2 py-2 px-4 rounded-lg text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-custom-dark-blue transition-colors self-start sm:self-center"
                >
                    <ArrowRightIcon className="w-5 h-5" />
                    <span>بازگشت</span>
                </button>
            </div>
            
            {isEditMode ? (
                // حالت ویرایش
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    {/* بخش تصاویر (فقط برای send) */}
                    {shipment.type === 'send' && (
                        <div className="lg:col-span-1 space-y-6">
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">تصاویر فعلی</h3>
                                <div className="grid grid-cols-2 gap-4">
                                    {images.map((image) => (
                                        <div key={image.id} className="relative group">
                                            <img
                                                src={image.url}
                                                alt="تصویر"
                                                className="w-full h-24 object-cover rounded-md"
                                            />
                                            <button
                                                type="button"
                                                onClick={() => removeOldImage(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 className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">افزودن تصاویر جدید</h3>
                                <label
                                    htmlFor="file-upload-edit"
                                    className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl 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="text-sm text-gray-500 dark:text-gray-400">
                                            <span className="font-semibold">برای آپلود کلیک کنید</span> یا بکشید
                                        </p>
                                        <p className="text-xs text-gray-400">فرمت‌های مجاز: JPG, PNG, GIF</p>
                                    </div>
                                    <input
                                        id="file-upload-edit"
                                        type="file"
                                        className="hidden"
                                        multiple
                                        accept="image/*"
                                        onChange={handleImageUpload}
                                    />
                                </label>
                                {newImages.length > 0 && (
                                    <div className="grid grid-cols-2 gap-4 mt-4">
                                        {newImages.map((image) => (
                                            <div key={image.id} className="relative group">
                                                <img
                                                    src={image.url}
                                                    alt="پیش‌نمایش"
                                                    className="w-full h-24 object-cover rounded-md"
                                                />
                                                <button
                                                    type="button"
                                                    onClick={() => removeNewImage(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={shipment.type === 'send' ? 'lg:col-span-2' : 'lg:col-span-3'}>
                        <div 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">
                                    {shipment.type === 'send' ? '۱. اطلاعات مرسوله' : '۱. اطلاعات سفر'}
                                </h3>
                                <div className="space-y-6">
                                    {shipment.type === 'send' ? (
                                        <>
                                            <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"
                                                    min="0.1"
                                                />
                                                <div>
                                                    <label 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
                                                            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 className="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>
                                            <InputWithIcon
                                                icon={ScaleIcon}
                                                id="carry_weight"
                                                placeholder="ظرفیت حمل به کیلوگرم"
                                                label="ظرفیت حمل"
                                                type="number"
                                                value={carryWeight}
                                                onChange={(e) => setCarryWeight(e.target.value)}
                                                step="0.1"
                                                min="0.1"
                                            />
                                            <TextareaWithIcon
                                                icon={ListIcon}
                                                id="trip_description"
                                                placeholder="توضیحات سفر"
                                                label="توضیحات"
                                                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="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={MapPinIcon}
                                                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={MapPinIcon}
                                                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="space-y-6">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                            نوع قیمت
                                        </label>
                                        <div className="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>
                                    </div>
                                    {priceType === 'fixed' && (
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                            <div>
                                                <label 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
                                                        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>
                                            <InputWithIcon
                                                icon={DollarSignIcon}
                                                id="amount"
                                                placeholder="مبلغ"
                                                label="مبلغ"
                                                type="number"
                                                value={amount}
                                                onChange={(e) => setAmount(e.target.value)}
                                                step="1000"
                                                min="0"
                                            />
                                        </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>
                            
                            {/* دکمه‌های عمل */}
                            <div className="flex justify-end gap-4">
                                <button
                                    type="button"
                                    onClick={handleCancelEdit}
                                    disabled={saving}
                                    className="px-6 py-3 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 font-bold rounded-lg transition-colors duration-300 disabled:opacity-50"
                                >
                                    <span>لغو</span>
                                </button>
                                <button
                                    type="button"
                                    onClick={handleSave}
                                    disabled={saving}
                                    className="px-6 py-3 bg-custom-purple hover:bg-custom-light-purple text-white font-bold rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl disabled:opacity-50 flex items-center gap-2"
                                >
                                    {saving ? (
                                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                    ) : (
                                        <CheckIcon className="w-5 h-5" />
                                    )}
                                    <span>{saving ? 'در حال ذخیره...' : 'ذخیره تغییرات'}</span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            ) : (
                // حالت مشاهده
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div className="lg:col-span-2 space-y-8">
                        {shipment.images && shipment.images.length > 0 ? (
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <img
                                    src={shipment.images[0].url}
                                    alt={shipment.title}
                                    className="w-full h-auto max-h-96 object-cover rounded-xl"
                                    onError={(e) => {
                                        e.currentTarget.src = 'https://via.placeholder.com/800x600?text=بدون+تصویر';
                                    }}
                                />
                                {shipment.images.length > 1 && (
                                    <div className="grid grid-cols-4 gap-2 pt-3">
                                        {shipment.images.slice(1, 5).map((img) => (
                                            <img
                                                key={img.id}
                                                src={img.url}
                                                alt="تصویر مرسوله"
                                                className="w-full h-20 object-cover rounded-lg cursor-pointer hover:opacity-80 transition-opacity"
                                                onError={(e) => {
                                                    e.currentTarget.style.display = 'none';
                                                }}
                                            />
                                        ))}
                                    </div>
                                )}
                            </div>
                        ) : (
                            <p></p>
                        )}
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-4 border-b pb-3 border-gray-200 dark:border-gray-700">
                                توضیحات
                            </h3>
                            <p className="text-gray-600 dark:text-gray-300 leading-relaxed whitespace-pre-line">
                                {shipment.description || 'توضیحاتی ثبت نشده است.'}
                            </p>
                        </div>
                    </div>
                    <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 space-y-4 lg:sticky lg:top-28">
                            <h3 className="text-lg font-semibold mb-2 pb-3 border-b border-gray-200 dark:border-gray-700">
                                اطلاعات کلی
                            </h3>
                            {shipment.category && (
                                <InfoRow
                                    icon={TagIcon}
                                    label="دسته‌بندی"
                                    value={translateCategory(shipment.category)}
                                />
                            )}
                            {shipment.type === 'send' && shipment.weight && (
                                <InfoRow
                                    icon={ScaleIcon}
                                    label="وزن"
                                    value={`${parseFloat(shipment.weight).toLocaleString('fa-IR')} کیلوگرم`}
                                />
                            )}
                            {shipment.type === 'carry' && shipment.carry_weight_capacity && (
                                <InfoRow
                                    icon={ScaleIcon}
                                    label="ظرفیت حمل"
                                    value={`${parseFloat(shipment.carry_weight_capacity).toLocaleString('fa-IR')} کیلوگرم`}
                                />
                            )}
                            <InfoRow
                                icon={MapPinIcon}
                                label="مبدأ"
                                value={`${shipment.origin.city}, ${shipment.origin.country}`}
                            />
                            <InfoRow
                                icon={MapPinIcon}
                                label="مقصد"
                                value={`${shipment.destination.city}, ${shipment.destination.country}`}
                            />
                            {shipment.departure_date && (
                                <InfoRow
                                    icon={CalendarIcon}
                                    label="تاریخ حرکت"
                                    value={convertGregorianToJalali(shipment.departure_date)}
                                />
                            )}
                            {shipment.arrival_date && (
                                <InfoRow
                                    icon={CalendarIcon}
                                    label="تاریخ رسیدن"
                                    value={convertGregorianToJalali(shipment.arrival_date)}
                                />
                            )}
                            <InfoRow
                                icon={DollarSignIcon}
                                label="هزینه"
                                value={formatPrice()}
                                valueClassName="text-green-600 dark:text-green-400 font-bold"
                            />
                            {!isOwnerView && shipment.user && (
                                <div className="pt-3 border-t border-gray-200 dark:border-gray-700">
                                    <InfoRow
                                        icon={UserIcon}
                                        label="ثبت‌کننده"
                                        value={shipment.user.name || 'بدون نام'}
                                    />
                                    {shipment.show_phone && shipment.user.phone && (
                                        <InfoRow
                                            icon={PhoneIcon}
                                            label="تماس"
                                            value={shipment.user.phone}
                                        />
                                    )}
                                </div>
                            )}
                        </div>
                        {isOwnerView && (
                            <div className="space-y-4">
                                <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 border-b border-gray-200 dark:border-gray-700 pb-3">عملیات</h3>
                                    <div className="grid grid-cols-2 gap-4">
                                        <button
                                            onClick={() => setIsEditMode(true)}
                                            className="w-full flex flex-col items-center justify-center gap-2 bg-custom-cyan/10 hover:bg-custom-cyan/20 text-custom-cyan font-bold py-3 px-4 rounded-lg transition-colors duration-300"
                                        >
                                            <PencilIcon className="w-5 h-5" />
                                            <span className="text-sm">ویرایش</span>
                                        </button>
                                        <button
                                            onClick={handleDelete}
                                            disabled={deleting}
                                            className="w-full flex flex-col items-center justify-center gap-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 font-bold py-3 px-4 rounded-lg transition-colors duration-300 disabled:opacity-50"
                                        >
                                            {deleting ? (
                                                <div className="w-5 h-5 border-2 border-red-500 border-t-transparent rounded-full animate-spin"></div>
                                            ) : (
                                                <Trash2Icon className="w-5 h-5" />
                                            )}
                                            <span className="text-sm">{deleting ? 'حذف...' : 'حذف'}</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}
            
            {/* مودال انتخاب موقعیت مکانی */}
            <LocationModal
                isOpen={modalState.isOpen}
                onClose={closeModal}
                onConfirm={confirmLocation}
                field={modalState.field}
            />
        </div>
    );
};

// کامپوننت‌های کمکی
const InfoRow: React.FC<{
    icon: React.FC<{ className?: string }>;
    label: string;
    value: string;
    valueClassName?: string;
}> = ({ icon: Icon, label, value, valueClassName = 'text-gray-800 dark:text-gray-200' }) => (
    <div className="flex items-center justify-between">
        <div className="flex items-center text-gray-500 dark:text-gray-400">
            <Icon className="w-5 h-5 ml-2" />
            <span className="text-sm">{label}</span>
        </div>
        <span className={`font-semibold text-sm ${valueClassName}`}>{value}</span>
    </div>
);

const InputWithIcon: React.FC<{
    icon: React.FC<{ className?: string }>;
    id: string;
    placeholder: string;
    label: string;
    value: string;
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    type?: string;
    step?: string;
    min?: string;
}> = ({ icon: Icon, id, placeholder, label, value, onChange, type = 'text', 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">
            <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
                id={id}
                type={type}
                placeholder={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={value}
                onChange={onChange}
                step={step}
                min={min}
            />
        </div>
    </div>
);

const TextareaWithIcon: React.FC<{
    icon: React.FC<{ className?: string }>;
    id: string;
    placeholder: string;
    label: string;
    value: string;
    onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
}> = ({ icon: Icon, id, placeholder, label, 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 right-3 pointer-events-none">
                <Icon className="w-5 h-5 text-gray-400" />
            </div>
            <textarea
                id={id}
                placeholder={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 h-24 resize-none"
                value={value}
                onChange={onChange}
            />
        </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>
    );
};

// کامپوننت انتخاب تاریخ شمسی
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 } => {
    const today = new Date().toLocaleDateString('fa-IR-u-nu-latn');
    const [year, month] = today.split('/').map(Number);
    return { year, month };
};

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 years = Array.from({ length: 4 }, (_, i) => currentYear + i);
    
    // تجزیه مقدار ورودی به اجزای تاریخ
    const [parsedYear, parsedMonth, parsedDay] = value
        ? value.split('/').map(Number)
        : [undefined, undefined, undefined];
    
    const daysInMonth = parsedYear && parsedMonth
        ? getDaysInJalaliMonth(parsedYear, parsedMonth)
        : 31;
    
    // هندلرهای تغییر — آنها مستقیماً onChange را فراخوانی می‌کنند
    const handleYearChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const year = Number(e.target.value);
        const newDate = `${year}/${parsedMonth || ''}/${parsedDay || ''}`;
        onChange(newDate.replace(/\/{2,}/g, '/').replace(/\/$/, '')); // جلوگیری از اسلش اضافه
    };
    
    const handleMonthChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const month = Number(e.target.value);
        const newDate = `${parsedYear || ''}/${month}/${parsedDay || ''}`;
        onChange(newDate.replace(/\/{2,}/g, '/').replace(/\/$/, ''));
    };
    
    const handleDayChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const day = Number(e.target.value);
        const newDate = `${parsedYear || ''}/${parsedMonth || ''}/${day}`;
        onChange(newDate.replace(/\/{2,}/g, '/').replace(/\/$/, ''));
    };
    
    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={parsedDay || ''}
                        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={parsedMonth || ''}
                        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={parsedYear || ''}
                        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 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>
);

// کامپوننت مودال موقعیت مکانی
declare const L: any;

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-xl 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 ShipmentDetailPage;