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

interface PurchaseRequest {
    id: number;
    title: string;
    imageUrl: string;
    purchaseLocation: { country: string; city: string; };
    deliveryLocation: { country: string; city: string; };
    itemPrice: number;
    proposedFee: number;
    currency: 'USD' | 'CAD' | 'IRT' | 'EUR';
    datePosted: string;
}

const mockPurchaseRequests: PurchaseRequest[] = [
  {
    id: 1,
    title: 'گوشی موبایل سامسونگ S23 Ultra',
    imageUrl: 'https://picsum.photos/seed/s23ultra/400/300',
    purchaseLocation: { country: 'آمریکا', city: 'نیویورک' },
    deliveryLocation: { country: 'ایران', city: 'تهران' },
    itemPrice: 1199,
    proposedFee: 100,
    currency: 'USD',
    datePosted: '۲ ساعت پیش',
  },
  {
    id: 2,
    title: 'کتاب Clean Architecture',
    imageUrl: 'https://picsum.photos/seed/cleanarch/400/300',
    purchaseLocation: { country: 'کانادا', city: 'تورنتو' },
    deliveryLocation: { country: 'ایران', city: 'اصفهان' },
    itemPrice: 45,
    proposedFee: 15,
    currency: 'CAD',
    datePosted: '۱ روز پیش',
  },
  {
    id: 3,
    title: 'پردازنده گرافیکی Nvidia RTX 4080',
    imageUrl: 'https://picsum.photos/seed/rtx4080/400/300',
    purchaseLocation: { country: 'آمریکا', city: 'لس آنجلس' },
    deliveryLocation: { country: 'ایران', city: 'شیراز' },
    itemPrice: 1250,
    proposedFee: 150,
    currency: 'USD',
    datePosted: '۳ روز پیش',
  },
  {
    id: 4,
    title: 'ست لگو Star Wars',
    imageUrl: 'https://picsum.photos/seed/legosw/400/300',
    purchaseLocation: { country: 'آلمان', city: 'برلین' },
    deliveryLocation: { country: 'ایران', city: 'مشهد' },
    itemPrice: 200,
    proposedFee: 40,
    currency: 'EUR',
    datePosted: '۵ روز پیش',
  },
  {
    id: 5,
    title: 'کیف دستی زنانه برند Coach',
    imageUrl: 'https://picsum.photos/seed/coachbag/400/300',
    purchaseLocation: { country: 'آمریکا', city: 'نیویورک' },
    deliveryLocation: { country: 'ایران', city: 'تهران' },
    itemPrice: 350,
    proposedFee: 60,
    currency: 'USD',
    datePosted: '۱ هفته پیش',
  },
  {
    id: 6,
    title: 'کفش ورزشی نایکی Air Jordan',
    imageUrl: 'https://picsum.photos/seed/jordans/400/300',
    purchaseLocation: { country: 'کانادا', city: 'ونکوور' },
    deliveryLocation: { country: 'ایران', city: 'تبریز' },
    itemPrice: 180,
    proposedFee: 35,
    currency: 'CAD',
    datePosted: '۲ هفته پیش',
  }
];

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

const AcceptOnlinePurchasePage: React.FC<AcceptOnlinePurchasePageProps> = ({ onNavigate }) => {
    const [requests, setRequests] = useState<PurchaseRequest[]>(mockPurchaseRequests);
    const [filteredRequests, setFilteredRequests] = useState<PurchaseRequest[]>(mockPurchaseRequests);

    // Filter states
    const [searchQuery, setSearchQuery] = useState('');
    const [purchaseCountry, setPurchaseCountry] = useState('');
    const [purchaseCity, setPurchaseCity] = useState('');
    const [deliveryCountry, setDeliveryCountry] = useState('');
    const [deliveryCity, setDeliveryCity] = useState('');
    const [sortBy, setSortBy] = useState('newest');

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

        if (searchQuery) {
            result = result.filter(req => req.title.toLowerCase().includes(searchQuery.toLowerCase()));
        }
        if (purchaseCountry) {
            result = result.filter(req => req.purchaseLocation.country.toLowerCase().includes(purchaseCountry.toLowerCase()));
        }
         if (purchaseCity) {
            result = result.filter(req => req.purchaseLocation.city.toLowerCase().includes(purchaseCity.toLowerCase()));
        }
        if (deliveryCountry) {
            result = result.filter(req => req.deliveryLocation.country.toLowerCase().includes(deliveryCountry.toLowerCase()));
        }
        if (deliveryCity) {
            result = result.filter(req => req.deliveryLocation.city.toLowerCase().includes(deliveryCity.toLowerCase()));
        }
        
        // Sort results
        switch (sortBy) {
            case 'fee_asc':
                result.sort((a, b) => a.proposedFee - b.proposedFee);
                break;
            case 'fee_desc':
                result.sort((a, b) => b.proposedFee - a.proposedFee);
                break;
            case 'oldest':
                // This is a mock sort; in a real app, you'd use timestamps
                result.reverse();
                break;
            case 'newest':
            default:
                // Default is newest, which is the initial mock data order
                break;
        }

        setFilteredRequests(result);
    }, [searchQuery, purchaseCountry, purchaseCity, deliveryCountry, deliveryCity, sortBy, requests]);

    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="purchaseCountry"
                        label="کشور خرید"
                        placeholder="مثال: آمریکا"
                        value={purchaseCountry}
                        onChange={e => setPurchaseCountry(e.target.value)}
                        icon={CrmIcon}
                    />
                     <FilterInput
                        id="purchaseCity"
                        label="شهر خرید"
                        placeholder="مثال: نیویورک"
                        value={purchaseCity}
                        onChange={e => setPurchaseCity(e.target.value)}
                        icon={MapPinIcon}
                    />
                     <FilterInput
                        id="deliveryCountry"
                        label="کشور تحویل"
                        placeholder="مثال: ایران"
                        value={deliveryCountry}
                        onChange={e => setDeliveryCountry(e.target.value)}
                        icon={CrmIcon}
                    />
                     <FilterInput
                        id="deliveryCity"
                        label="شهر تحویل"
                        placeholder="مثال: تهران"
                        value={deliveryCity}
                        onChange={e => setDeliveryCity(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>

            {/* Requests List */}
            {filteredRequests.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {filteredRequests.map(request => (
                        <PurchaseRequestCard key={request.id} {...request} 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">
                    <ECommerceIcon 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 PurchaseRequestCardProps extends PurchaseRequest {
    onNavigate: (page: string, payload?: any) => void;
}

const PurchaseRequestCard: React.FC<PurchaseRequestCardProps> = ({ id, title, imageUrl, purchaseLocation, deliveryLocation, itemPrice, proposedFee, 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>
            <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={ECommerceIcon} label="خرید از" value={`${purchaseLocation.city}, ${purchaseLocation.country}`} />
                    <InfoRow icon={MapPinIcon} label="تحویل در" value={`${deliveryLocation.city}, ${deliveryLocation.country}`} />
                    <InfoRow icon={DollarSignIcon} label="قیمت کالا" value={`${itemPrice.toLocaleString()} ${currency}`} />
                    <InfoRow icon={DollarSignIcon} label="کارمزد پیشنهادی" value={`${proposedFee.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('purchase-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 AcceptOnlinePurchasePage;