// src/components/pages/TripDetailPage.tsx
import React, { useState, useEffect, useRef } from 'react';
import {
    SearchIcon, ChevronDownIcon, MapPinIcon, ClockIcon, PlaneIcon, UserIcon, ScaleIcon,
    CalendarIcon, ChatIcon, PencilIcon, Trash2Icon, CheckIcon, XIcon, GlobeIcon, CarIcon,
    BusIcon, TrainIcon, CrmIcon, HomeIcon, ListIcon, PhoneIcon, CrosshairIcon
} from '../Icons';
import { authFetch } from '../../App';
import moment from 'moment-jalaali';
import { API_BASE_URL } from '@/src/config.js';
// --- Helper Functions ---
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 persianMonths = [
    "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور",
    "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"
];

const parseJalaliDateForDisplay = (dateStr: string): string => {
    if (!dateStr) return '';
    return dateStr.replace(/-/g, '/');
};

const formatJalaliDateForServer = (dateStr: string): string => {
    if (!dateStr) return '';
    return dateStr.replace(/\//g, '-');
};

const formatDate = (dateString: string): string => {
    if (!dateString) return '—';
    const date = new Date(dateString);
    return new Date(dateString).toLocaleDateString('fa-IR', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
};

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

const PersianDateSelector: React.FC<PersianDateSelectorProps> = ({ id, label, value, onChange }) => {
    const today = moment().locale('fa').format('jYYYY/jMM/jDD');
    const currentYear = parseInt(today.split('/')[0]);
    const years = Array.from({ length: 4 }, (_, i) => currentYear + i);
    const [yearStr, monthStr, dayStr] = value ? value.split('/') : ['', '', ''];
    const year = yearStr ? parseInt(yearStr) : undefined;
    const month = monthStr ? parseInt(monthStr) : undefined;
    const daysInMonth = year && month ? getDaysInJalaliMonth(year, month) : 31;

    const handleYearChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newDate = `${e.target.value}/${monthStr || ''}/${dayStr || ''}`;
        onChange(newDate.replace(/\/{2,}/g, '/').replace(/\/$/, ''));
    };

    const handleMonthChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newDate = `${yearStr || ''}/${e.target.value}/${dayStr || ''}`;
        onChange(newDate.replace(/\/{2,}/g, '/').replace(/\/$/, ''));
    };

    const handleDayChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newDate = `${yearStr || ''}/${monthStr || ''}/${e.target.value}`;
        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={dayStr || ''} 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={monthStr || ''} 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={yearStr || ''} 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>
    );
};

// --- Helper Components ---
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; }> = ({ icon: Icon, id, placeholder, label, value, onChange, type = 'text' }) => (
    <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 id={id} type={type} placeholder={placeholder} 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`} value={value} onChange={onChange} />
        </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 min-h-[100px] resize-y" value={value} onChange={onChange} />
        </div>
    </div>
);

const ToggleSwitch: React.FC<{ enabled: boolean; setEnabled: (enabled: boolean) => void; }> = ({ enabled, setEnabled }) => (
    <button type="button" onClick={() => setEnabled(!enabled)} className={`${enabled ? 'bg-custom-purple' : 'bg-gray-300 dark:bg-gray-600'} relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-custom-purple focus:ring-offset-2`}>
        <span className={`${enabled ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition-transform`} />
    </button>
);

const InputWithLocationButton: React.FC<{ id: string; label: string; placeholder: string; value: string; onButtonClick: () => void; }> = ({ 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>
);

// --- Vehicles ---
const vehicleOptions = [
    { id: 'private_car', name: 'ماشین شخصی', icon: CarIcon },
    { id: 'bus', name: 'اتوبوس', icon: BusIcon },
    { id: 'train', name: 'قطار', icon: TrainIcon },
    { id: 'airplane', name: 'هواپیما', icon: PlaneIcon },
];

const getVehicleTypeName = (vehicleType: string) => {
    const option = vehicleOptions.find(opt => opt.id === vehicleType);
    return option ? option.name : vehicleType;
};

// --- MAIN COMPONENT ---
interface TripDetailPageProps {
    tripId: string | null;
    onNavigate: (page: string, payload?: any, options?: { isOwnerView?: boolean }) => void;
    isOwnerView?: boolean;
    type?: 'trip' | 'companion';
}

const TripDetailPage: React.FC<TripDetailPageProps> = ({ tripId, onNavigate, isOwnerView = false, type = 'trip' }) => {
    const [trip, setTrip] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [isEditMode, setIsEditMode] = useState(false);
    const [saving, setSaving] = useState(false);
    const [deleting, setDeleting] = useState(false);
    
    // Edit states
    const [editOriginCountry, setEditOriginCountry] = useState('');
    const [editOriginCity, setEditOriginCity] = useState('');
    const [editOriginAddress, setEditOriginAddress] = useState('');
    const [editOriginCoordinates, setEditOriginCoordinates] = useState('');
    const [editDestinationCountry, setEditDestinationCountry] = useState('');
    const [editDestinationCity, setEditDestinationCity] = useState('');
    const [editDestinationAddress, setEditDestinationAddress] = useState('');
    const [editDestinationCoordinates, setEditDestinationCoordinates] = useState('');
    const [editVehicleType, setEditVehicleType] = useState('');
    const [editCompanionVehicleTypes, setEditCompanionVehicleTypes] = useState<string[]>([]);
    const [editDepartureDate, setEditDepartureDate] = useState('');
    const [editArrivalDate, setEditArrivalDate] = useState('');
    const [editCapacity, setEditCapacity] = useState('');
    const [editDescription, setEditDescription] = useState('');
    const [editShowPhone, setEditShowPhone] = useState(false);
    
    const [modalState, setModalState] = useState<{ isOpen: boolean; field: 'origin' | 'destination' | 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);

    // Fetch data
    useEffect(() => {
        if (!tripId) return;
        const fetchTripDetails = async () => {
            try {
                setLoading(true);
                setError(null);
                const endpoint = type === 'trip' ? `trips/trip/${tripId}` : `trips/companion/${tripId}`;
                const response = await authFetch(`${API_BASE_URL}/${endpoint}`);
                if (!response.ok) throw new Error('خطا در دریافت اطلاعات');
                const data = await response.json();
                setTrip(data.data);
            } catch (err: any) {
                setError(err.message || 'خطا در بارگذاری اطلاعات');
            } finally {
                setLoading(false);
            }
        };
        fetchTripDetails();
    }, [tripId, type]);

    // Fill edit form
    useEffect(() => {
        if (isEditMode && trip) {
            setEditOriginCountry(trip.origin_country || '');
            setEditOriginCity(trip.origin_city || '');
            setEditOriginAddress(trip.origin_address || '');
            setEditOriginCoordinates(trip.origin_coordinates || '');
            setOrigin(trip.origin_coordinates ? {
                lat: parseFloat(trip.origin_coordinates.split(',')[0]),
                lng: parseFloat(trip.origin_coordinates.split(',')[1])
            } : null);
            setEditDestinationCountry(trip.destination_country || '');
            setEditDestinationCity(trip.destination_city || '');
            setEditDestinationAddress(trip.destination_address || '');
            setEditDestinationCoordinates(trip.destination_coordinates || '');
            setDestination(trip.destination_coordinates ? {
                lat: parseFloat(trip.destination_coordinates.split(',')[0]),
                lng: parseFloat(trip.destination_coordinates.split(',')[1])
            } : null);
            setEditVehicleType(trip.vehicle_type || '');
            setEditCompanionVehicleTypes(trip.vehicle_types || []);
            setEditDepartureDate(trip.departure_date ? parseJalaliDateForDisplay(trip.departure_date) : '');
            setEditArrivalDate(trip.arrival_date ? parseJalaliDateForDisplay(trip.arrival_date) : '');
            setEditCapacity(trip.capacity ? String(trip.capacity) : '');
            setEditDescription(trip.description || '');
            setEditShowPhone(trip.show_phone || false);
        }
    }, [isEditMode, trip]);

    const handleDelete = async () => {
        if (!tripId || !window.confirm('آیا از حذف این مورد مطمئن هستید؟')) return;
        setDeleting(true);
        try {
            const endpoint = type === 'trip' ? `trips/trip/${tripId}` : `trips/companion/${tripId}`;
            const response = await authFetch(`${API_BASE_URL}/${endpoint}`, { method: 'DELETE' });
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'خطا در حذف');
            }
            onNavigate(type === 'trip' ? 'my-trips' : 'my-companions');
        } catch (err: any) {
            alert(err.message || 'خطا در حذف');
        } finally {
            setDeleting(false);
        }
    };

    // Modal handlers
    const openModal = (field: 'origin' | 'destination') => setModalState({ isOpen: true, field });
    const closeModal = () => setModalState({ isOpen: false, field: null });
    const confirmLocation = (location: { lat: number, lng: number }) => {
        if (modalState.field === 'origin') {
            setOrigin(location);
            setEditOriginCoordinates(`${location.lat},${location.lng}`);
        } else if (modalState.field === 'destination') {
            setDestination(location);
            setEditDestinationCoordinates(`${location.lat},${location.lng}`);
        }
        closeModal();
    };

    // Companion vehicle
    const handleCompanionVehicleChange = (vehicleId: string) => {
        setEditCompanionVehicleTypes(prev =>
            prev.includes(vehicleId)
                ? prev.filter(v => v !== vehicleId)
                : [...prev, vehicleId]
        );
    };

    // Submit edit
    const handleEditSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);
        try {
            const endpoint = type === 'trip' ? `trips/trip/${tripId}` : `trips/companion/${tripId}`;
            const formData = new FormData();
            formData.append('_method', 'PUT');
            formData.append('origin[country]', editOriginCountry);
            formData.append('origin[city]', editOriginCity);
            formData.append('origin[address]', editOriginAddress);
            formData.append('origin[coordinates]', editOriginCoordinates);
            formData.append('destination[country]', editDestinationCountry);
            formData.append('destination[city]', editDestinationCity);
            formData.append('destination[address]', editDestinationAddress);
            formData.append('destination[coordinates]', editDestinationCoordinates);
            formData.append('capacity', editCapacity);
            formData.append('description', editDescription);
            formData.append('show_phone', editShowPhone ? '1' : '0');
            if (type === 'trip') {
                formData.append('vehicle_type', editVehicleType);
                formData.append('departure_date', editDepartureDate ? formatJalaliDateForServer(editDepartureDate) : '');
                formData.append('arrival_date', editArrivalDate ? formatJalaliDateForServer(editArrivalDate) : '');
            } else {
                editCompanionVehicleTypes.forEach(vehicleType => {
                    formData.append('vehicle_types[]', vehicleType);
                });
                if (!editDepartureDate) {
                    const today = moment().locale('fa').format('jYYYY/jMM/jDD');
                    formData.append('available_from', formatJalaliDateForServer(today));
                } else {
                    formData.append('available_from', formatJalaliDateForServer(editDepartureDate));
                }
                formData.append('available_to', editArrivalDate ? formatJalaliDateForServer(editArrivalDate) : '');
            }
            const response = await authFetch(`${API_BASE_URL}/${endpoint}`, {
                method: 'POST',
                body: formData,
            });
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'خطا در به‌روزرسانی');
            }
            const result = await response.json();
            setTrip(result.data);
            setIsEditMode(false);
        } catch (err: any) {
            alert(err.message || 'خطا در به‌روزرسانی');
        } finally {
            setSaving(false);
        }
    };

    if (loading) return <div className="text-center py-12">در حال بارگذاری...</div>;
    if (error) return <div className="text-center py-12 text-red-500">خطا: {error}</div>;
    if (!trip) return <div className="text-center py-12">اطلاعاتی یافت نشد.</div>;

    if (isEditMode) {
        return (
            <form onSubmit={handleEditSubmit} className="space-y-8">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">ویرایش {type === 'trip' ? 'سفر' : 'همسفری'}</h1>
                    <button
                        type="button"
                        onClick={() => setIsEditMode(false)}
                        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"
                    >
                        <span>بازگشت به نمایش</span>
                    </button>
                </div>

                {/* Origins & Destinations */}
                <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={origin ? `${origin.lat.toFixed(5)}, ${origin.lng.toFixed(5)}` : ''}
                                id="edit_origin"
                                placeholder="موقعیت ثبت نشده"
                                label="انتخاب از روی نقشه"
                            />
                            <InputWithIcon icon={CrmIcon} id="edit_origin_country" placeholder="مثال: ایران" label="کشور" value={editOriginCountry} onChange={(e) => setEditOriginCountry(e.target.value)} />
                            <InputWithIcon icon={MapPinIcon} id="edit_origin_city" placeholder="مثال: تهران" label="شهر" value={editOriginCity} onChange={(e) => setEditOriginCity(e.target.value)} />
                            <InputWithIcon icon={HomeIcon} id="edit_origin_address" placeholder="آدرس کامل" label="آدرس دستی" value={editOriginAddress} onChange={(e) => setEditOriginAddress(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={destination ? `${destination.lat.toFixed(5)}, ${destination.lng.toFixed(5)}` : ''}
                                id="edit_destination"
                                placeholder="موقعیت ثبت نشده"
                                label="انتخاب از روی نقشه"
                            />
                            <InputWithIcon icon={CrmIcon} id="edit_destination_country" placeholder="مثال: کانادا" label="کشور" value={editDestinationCountry} onChange={(e) => setEditDestinationCountry(e.target.value)} />
                            <InputWithIcon icon={MapPinIcon} id="edit_destination_city" placeholder="مثال: تورنتو" label="شهر" value={editDestinationCity} onChange={(e) => setEditDestinationCity(e.target.value)} />
                            <InputWithIcon icon={HomeIcon} id="edit_destination_address" placeholder="آدرس کامل" label="آدرس دستی" value={editDestinationAddress} onChange={(e) => setEditDestinationAddress(e.target.value)} />
                        </div>
                    </div>
                </div>

                {/* Details */}
                <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">جزئیات {type === 'trip' ? 'سفر' : 'همسفری'}</h3>
                    <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                        <PersianDateSelector
                            id="edit_departure_date"
                            label={type === 'trip' ? "تاریخ حرکت" : "در دسترس از تاریخ"}
                            value={editDepartureDate}
                            onChange={setEditDepartureDate}
                        />
                        <PersianDateSelector
                            id="edit_arrival_date"
                            label={type === 'trip' ? "تاریخ رسیدن" : "در دسترس تا تاریخ"}
                            value={editArrivalDate}
                            onChange={setEditArrivalDate}
                        />
                    </div>
                    {type === 'trip' ? (
                        <div className="mt-6">
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">وسیله نقلیه</label>
                            <select
                                value={editVehicleType}
                                onChange={(e) => setEditVehicleType(e.target.value)}
                                className="w-full appearance-none 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"
                            >
                                {vehicleOptions.map(option => (
                                    <option key={option.id} value={option.id}>{option.name}</option>
                                ))}
                            </select>
                        </div>
                    ) : (
                        <div className="mt-6">
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">وسایل نقلیه مورد نظر</label>
                            <div className="grid grid-cols-2 gap-3">
                                {vehicleOptions.map(vehicle => (
                                    <label
                                        key={vehicle.id}
                                        className={`flex items-center p-3 border rounded-lg cursor-pointer transition-all duration-200 ${editCompanionVehicleTypes.includes(vehicle.id)
                                            ? 'bg-custom-purple/10 border-custom-purple ring-2 ring-custom-purple/50 dark:bg-custom-purple/20'
                                            : 'bg-custom-light-bg dark:bg-custom-dark-blue border-gray-300 dark:border-gray-600 hover:border-custom-purple/50'
                                            }`}
                                    >
                                        <input
                                            type="checkbox"
                                            checked={editCompanionVehicleTypes.includes(vehicle.id)}
                                            onChange={() => handleCompanionVehicleChange(vehicle.id)}
                                            className="sr-only"
                                        />
                                        <div
                                            className={`w-5 h-5 border-2 rounded flex-shrink-0 flex items-center justify-center ml-3 transition-all duration-200 ${editCompanionVehicleTypes.includes(vehicle.id)
                                                ? 'bg-custom-purple border-custom-purple'
                                                : 'border-gray-300 dark:border-gray-500'
                                                }`}
                                        >
                                            {editCompanionVehicleTypes.includes(vehicle.id) && (
                                                <svg className="w-3 h-3 text-white fill-current" viewBox="0 0 20 20">
                                                    <path d="M0 11l2-2 5 5L18 3l2 2L7 18z" />
                                                </svg>
                                            )}
                                        </div>
                                        <vehicle.icon
                                            className={`w-6 h-6 ml-2 transition-colors ${editCompanionVehicleTypes.includes(vehicle.id)
                                                ? 'text-custom-purple'
                                                : 'text-gray-500 dark:text-gray-400'
                                                }`}
                                        />
                                        <span
                                            className={`font-semibold transition-colors ${editCompanionVehicleTypes.includes(vehicle.id)
                                                ? 'text-custom-purple dark:text-custom-light-purple'
                                                : 'text-gray-800 dark:text-gray-200'
                                                }`}
                                        >
                                            {vehicle.name}
                                        </span>
                                    </label>
                                ))}
                            </div>
                        </div>
                    )}
                    <InputWithIcon
                        icon={ScaleIcon}
                        id="edit_capacity"
                        label="ظرفیت حمل"
                        placeholder="به کیلوگرم"
                        type="number"
                        value={editCapacity}
                        onChange={(e) => setEditCapacity(e.target.value)}
                        className="mt-6"
                    />
                    <TextareaWithIcon
                        icon={ListIcon}
                        id="edit_description"
                        label="توضیحات"
                        placeholder={type === 'trip' ? "توضیحات سفر..." : "توضیحات همسفری..."}
                        value={editDescription}
                        onChange={(e) => setEditDescription(e.target.value)}
                        className="mt-6"
                    />
                </div>

                {/* Contact Info */}
                <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="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={editShowPhone} setEnabled={setEditShowPhone} />
                    </div>
                </div>

                {/* Actions */}
                <div className="flex justify-end gap-4">
                    <button
                        type="button"
                        onClick={() => setIsEditMode(false)}
                        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"
                    >
                        لغو
                    </button>
                    <button
                        type="submit"
                        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>}
                        ذخیره تغییرات
                    </button>
                </div>
                <LocationModal isOpen={modalState.isOpen} onClose={closeModal} onConfirm={confirmLocation} field={modalState.field} />
            </form>
        );
    }

    // ✅ VIEW MODE - FULLY ENHANCED
    return (
        <div className="space-y-6">
            <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">
                        {type === 'trip'
                            ? `سفر از ${trip.origin_city} به ${trip.destination_city}`
                            : `همسفری از ${trip.origin_city} به ${trip.destination_city}`}
                    </h1>
                    <p className="text-gray-500 dark:text-gray-400 mt-1">
                        {type === 'trip' ? 'جزئیات کامل سفر' : 'جزئیات کامل اعلام آمادگی'}
                    </p>
                </div>
                <div className="flex gap-2">
                    <button
                        onClick={() => onNavigate(type === 'trip' ? 'my-trips' : 'my-companions')}
                        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"
                    >
                        بازگشت
                    </button>
                  
                </div>
            </div>

            {/* Enhanced View Mode */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div className="lg:col-span-2 space-y-8">
                    {/* Main Info */}
                    <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 flex items-center gap-2">
                            {type === 'trip' ? 'جزئیات سفر' : 'جزئیات اعلام آمادگی همسفری'}
                        </h3>
                        <div className="space-y-4">
                            {(trip.departure_date || trip.available_from) && (
                                <div className="flex items-start gap-3">
                                    <CalendarIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                    <div>
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">
                                            {type === 'trip' ? 'تاریخ حرکت:' : 'در دسترس از تاریخ:'}
                                        </span>
                                        <p className="font-medium">
                                            {type === 'trip' 
                                                ? parseJalaliDateForDisplay(trip.departure_date) 
                                                : parseJalaliDateForDisplay(trip.available_from)}
                                        </p>
                                    </div>
                                </div>
                            )}
                            {(trip.arrival_date || trip.available_to) && (
                                <div className="flex items-start gap-3">
                                    <CalendarIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                    <div>
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">
                                            {type === 'trip' ? 'تاریخ رسیدن:' : 'در دسترس تا تاریخ:'}
                                        </span>
                                        <p className="font-medium">
                                            {type === 'trip' 
                                                ? parseJalaliDateForDisplay(trip.arrival_date) 
                                                : parseJalaliDateForDisplay(trip.available_to)}
                                        </p>
                                    </div>
                                </div>
                            )}
                            {trip.capacity && (
                                <div className="flex items-center gap-3">
                                    <ScaleIcon className="w-5 h-5 text-gray-500" />
                                    <div>
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">ظرفیت حمل:</span>
                                        <p className="font-medium">{trip.capacity} کیلوگرم</p>
                                    </div>
                                </div>
                            )}
                            {type === 'trip' && trip.vehicle_type && (
                                <div className="flex items-center gap-3">
                                    <CarIcon className="w-5 h-5 text-gray-500" />
                                    <div>
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">وسیله نقلیه:</span>
                                        <p className="font-medium">{getVehicleTypeName(trip.vehicle_type)}</p>
                                    </div>
                                </div>
                            )}
                            {type === 'companion' && trip.vehicle_types && trip.vehicle_types.length > 0 && (
                                <div className="flex items-start gap-3">
                                    <CarIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                    <div>
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">وسایل نقلیه مورد نظر:</span>
                                        <div className="flex flex-wrap gap-2 mt-1">
                                            {trip.vehicle_types.map((v: string) => (
                                                <span
                                                    key={v}
                                                    className="px-3 py-1 bg-custom-purple/10 text-custom-purple dark:bg-custom-purple/20 dark:text-custom-light-purple rounded-full text-sm font-medium"
                                                >
                                                    {getVehicleTypeName(v)}
                                                </span>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            )}
                            {trip.description && (
                                <div>
                                    <div className="flex items-start gap-3 mb-2">
                                        <ListIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                        <span className="text-gray-500 dark:text-gray-400 text-sm">توضیحات:</span>
                                    </div>
                                    <p className="text-gray-600 dark:text-gray-300 leading-relaxed whitespace-pre-line bg-custom-light-bg dark:bg-custom-dark-blue p-3 rounded-lg">
                                        {trip.description}
                                    </p>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Full Addresses */}
                    <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-1 md:grid-cols-2 gap-6">
                            <div>
                                <h4 className="font-medium text-green-600 dark:text-green-400 mb-2 flex items-center gap-2">
                                    <MapPinIcon className="w-4 h-4" /> مبدأ
                                </h4>
                                <p className="text-gray-700 dark:text-gray-300 mb-1">
                                    <span className="font-semibold">{trip.origin_city}, {trip.origin_country}</span>
                                </p>
                                {trip.origin_address && (
                                    <p className="text-gray-600 dark:text-gray-400 text-sm">{trip.origin_address}</p>
                                )}
                                {trip.origin_coordinates && (
                                    <a
                                        href={`https://www.google.com/maps?q=${trip.origin_coordinates}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="text-custom-purple hover:underline text-sm mt-1 inline-block"
                                    >
                                        نمایش روی نقشه
                                    </a>
                                )}
                            </div>
                            <div>
                                <h4 className="font-medium text-red-600 dark:text-red-400 mb-2 flex items-center gap-2">
                                    <MapPinIcon className="w-4 h-4" /> مقصد
                                </h4>
                                <p className="text-gray-700 dark:text-gray-300 mb-1">
                                    <span className="font-semibold">{trip.destination_city}, {trip.destination_country}</span>
                                </p>
                                {trip.destination_address && (
                                    <p className="text-gray-600 dark:text-gray-400 text-sm">{trip.destination_address}</p>
                                )}
                                {trip.destination_coordinates && (
                                    <a
                                        href={`https://www.google.com/maps?q=${trip.destination_coordinates}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="text-custom-purple hover:underline text-sm mt-1 inline-block"
                                    >
                                        نمایش روی نقشه
                                    </a>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Status and Registration Info */}
                    <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 flex items-center gap-2">
                            وضعیت و اطلاعات
                        </h3>
                        <div className="space-y-4">
                            <div className="flex justify-between">
                                <span className="text-gray-500 dark:text-gray-400">وضعیت</span>
                                <span className={`px-3 py-1 rounded-full text-xs font-bold ${trip.status === 'active' ? 'bg-green-500/10 text-green-500' :
                                        trip.status === 'pending' ? 'bg-custom-orange/10 text-custom-orange' :
                                            'bg-gray-500/10 text-gray-500 dark:bg-gray-400/10 dark:text-gray-400'
                                    }`}>
                                    {trip.status === 'active' ? 'فعال' : trip.status === 'pending' ? 'در انتظار تایید' : 'انجام شده'}
                                </span>
                            </div>
                            <div className="flex justify-between">
                                <span className="text-gray-500 dark:text-gray-400">تاریخ ثبت</span>
                                <span className="font-medium">{formatDate(trip.created_at)}</span>
                            </div>
                            {trip.show_phone && trip.user?.phone && (
                                <div className="pt-3 border-t border-gray-200 dark:border-gray-700">
                                    <div className="flex items-center gap-2 text-gray-700 dark:text-gray-300">
                                        <PhoneIcon className="w-5 h-5 text-gray-500" />
                                        <span className="font-medium">{trip.user.phone}</span>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Sidebar Info */}
                {isOwnerView && (
                    <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-lg font-semibold pb-3 border-b border-gray-200 dark:border-gray-700">عملیات</h3>
                            <div className="grid grid-cols-2 gap-4 mt-4">
                                <button
                                    onClick={() => setIsEditMode(true)}
                                    className="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"
                                >
                                    <PencilIcon className="w-5 h-5" />
                                    <span className="text-sm">ویرایش</span>
                                </button>
                                <button
                                    onClick={handleDelete}
                                    disabled={deleting}
                                    className="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 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>
            <LocationModal isOpen={modalState.isOpen} onClose={closeModal} onConfirm={confirmLocation} field={modalState.field} />
        </div>
    );
};

// --- LocationModal ---
declare const L: any;

interface LocationModalProps {
    isOpen: boolean;
    onClose: () => void;
    onConfirm: (location: { lat: number, lng: number }) => void;
    field: 'origin' | 'destination' | 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('جستجو ناموفق بود');
            const data = await response.json();
            if (data && data.length > 0) {
                const { lat, lon } = data[0];
                const latlng = { lat: parseFloat(lat), lng: parseFloat(lon) };
                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); }
                }
            }
        } catch (error) {
            console.error("Geocoding error:", error);
        } finally {
            setIsSearching(false);
        }
    };

    const handleUseCurrentLocation = async () => {
        if (!navigator.geolocation) return;
        navigator.geolocation.getCurrentPosition(
            (position) => {
                const { lat, 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)
        );
    };

    const handleConfirm = () => {
        if (selectedLocation) { onConfirm(selectedLocation); }
    };

    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 TripDetailPage;