import React, { useState, useEffect } from 'react';
import { SearchIcon, MapPinIcon, DollarSignIcon, ClockIcon, PackageIcon, CrmIcon, ChevronDownIcon, ScaleIcon, ChatIcon } from '../Icons';

interface Shipment {
    id: number;
    title: string;
    imageUrl: string;
    origin: { country: string; city: string; };
    destination: { country: string; city: string; };
    weight: number; // in kg
    category: string;
    fee: number;
    currency: 'USD' | 'CAD' | 'IRT' | 'EUR';
    datePosted: string;
}

const mockShipments: Shipment[] = [
  {
    id: 1,
    title: 'بسته مدارک مهم شرکتی',
    imageUrl: 'https://picsum.photos/seed/docs1/400/300',
    origin: { country: 'ایران', city: 'تهران' },
    destination: { country: 'کانادا', city: 'تورنتو' },
    weight: 0.5,
    category: 'مدارک و اسناد',
    fee: 50,
    currency: 'USD',
    datePosted: '۳ ساعت پیش',
  },
  {
    id: 2,
    title: 'لپتاپ و لوازم جانبی',
    imageUrl: 'https://picsum.photos/seed/laptop2/400/300',
    origin: { country: 'آمریکا', city: 'لس آنجلس' },
    destination: { country: 'ایران', city: 'شیراز' },
    weight: 3,
    category: 'لوازم الکترونیکی',
    fee: 120,
    currency: 'USD',
    datePosted: '۱ روز پیش',
  },
  {
    id: 3,
    title: 'مجموعه کتاب‌های نایاب',
    imageUrl: 'https://picsum.photos/seed/books3/400/300',
    origin: { country: 'ایران', city: 'اصفهان' },
    destination: { country: 'آلمان', city: 'برلین' },
    weight: 4.5,
    category: 'کتاب و مجله',
    fee: 80,
    currency: 'EUR',
    datePosted: '۲ روز پیش',
  },
  {
    id: 4,
    title: 'لباس‌های محلی و صنایع دستی',
    imageUrl: 'https://picsum.photos/seed/crafts4/400/300',
    origin: { country: 'ایران', city: 'یزد' },
    destination: { country: 'آمریکا', city: 'نیویورک' },
    weight: 2,
    category: 'پوشاک',
    fee: 65,
    currency: 'USD',
    datePosted: '۵ روز پیش',
  },
  {
    id: 5,
    title: 'هدیه تولد (عطر و ادکلن)',
    imageUrl: 'https://picsum.photos/seed/perfume5/400/300',
    origin: { country: 'فرانسه', city: 'پاریس' },
    destination: { country: 'ایران', city: 'تهران' },
    weight: 1,
    category: 'هدیه',
    fee: 40,
    currency: 'EUR',
    datePosted: '۱ هفته پیش',
  },
  {
    id: 6,
    title: 'قطعات یدکی خودرو',
    imageUrl: 'https://picsum.photos/seed/carparts6/400/300',
    origin: { country: 'آلمان', city: 'مونیخ' },
    destination: { country: 'ایران', city: 'تبریز' },
    weight: 8,
    category: 'قطعات',
    fee: 200,
    currency: 'EUR',
    datePosted: '۲ هفته پیش',
  }
];

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

const AcceptShipmentPage: React.FC<AcceptShipmentPageProps> = ({ onNavigate }) => {
    const [shipments, setShipments] = useState<Shipment[]>(mockShipments);
    const [filteredShipments, setFilteredShipments] = useState<Shipment[]>(mockShipments);

    // 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 = [...shipments];

        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 'fee_asc':
                result.sort((a, b) => a.fee - b.fee);
                break;
            case 'fee_desc':
                result.sort((a, b) => b.fee - a.fee);
                break;
            case 'oldest':
                result.reverse();
                break;
            case 'newest':
            default:
                break;
        }

        setFilteredShipments(result);
    }, [searchQuery, originCountry, originCity, destinationCountry, destinationCity, sortBy, shipments]);

    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>

            {/* Shipments List */}
            {filteredShipments.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredShipments.map(shipment => (
                        <ShipmentCard key={shipment.id} {...shipment} 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">
                    <PackageIcon 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 for filters
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="fee_asc">کارمزد: کم به زیاد</option>
                <option value="fee_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>
);

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

const ShipmentCard: React.FC<ShipmentCardProps> = ({ id, title, imageUrl, origin, destination, weight, category, fee, currency, 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="relative">
                <img src={imageUrl} alt={title} className="w-full h-48 object-cover" />
                 <div className="absolute top-0 right-0 m-2 px-3 py-1 bg-black/60 text-white text-xs font-bold rounded-full backdrop-blur-sm">{datePosted}</div>
                 <div className="absolute top-0 left-0 m-2 px-3 py-1 bg-custom-cyan/80 text-white text-xs font-bold rounded-full backdrop-blur-sm">{category}</div>
            </div>
            <div className="p-5 flex flex-col flex-grow">
                <h3 className="text-lg font-bold text-gray-800 dark:text-white mb-3 flex-grow">{title}</h3>
                
                <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={PackageIcon} label="مبدا" value={`${origin.city}, ${origin.country}`} />
                    <InfoRow icon={MapPinIcon} label="مقصد" value={`${destination.city}, ${destination.country}`} />
                    <InfoRow icon={ScaleIcon} label="وزن تقریبی" value={`${weight} کیلوگرم`} />
                    <InfoRow icon={DollarSignIcon} label="هزینه حمل" value={`${fee.toLocaleString()} ${currency}`} valueClassName="text-green-600 dark:text-green-400" />
                </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('shipment-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 AcceptShipmentPage;