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

type TripMode = 'register' | 'companion';
type LocationField = 'origin' | 'destination';

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

// سرویس API
const tripAPI = {
    registerTrip: (data: any) => fetch(`${API_BASE_URL}/trips/register`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Auth-Token': localStorage.getItem('auth_token')
        },
        body: JSON.stringify(data)
    }),

    registerCompanion: (data: any) => fetch(`${API_BASE_URL}/trips/companion`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Auth-Token': localStorage.getItem('auth_token')
        },
        body: JSON.stringify(data)
    }),
};
interface RegisterTripPageProps {
    showError: (message: string) => void;
    showSuccess: (message: string) => void;
}

const RegisterTripPage: React.FC<RegisterTripPageProps> = ({ showError, showSuccess }) => {
    const [tripMode, setTripMode] = useState<TripMode>('register');
    const [showPhoneNumber, setShowPhoneNumber] = useState(false);
    const [loading, setLoading] = useState(false);
   

    const [modalState, setModalState] = useState<{ isOpen: boolean; field: LocationField | null }>({ isOpen: false, field: null });
    const [origin, setOrigin] = useState<{ lat: number, lng: number } | null>(null);
    const [destination, setDestination] = useState<{ lat: number, lng: number } | null>(null);

    const [originCountry, setOriginCountry] = useState('');
    const [originCity, setOriginCity] = useState('');
    const [originAddress, setOriginAddress] = useState('');
    const [destinationCountry, setDestinationCountry] = useState('');
    const [destinationCity, setDestinationCity] = useState('');
    const [destinationAddress, setDestinationAddress] = useState('');

    const [vehicleType, setVehicleType] = useState<string>('');
    const [companionVehicleTypes, setCompanionVehicleTypes] = useState<string[]>([]);

    const [departureDate, setDepartureDate] = useState('');
    const [arrivalDate, setArrivalDate] = useState('');
    const [tripDescription, setTripDescription] = useState('');
    const [capacity, setCapacity] = useState('');

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

    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();
    };

    // Reset form state when mode changes to avoid carrying over data
    useEffect(() => {
        setOrigin(null);
        setDestination(null);
        setOriginCountry('');
        setOriginCity('');
        setOriginAddress('');
        setDestinationCountry('');
        setDestinationCity('');
        setDestinationAddress('');
        setDepartureDate('');
        setArrivalDate('');
        setTripDescription('');
        setVehicleType('');
        setCompanionVehicleTypes([]);
        setCapacity('');
      
    }, [tripMode]);

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

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

            if (tripMode === 'register') {
                // اعتبارسنجی فرم ثبت سفر
                if (!originCountry || !originCity || !destinationCountry || !destinationCity || !vehicleType || !departureDate || !capacity) {
                    throw new Error('لطفا تمام فیلدهای обязаاری را پر کنید');
                }

                formData = {
                    origin: {
                        country: originCountry,
                        city: originCity,
                        address: originAddress,
                        coordinates: origin ? `${origin.lat},${origin.lng}` : null,
                    },
                    destination: {
                        country: destinationCountry,
                        city: destinationCity,
                        address: destinationAddress,
                        coordinates: destination ? `${destination.lat},${destination.lng}` : null,
                    },
                    vehicle_type: vehicleType,
                    departure_date: departureDate,
                    arrival_date: arrivalDate,
                    capacity: parseFloat(capacity),
                    description: tripDescription,
                    show_phone: showPhoneNumber,
                };
                apiCall = tripAPI.registerTrip;
            } else {
                // اعتبارسنجی فرم همسفری
                if (!originCountry || !originCity || !destinationCountry || !destinationCity || companionVehicleTypes.length === 0 || !departureDate || !capacity) {
                    throw new Error('لطفا تمام فیلدهای обязаاری را پر کنید');
                }

                formData = {
                    origin: {
                        country: originCountry,
                        city: originCity,
                        address: originAddress,
                        coordinates: origin ? `${origin.lat},${origin.lng}` : null,
                    },
                    destination: {
                        country: destinationCountry,
                        city: destinationCity,
                        address: destinationAddress,
                        coordinates: destination ? `${destination.lat},${destination.lng}` : null,
                    },
                    vehicle_types: companionVehicleTypes,
                    available_from: departureDate,
                    available_to: arrivalDate,
                    capacity: parseFloat(capacity),
                    description: tripDescription,
                    show_phone: showPhoneNumber,
                };
                apiCall = tripAPI.registerCompanion;
            }

            const response = await apiCall(formData);
            const result = await response.json();

            if (!response.ok) {
                const errorData = await response.json();
                const messages = errorData.messages || errorData.error || 'خطا در ثبت اطلاعات';
                if (errorData.errors) {
                    // نمایش اولین خطای اعتبارسنجی (مثل Laravel)
                    const firstError = Object.values(errorData.errors)[0];
                    showError(Array.isArray(firstError) ? firstError[0] : String(firstError));
                } else {
                    showError(messages);
                }
                return;
            }
            showSuccess(tripMode === 'register' ? 'سفر با موفقیت ثبت شد!' : 'آمادگی برای همسفری با موفقیت ثبت شد!');
            // ریست فرم
            setOrigin(null);
            setDestination(null);
            setOriginCountry('');
            setOriginCity('');
            setOriginAddress('');
            setDestinationCountry('');
            setDestinationCity('');
            setDestinationAddress('');
            setDepartureDate('');
            setArrivalDate('');
            setTripDescription('');
            setVehicleType('');
            setCompanionVehicleTypes([]);
            setCapacity('');
            setShowPhoneNumber(false);

        } catch (err: any) {
            showError(err.message || 'خطای ناشناخته رخ داد');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="flex flex-col space-y-8">



            <div>
                <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
                    {tripMode === 'register' ? 'ثبت سفر جدید' : 'اعلام آمادگی برای همسفری'}
                </h1>
                <p className="text-gray-500 dark:text-gray-400 mt-1">
                    {tripMode === 'register' ? 'اطلاعات سفر خود را برای حمل مرسوله وارد کنید.' : 'اطلاعات مسیر و زمان در دسترس بودن خود را ثبت کنید.'}
                </p>
            </div>

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

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

                    {/* Card 2: Trip 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">
                            {tripMode === 'register' ? '۲. جزئیات سفر' : '۲. زمان و ظرفیت در دسترس'}
                        </h3>

                        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                            <PersianDateSelector
                                id={tripMode === 'register' ? "departure_date" : "available_from_date"}
                                label={tripMode === 'register' ? "تاریخ حرکت" : "در دسترس از تاریخ"}
                                value={departureDate}
                                onChange={setDepartureDate}
                            />
                            <PersianDateSelector
                                id={tripMode === 'register' ? "arrival_date" : "available_to_date"}
                                label={tripMode === 'register' ? "تاریخ رسیدن" : "در دسترس تا تاریخ"}
                                value={arrivalDate}
                                onChange={setArrivalDate}
                            />
                        </div>

                        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                            {tripMode === 'register' ? (
                                <VehicleSelector
                                    label="نوع وسیله نقلیه"
                                    options={vehicleOptions}
                                    selectedValue={vehicleType}
                                    onChange={setVehicleType}
                                />
                            ) : (
                                <div className="md:col-span-2">
                                    <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 ${companionVehicleTypes.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={companionVehicleTypes.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 ${companionVehicleTypes.includes(vehicle.id) ? 'bg-custom-purple border-custom-purple' : 'border-gray-300 dark:border-gray-500'}`}>
                                                    {companionVehicleTypes.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 ${companionVehicleTypes.includes(vehicle.id) ? 'text-custom-purple' : 'text-gray-500 dark:text-gray-400'}`} />
                                                <span className={`font-semibold transition-colors ${companionVehicleTypes.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="capacity"
                                label="ظرفیت حمل"
                                placeholder="حداکثر وزن قابل حمل به کیلوگرم"
                                type="number"
                                value={capacity}
                                onChange={(e) => setCapacity(e.target.value)}
                            />
                        </div>

                        <div className="mt-6">
                            <TextareaWithIcon
                                icon={ListIcon}
                                id="description"
                                label="توضیحات (اختیاری)"
                                placeholder={tripMode === 'register' ? "توضیحات بیشتر در مورد سفر، نوع وسیله نقلیه، اقلام ممنوعه و..." : "توضیحات بیشتر در مورد نوع سفر، شرایط خاص و..."}
                                value={tripDescription}
                                onChange={(e) => setTripDescription(e.target.value)}
                            />
                        </div>
                    </div>

                    {/* Card 3: Contact */}
                    <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">
                            <ToggleableContact enabled={showPhoneNumber} setEnabled={setShowPhoneNumber} />
                        </div>
                    </div>

                    <button
                        type="submit"
                        disabled={loading}
                        className="w-full bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-3 px-4 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50 disabled:bg-gray-400 disabled:cursor-not-allowed"
                    >
                        {loading ? 'در حال ثبت...' : tripMode === 'register' ? 'ثبت و اعلام سفر' : 'ثبت آمادگی'}
                    </button>
                </form>
            </div>

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

// کامپوننت‌های کمکی (همان‌ها بدون تغییر)

const VehicleSelector: React.FC<{
    selectedValue: string;
    onChange: (value: string) => void;
    options: { id: string; name: string; icon: React.FC<{ className?: string; }> }[];
    label: string;
}> = ({ selectedValue, onChange, options, label }) => {
    const [isOpen, setIsOpen] = useState(false);
    const selectorRef = useRef<HTMLDivElement>(null);
    const selectedOption = options.find(opt => opt.id === selectedValue);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (selectorRef.current && !selectorRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [selectorRef]);

    return (
        <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
            <div className="relative" ref={selectorRef}>
                <button
                    type="button"
                    onClick={() => setIsOpen(!isOpen)}
                    className="w-full flex items-center justify-between text-right 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"
                >
                    <div className="flex items-center">
                        {selectedOption ? (
                            <>
                                <selectedOption.icon className="w-5 h-5 ml-2 text-gray-500 dark:text-gray-400" />
                                <span className="text-gray-800 dark:text-gray-200">{selectedOption.name}</span>
                            </>
                        ) : (
                            <span className="text-gray-400">یک گزینه را انتخاب کنید</span>
                        )}
                    </div>
                    <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 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
                    </div>
                </button>
                {isOpen && (
                    <ul className="absolute z-10 w-full mt-1 bg-custom-light-card dark:bg-custom-dark-blue-light border border-gray-300 dark:border-gray-600 rounded-lg shadow-lg max-h-60 overflow-auto">
                        {options.map(option => (
                            <li
                                key={option.id}
                                onClick={() => {
                                    onChange(option.id);
                                    setIsOpen(false);
                                }}
                                className="flex items-center p-3 cursor-pointer hover:bg-gray-100 dark:hover:bg-custom-dark-blue"
                            >
                                <option.icon className="w-5 h-5 ml-3 text-gray-500 dark:text-gray-400" />
                                <span className="text-gray-800 dark:text-gray-200">{option.name}</span>
                            </li>
                        ))}
                    </ul>
                )}
            </div>
        </div>
    );
};

const ToggleableContact: React.FC<{ enabled: boolean, setEnabled: (e: boolean) => void }> = ({ enabled, setEnabled }) => (
    <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={enabled} setEnabled={setEnabled} />
    </div>
);

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

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

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

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

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

const PersianDateSelector: React.FC<PersianDateSelectorProps> = ({ id, label, value, onChange }) => {
    const today = getJalaliToday();
    const currentYear = today.year;

    const [selectedYear, setSelectedYear] = useState<number | undefined>();
    const [selectedMonth, setSelectedMonth] = useState<number | undefined>();
    const [selectedDay, setSelectedDay] = useState<number | undefined>();

    const years = Array.from({ length: 4 }, (_, i) => currentYear + i);
    const daysInMonth = selectedYear && selectedMonth ? getDaysInJalaliMonth(selectedYear, selectedMonth) : 31;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    useEffect(() => {
        if (!isOpen) return;

        const cleanup = () => {
            if (mapRef.current) {
                mapRef.current.remove();
                mapRef.current = null;
            }
            markerRef.current = null;
            setSelectedLocation(null);
            setSearchQuery('');
        };

        if (mapContainerRef.current && !mapRef.current) {
            const map = L.map(mapContainerRef.current).setView([35.6892, 51.3890], 10);
            mapRef.current = map;

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);

            map.on('click', (e: any) => {
                const { lat, lng } = e.latlng;
                setSelectedLocation({ lat, lng });

                if (markerRef.current) {
                    markerRef.current.setLatLng(e.latlng);
                } else {
                    markerRef.current = L.marker(e.latlng).addTo(mapRef.current);
                }
            });

            setTimeout(() => map.invalidateSize(), 100);
        }

        return cleanup;
    }, [isOpen]);

    const handleSearch = async () => {
        if (!searchQuery.trim()) return;
        setIsSearching(true);
        try {
            const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchQuery)}&accept-language=fa`);
            if (!response.ok) throw new Error('Network response was not ok');
            const data = await response.json();

            if (data && data.length > 0) {
                const { lat, lon } = data[0];
                const newLat = parseFloat(lat);
                const newLng = parseFloat(lon);
                const latlng = { lat: newLat, lng: newLng };

                setSelectedLocation(latlng);

                if (mapRef.current) {
                    mapRef.current.setView(latlng, 15);
                    if (markerRef.current) {
                        markerRef.current.setLatLng(latlng);
                    } else {
                        markerRef.current = L.marker(latlng).addTo(mapRef.current);
                    }
                }
            } else {
                alert('مکان مورد نظر یافت نشد.');
            }
        } catch (error) {
            console.error("Geocoding error:", error);
            alert('خطایی در جستجوی مکان رخ داد.');
        } finally {
            setIsSearching(false);
        }
    };

    const handleUseCurrentLocation = async () => {
        if (!navigator.geolocation) {
            alert("مرورگر شما از موقعیت‌یابی جغرافیایی پشتیبانی نمی‌کند.");
            return;
        }

        if (navigator.permissions && navigator.permissions.query) {
            try {
                const permissionStatus = await navigator.permissions.query({ name: 'geolocation' });
                if (permissionStatus.state === 'denied') {
                    alert("شما دسترسی به موقعیت مکانی را مسدود کرده‌اید. لطفاً آن را در تنظیمات مرورگر خود فعال کنید.");
                    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;
                }
                alert(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()}
            >
                {/* Header */}
                <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>

                {/* Content */}
                <div className="p-6 space-y-5">
                    <div className="flex items-center gap-2">
                        <div className="relative flex-grow">
                            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                <SearchIcon className="w-5 h-5 text-gray-400" />
                            </div>
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                onKeyDown={(e) => { if (e.key === 'Enter') handleSearch(); }}
                                placeholder="جستجوی آدرس یا مکان..."
                                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
                            />
                        </div>
                        <button
                            onClick={handleSearch}
                            disabled={isSearching}
                            className="flex-shrink-0 flex items-center justify-center w-28 py-2.5 px-4 rounded-lg bg-custom-purple text-white font-semibold hover:bg-custom-light-purple transition-colors disabled:bg-gray-400 disabled:cursor-wait"
                        >
                            {isSearching ? (
                                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                            ) : (
                                <span>جستجو</span>
                            )}
                        </button>
                    </div>

                    <button
                        onClick={handleUseCurrentLocation}
                        className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl bg-gradient-to-br from-custom-cyan to-teal-400 text-white font-semibold hover:shadow-lg hover:shadow-custom-cyan/30 transition-all duration-300 transform hover:-translate-y-0.5"
                    >
                        <CrosshairIcon className="w-5 h-5" />
                        <span>استفاده از موقعیت فعلی من</span>
                    </button>

                    <div className="relative my-4">
                        <div className="absolute inset-0 flex items-center" aria-hidden="true">
                            <div className="w-full border-t border-gray-300 dark:border-gray-600" />
                        </div>
                        <div className="relative flex justify-center">
                            <span className="bg-custom-light-card dark:bg-custom-dark-blue-light px-3 text-sm text-gray-500 dark:text-gray-400">یا</span>
                        </div>
                    </div>

                    <p className="text-center text-sm text-gray-500 dark:text-gray-400 -mt-2 mb-2">برای انتخاب، روی نقشه کلیک کنید.</p>
                    <div ref={mapContainerRef} className="w-full h-80 bg-gray-200 dark:bg-gray-700 rounded-lg cursor-pointer z-0 border border-gray-300 dark:border-gray-600 shadow-inner">
                        {/* Leaflet map will render here */}
                    </div>
                </div>

                {/* Footer */}
                <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 RegisterTripPage;