import React, { useState, useEffect } from 'react';
import { SearchIcon, MapPinIcon, ChevronDownIcon, UserIcon, CrmIcon, CalendarIcon, ScaleIcon, PlaneIcon, CarIcon, BusIcon, TrainIcon, ChatIcon } from '../Icons';

interface CompanionOffer {
    id: number;
    user: { name: string; avatar: string; rating: number; };
    title: string;
    origin: { country: string; city: string; };
    destination: { country: string; city: string; };
    departureDate: string;
    arrivalDate: string;
    carryCapacity: number; // in kg
    vehicleTypes: Array<'airplane' | 'car' | 'bus' | 'train'>;
    datePosted: string;
}

const mockCompanionOffers: CompanionOffer[] = [
    {
        id: 1,
        user: { name: 'رضا محمدی', avatar: 'https://picsum.photos/id/1012/100/100', rating: 4.8 },
        title: 'سفر هفتگی از تهران به تورنتو',
        origin: { country: 'ایران', city: 'تهران' },
        destination: { country: 'کانادا', city: 'تورنتو' },
        departureDate: '۱۴۰۳/۰۵/۱۰',
        arrivalDate: '۱۴۰۳/۰۵/۱۱',
        carryCapacity: 7,
        vehicleTypes: ['airplane'],
        datePosted: '۱ ساعت پیش',
    },
    {
        id: 2,
        user: { name: 'مریم حسینی', avatar: 'https://picsum.photos/id/1013/100/100', rating: 4.9 },
        title: 'حمل بار با خودرو شخصی از اصفهان به شیراز',
        origin: { country: 'ایران', city: 'اصفهان' },
        destination: { country: 'ایران', city: 'شیراز' },
        departureDate: '۱۴۰۳/۰۵/۱۲',
        arrivalDate: '۱۴۰۳/۰۵/۱۲',
        carryCapacity: 20,
        vehicleTypes: ['car'],
        datePosted: '۸ ساعت پیش',
    },
    {
        id: 3,
        user: { name: 'علی اکبری', avatar: 'https://picsum.photos/id/1015/100/100', rating: 4.5 },
        title: 'سفر با قطار از مشهد به تهران',
        origin: { country: 'ایران', city: 'مشهد' },
        destination: { country: 'ایران', city: 'تهران' },
        departureDate: '۱۴۰۳/۰۵/۱۵',
        arrivalDate: '۱۴۰۳/۰۵/۱۵',
        carryCapacity: 15,
        vehicleTypes: ['train'],
        datePosted: '۲ روز پیش',
    },
    {
        id: 4,
        user: { name: 'سارا نادری', avatar: 'https://picsum.photos/id/1016/100/100', rating: 5.0 },
        title: 'آماده حمل بار از آلمان به ایران',
        origin: { country: 'آلمان', city: 'برلین' },
        destination: { country: 'ایران', city: 'تهران' },
        departureDate: '۱۴۰۳/۰۶/۰۱',
        arrivalDate: '۱۴۰۳/۰۶/۰۱',
        carryCapacity: 10,
        vehicleTypes: ['airplane', 'bus'],
        datePosted: '۳ روز پیش',
    },
];

interface AcceptCompanionPageProps {
    onNavigate: (page: string, payload?: any) => void;
}

const AcceptCompanionPage: React.FC<AcceptCompanionPageProps> = ({ onNavigate }) => {
    const [offers, setOffers] = useState<CompanionOffer[]>(mockCompanionOffers);
    const [filteredOffers, setFilteredOffers] = useState<CompanionOffer[]>(mockCompanionOffers);

    // Filter states
    const [searchQuery, setSearchQuery] = useState('');
    const [originCountry, setOriginCountry] = useState('');
    const [originCity, setOriginCity] = useState('');
    const [destinationCountry, setDestinationCountry] = useState('');
    const [destinationCity, setDestinationCity] = useState('');
    const [sortBy, setSortBy] = useState('newest');

    useEffect(() => {
        let result = [...offers];

        if (searchQuery) {
            result = result.filter(req => req.title.toLowerCase().includes(searchQuery.toLowerCase()));
        }
        if (originCountry) {
            result = result.filter(req => req.origin.country.toLowerCase().includes(originCountry.toLowerCase()));
        }
        if (originCity) {
            result = result.filter(req => req.origin.city.toLowerCase().includes(originCity.toLowerCase()));
        }
        if (destinationCountry) {
            result = result.filter(req => req.destination.country.toLowerCase().includes(destinationCountry.toLowerCase()));
        }
        if (destinationCity) {
            result = result.filter(req => req.destination.city.toLowerCase().includes(destinationCity.toLowerCase()));
        }
        
        // Sort results
        switch (sortBy) {
            case 'capacity_asc':
                result.sort((a, b) => a.carryCapacity - b.carryCapacity);
                break;
            case 'capacity_desc':
                result.sort((a, b) => b.carryCapacity - a.carryCapacity);
                break;
            case 'oldest':
                result.reverse();
                break;
            case 'newest':
            default:
                break;
        }

        setFilteredOffers(result);
    }, [searchQuery, originCountry, originCity, destinationCountry, destinationCity, sortBy, offers]);

    return (
        <div className="flex flex-col space-y-8">
            <div>
                <h1 className="text-3xl font-bold text-gray-800 dark:text-white">پیدا کردن همسفر</h1>
                <p className="text-gray-500 dark:text-gray-400 mt-1">لیست افرادی که آماده همسفری و حمل مرسوله شما هستند را مشاهده کنید.</p>
            </div>

            {/* Filters Card */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    <FilterInput id="searchQuery" label="جستجو در عنوان" placeholder="مثال: سفر از تهران..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)} icon={SearchIcon} />
                    <FilterInput id="originCountry" label="کشور مبدا" placeholder="مثال: ایران" value={originCountry} onChange={e => setOriginCountry(e.target.value)} icon={CrmIcon} />
                    <FilterInput id="originCity" label="شهر مبدا" placeholder="مثال: تهران" value={originCity} onChange={e => setOriginCity(e.target.value)} icon={MapPinIcon} />
                    <FilterInput id="destinationCountry" label="کشور مقصد" placeholder="مثال: کانادا" value={destinationCountry} onChange={e => setDestinationCountry(e.target.value)} icon={CrmIcon} />
                    <FilterInput id="destinationCity" label="شهر مقصد" placeholder="مثال: تورنتو" value={destinationCity} onChange={e => setDestinationCity(e.target.value)} icon={MapPinIcon} />
                    <SortSelect value={sortBy} onChange={e => setSortBy(e.target.value)} />
                </div>
                 <div className="mt-6 flex justify-end">
                    <button className="w-full sm:w-auto bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2.5 px-8 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50 flex items-center justify-center gap-2">
                        <SearchIcon className="w-5 h-5" />
                        <span>جستجو</span>
                    </button>
                </div>
            </div>

            {/* Companions List */}
            {filteredOffers.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredOffers.map(offer => (
                        <CompanionCard key={offer.id} {...offer} onNavigate={onNavigate} />
                    ))}
                </div>
            ) : (
                <div className="col-span-1 md:col-span-2 lg:col-span-3 text-center py-12 bg-custom-light-card dark:bg-custom-dark-blue-light rounded-2xl">
                    <UserIcon className="w-16 h-16 mx-auto text-gray-300 dark:text-gray-600" />
                    <h3 className="mt-4 text-xl font-semibold text-gray-800 dark:text-gray-200">همسفری یافت نشد</h3>
                    <p className="mt-1 text-gray-500 dark:text-gray-400">هیچ همسفری با این مشخصات یافت نشد.</p>
                </div>
            )}
        </div>
    );
};


// Helper components
const FilterInput: React.FC<{id: string, label: string, placeholder: string, value: string, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void, icon: React.FC<{className?: string}>}> = 
({ id, label, placeholder, value, onChange, icon: Icon }) => (
    <div>
        <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
        <div className="relative">
            <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <Icon className="w-5 h-5 text-gray-400" />
            </div>
            <input type="text" 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" value={value} onChange={onChange} />
        </div>
    </div>
);

const SortSelect: React.FC<{value: string, onChange: (e: React.ChangeEvent<HTMLSelectElement>) => void}> = ({ value, onChange }) => (
     <div>
        <label htmlFor="sortBy" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">مرتب‌سازی</label>
        <div className="relative">
             <select id="sortBy" className="w-full appearance-none pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition" value={value} onChange={onChange}>
                <option value="newest">جدیدترین</option>
                <option value="oldest">قدیمی‌ترین</option>
                <option value="capacity_asc">ظرفیت حمل: کم به زیاد</option>
                <option value="capacity_desc">ظرفیت حمل: زیاد به کم</option>
            </select>
            <ChevronDownIcon className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none"/>
        </div>
    </div>
);

const VehicleIconMap = {
    airplane: PlaneIcon,
    car: CarIcon,
    bus: BusIcon,
    train: TrainIcon,
};

interface CompanionCardProps extends CompanionOffer {
    onNavigate: (page: string, payload?: any) => void;
}

const CompanionCard: React.FC<CompanionCardProps> = ({ id, user, title, origin, destination, departureDate, arrivalDate, carryCapacity, vehicleTypes, datePosted, onNavigate }) => {
    return (
        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light rounded-2xl shadow-sm overflow-hidden flex flex-col group transform hover:-translate-y-1.5 transition-transform duration-300">
            <div className="p-5 flex flex-col flex-grow">
                 <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center">
                        <img src={user.avatar} alt={user.name} className="w-12 h-12 rounded-full" />
                        <div className="mr-3">
                            <h3 className="font-bold text-gray-800 dark:text-white">{user.name}</h3>
                             <div className="flex items-center text-xs text-amber-500">
                                <svg className="w-4 h-4 fill-current" viewBox="0 0 20 20"><path d="M10 15l-5.878 3.09 1.123-6.545L.489 6.91l6.572-.955L10 0l2.939 5.955 6.572.955-4.756 4.635 1.123 6.545z"/></svg>
                                <span className="mr-1 font-bold">{user.rating}</span>
                            </div>
                        </div>
                    </div>
                    <div className="px-3 py-1 bg-custom-light-bg dark:bg-custom-dark-blue text-gray-500 dark:text-gray-400 text-xs font-bold rounded-full">{datePosted}</div>
                 </div>

                <h4 className="text-lg font-semibold text-gray-800 dark:text-white mb-3 flex-grow">{title}</h4>
                
                <div className="space-y-3 text-sm text-gray-600 dark:text-gray-300 mb-4 border-t border-gray-200 dark:border-gray-700 pt-4">
                    <InfoRow icon={MapPinIcon} label="مبدا" value={`${origin.city}, ${origin.country}`} />
                    <InfoRow icon={MapPinIcon} label="مقصد" value={`${destination.city}, ${destination.country}`} />
                    <InfoRow icon={CalendarIcon} label="تاریخ حرکت" value={departureDate} />
                    <InfoRow icon={CalendarIcon} label="تاریخ رسیدن" value={arrivalDate} />
                    <InfoRow icon={ScaleIcon} label="ظرفیت حمل" value={`${carryCapacity} کیلوگرم`} valueClassName="text-green-600 dark:text-green-400" />
                </div>
                
                <div className="flex items-center justify-between mt-2 mb-4">
                    <span className="text-sm font-medium text-gray-500 dark:text-gray-400">وسیله نقلیه:</span>
                    <div className="flex gap-2">
                        {/* FIX: The `title` prop is not valid for the Icon component.
Instead, wrap the Icon in a `div` and apply the title and styling to the wrapper.
This correctly applies the tooltip and styles without causing a TypeScript error. */}
                        {vehicleTypes.map(type => {
                             const Icon = VehicleIconMap[type];
                             return <div key={type} title={type} className="w-6 h-6 p-1 flex items-center justify-center text-custom-purple bg-custom-purple/10 rounded-full">
                                <Icon className="w-4 h-4" />
                             </div>;
                        })}
                    </div>
                </div>

                <div className="mt-auto grid grid-cols-2 gap-3">
                    <button onClick={() => onNavigate('messages')} className="w-full flex items-center justify-center gap-2 bg-custom-cyan/10 hover:bg-custom-cyan/20 text-custom-cyan font-bold py-2.5 px-4 rounded-lg transition-colors duration-300">
                        <ChatIcon className="w-5 h-5" />
                        <span>چت</span>
                    </button>
                    <button onClick={() => onNavigate('trip-detail', id.toString())} className="w-full bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2.5 px-4 rounded-lg transition-colors duration-300">
                        ارسال درخواست
                    </button>
                </div>
            </div>
        </div>
    );
};

const InfoRow: React.FC<{icon: React.FC<{className?: string}>, label: string, value: string, valueClassName?: string}> = ({ icon: Icon, label, value, valueClassName = 'text-gray-800 dark:text-gray-200' }) => (
    <div className="flex items-center justify-between">
        <div className="flex items-center text-gray-500 dark:text-gray-400">
            <Icon className="w-4 h-4 ml-2" />
            <span>{label}:</span>
        </div>
        <span className={`font-semibold ${valueClassName}`}>{value}</span>
    </div>
);

export default AcceptCompanionPage;