import React, { useState, useEffect } from 'react';
import { SearchIcon, ChevronDownIcon, MapPinIcon, DollarSignIcon, ClockIcon, ECommerceIcon, UserIcon, XIcon } from '../Icons';
import { authFetch } from '../../App';
import ConfirmDeleteModal from "../ConfirmDeleteModal";
import { API_BASE_URL } from '@/src/config.js';
// انواع داده برای نمایش در لیست
interface PurchaseRequestItem {
    id: string;
    type: 'request';
    title: string;
    requestDate: string;
    status: 'pending' | 'active' | 'rejected';
    fee: string;
    currency: string;
    location: string;
    imageUrl?: string;
}

interface ShopperItem {
    id: string;
    type: 'offer';
    title: string;
    requestDate: string;
    status: 'pending' | 'active' | 'rejected';
    fee: string;
    currency: '';
    shopperLocation: string;
    imageUrl?: string;
}

type ListItem = PurchaseRequestItem | ShopperItem;

interface MyPurchaseRequestsPageProps {
    onNavigate: (page: string, payload?: any, options?: { isOwnerView?: boolean }) => void;
    showSuccess: (message: string) => void;
    showError: (message: string) => void;
}

const MyPurchaseRequestsPage: React.FC<MyPurchaseRequestsPageProps> = ({ onNavigate, showSuccess, showError }) => {
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');
    const [listItems, setListItems] = useState<ListItem[]>([]);
    const [filteredItems, setFilteredItems] = useState<ListItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [deletingId, setDeletingId] = useState<string | null>(null);

    // State برای مدال حذف
    const [deleteModal, setDeleteModal] = useState<{ open: boolean; item: ListItem | null }>({
        open: false,
        item: null
    });

    const formatDate = (dateString: string): string => {
        if (!dateString) return 'تاریخ نامعلوم';

        const date = new Date(dateString);
        const now = new Date();
        const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60));

        if (diffInHours < 1) return 'چند دقیقه پیش';
        if (diffInHours < 24) return `${diffInHours} ساعت پیش`;
        if (diffInHours < 168) return `${Math.floor(diffInHours / 24)} روز پیش`;
        return `${Math.floor(diffInHours / 168)} هفته پیش`;
    };

    const fetchData = async () => {
        try {
            setLoading(true);
            setError(null);

            // درخواست‌های خرید
            const requestsRes = await authFetch(`${API_BASE_URL}/online-purchase/my-requests`);
           // if (!requestsRes.ok) throw new Error('خطا در دریافت درخواست‌ها');
            const requestsData = (await requestsRes.json()).data || [];

            // پروفایل خریدار
            const shopperRes = await authFetch(`${API_BASE_URL}/online-purchase/my-shopper`);
            if (!shopperRes.ok) throw new Error('خطا در دریافت پروفایل خریدار');
            const shopperResult = await shopperRes.json();
            const shopperData = shopperResult.data;

            // تبدیل درخواست‌های خرید
            const requestItems: PurchaseRequestItem[] = requestsData.map((req: any) => ({
                id: req.id.toString(),
                type: 'request',
                title: req.title || 'بدون عنوان',
                requestDate: formatDate(req.created_at),
                status: req.status === 'active' ? 'active' : 'pending',
                fee: req.proposed_fee?.toString() || '0',
                currency: req.currency || 'IRT',
                location: [req.delivery_city, req.delivery_country].filter(Boolean).join('، ') || '—',
                imageUrl: req.images?.[0]?.url ||
                    (req.images?.[0]?.path ? `https://eino.eifa.site/users-api/public/${req.images[0].path}` : undefined),
            }));

            // تبدیل پروفایل خریدار
            const shopperItems: ShopperItem[] = [];
            if (shopperData && shopperData.id) {
                const title = shopperData.service_title?.trim()
                    ? shopperData.service_title.trim()
                    : `آماده خرید از ${shopperData.country || 'کشور نامشخص'}`;

                shopperItems.push({
                    id: shopperData.id.toString(),
                    type: 'offer',
                    title,
                    requestDate: formatDate(shopperData.created_at || shopperData.updated_at),
                    status: shopperData.status === 'active' ? 'active' : 'pending',
                    fee: shopperData.fee_description?.trim() || 'توافقی',
                    currency: '',
                    shopperLocation: [
                        shopperData.city?.trim(),
                        shopperData.country?.trim()
                    ].filter(Boolean).join('، ') || '—',

                    imageUrl: shopperData.images?.[0]?.url
                    
                });
            }

            setListItems([...requestItems, ...shopperItems]);
        } catch (err: any) {
            console.error('خطا در دریافت داده‌ها:', err);
            setError(err.message || 'خطا در بارگذاری اطلاعات');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    // فیلتر کردن
    useEffect(() => {
        const lowercasedQuery = searchQuery.toLowerCase();
        const result = listItems.filter(item => {
            const matchesSearch = item.title.toLowerCase().includes(lowercasedQuery);
            const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
            const matchesType = typeFilter === 'all' || item.type === typeFilter;
            return matchesSearch && matchesStatus && matchesType;
        });
        setFilteredItems(result);
    }, [searchQuery, statusFilter, typeFilter, listItems]);

    // باز کردن مدال حذف
    const handleDeleteClick = (item: ListItem) => {
        console.log('🔴 DELETE CLICKED:', item);
        setDeleteModal({ open: true, item });
    };

    // بستن مدال حذف
    const handleCancelDelete = () => {
        setDeleteModal({ open: false, item: null});
    };

    // تأیید حذف
    const handleConfirmDelete = async () => {
        const itemToDelete = deleteModal.item;
        if (!itemToDelete) return;

        setDeletingId(itemToDelete.id);

        try {
            const endpoint = itemToDelete.type === 'request'
                ? `online-purchase/request/${itemToDelete.id}`
                : `online-purchase/shopper/${itemToDelete.id}`;

            const response = await authFetch(`${API_BASE_URL}/${endpoint}`, {
                method: 'DELETE',
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'خطا در حذف');
            }

            showSuccess(itemToDelete.type === 'request' ? 'درخواست خرید با موفقیت حذف شد' : 'پروفایل خریدار با موفقیت حذف شد');

            // حذف از لیست محلی
            setListItems(prev => prev.filter(i => i.id !== itemToDelete.id));

            // بستن مدال
            setDeleteModal({ open: false, item: null });

        } catch (err: any) {
            showError(err.message || 'خطا در حذف آیتم');
        } finally {
            setDeletingId(null);
        }
    };

    // تابع مشاهده جزئیات
    const handleViewDetails = (item: ListItem) => {
        if (item.type === 'request') {
            onNavigate('purchase-request-detail', item.id, { isOwnerView: true });
        } else {
            onNavigate('purchase-shopper-detail', item.id, { isOwnerView: true });
        }
    };

    if (loading) {
        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>
                <div className="flex justify-center items-center py-12">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-custom-purple"></div>
                </div>
            </div>
        );
    }

    if (error) {
        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>
                <div className="text-center py-12 bg-custom-light-card dark:bg-custom-dark-blue-light rounded-2xl">
                    <div className="text-red-500 mb-4 text-4xl">⚠️</div>
                    <h3 className="text-xl font-semibold text-red-600 dark:text-red-400 mb-2">خطا در بارگذاری</h3>
                    <p className="text-red-500 dark:text-red-300 mb-4">{error}</p>
                    <button
                        onClick={fetchData}
                        className="bg-custom-purple hover:bg-custom-light-purple text-white px-6 py-2 rounded-lg transition-colors"
                    >
                        تلاش مجدد
                    </button>
                </div>
            </div>
        );
    }

    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>

            {/* فیلترها */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                <div className="w-full grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="relative">
                        <input
                            type="text"
                            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={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                        <SearchIcon className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                    </div>
                    <div className="relative">
                        <select
                            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={statusFilter}
                            onChange={(e) => setStatusFilter(e.target.value)}
                        >
                            <option value="all">همه وضعیت‌ها</option>
                            <option value="active">فعال</option>
                            <option value="pending">در حال بررسی</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 className="relative">
                        <select
                            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={typeFilter}
                            onChange={(e) => setTypeFilter(e.target.value)}
                        >
                            <option value="all">همه انواع</option>
                            <option value="request">درخواست خرید</option>
                            <option value="offer">قبول کردن خرید</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>
            </div>

            {/* آمار کلی */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">کل فعالیت‌ها</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">{listItems.length}</p>
                        </div>
                        <ECommerceIcon className="w-8 h-8 text-custom-purple" />
                    </div>
                </div>
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">درخواست‌های خرید</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">
                                {listItems.filter(item => item.type === 'request').length}
                            </p>
                        </div>
                        <ECommerceIcon className="w-8 h-8 text-custom-cyan" />
                    </div>
                </div>
                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl shadow-sm">
                    <div className="flex items-center justify-between">
                        <div>
                            <p className="text-sm text-gray-500 dark:text-gray-400">پروفایل خریدار</p>
                            <p className="text-2xl font-bold text-gray-800 dark:text-white">
                                {listItems.filter(item => item.type === 'offer').length}
                            </p>
                        </div>
                        <UserIcon className="w-8 h-8 text-custom-orange" />
                    </div>
                </div>
            </div>

            {/* لیست آیتم‌ها */}
            <div className="space-y-6">
                {filteredItems.length > 0 ? (
                    filteredItems.map(item => (
                        <RequestCard
                            key={`${item.type}-${item.id}`}
                            item={item}
                            onViewDetails={handleViewDetails}
                            onDelete={handleDeleteClick}
                            isDeleting={deletingId === item.id}
                        />
                    ))
                ) : (
                    <div className="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">
                            {listItems.length === 0
                                ? 'شما هنوز درخواست یا پروفایل خریداری ثبت نکرده‌اید.'
                                : 'هیچ فعالیتی با این مشخصات یافت نشد.'
                            }
                        </p>
                        {listItems.length === 0 && (
                            <button
                                onClick={() => onNavigate('register-online-purchase')}
                                className="mt-4 bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2 px-6 rounded-lg transition-colors duration-300"
                            >
                                ثبت اولین فعالیت
                            </button>
                        )}
                    </div>
                )}
            </div>

            {/* در انتهای کامپوننت MyPurchaseRequestsPage */}
            <ConfirmDeleteModal
                open={deleteModal.open}
                title={
                    deleteModal.item?.type === 'request'
                        ? 'حذف درخواست خرید'
                        : 'حذف پروفایل خریدار'
                }
                message={
                    deleteModal.item
                        ? `آیا از حذف "${deleteModal.item.title}" مطمئن هستید؟ این عملیات غیرقابل بازگشت است.`
                        : 'آیا مطمئن هستید؟'
                }
                onCancel={handleCancelDelete}
                onConfirm={handleConfirmDelete}
            />

        </div>
    );
};

// کامپوننت کارت
interface RequestCardProps {
    item: ListItem;
    onViewDetails: (item: ListItem) => void;
    onDelete: (item: ListItem) => void;
    isDeleting: boolean;
}

const RequestCard: React.FC<RequestCardProps> = ({ item, onViewDetails, onDelete, isDeleting }) => {
    const isRequest = item.type === 'request';

    const getStatusChip = () => {
        switch (item.status) {
            case 'active':
                return <span className="px-3 py-1 text-xs font-bold rounded-full bg-green-500/10 text-green-500">فعال</span>;
            case 'pending':
                return <span className="px-3 py-1 text-xs font-bold rounded-full bg-custom-orange/10 text-custom-orange">در حال بررسی</span>;
            case 'rejected':
                return <span className="px-3 py-1 text-xs font-bold rounded-full bg-red-500/10 text-red-500">رد شده</span>;
            default:
                return <span className="px-3 py-1 text-xs font-bold rounded-full bg-gray-500/10 text-gray-500">{item.status}</span>;
        }
    };

    return (
        <div className="flex flex-col md:flex-row md:items-center gap-6 bg-custom-light-card dark:bg-custom-dark-blue-light p-5 rounded-2xl shadow-sm border border-transparent hover:border-custom-purple/50 hover:shadow-lg transition-all duration-300">
            {/* تصویر */}
            <div className="flex-shrink-0 w-full md:w-32 h-32">
                
                {item.imageUrl ? (
                    <img
                        src={item.imageUrl}
                        alt={item.title}
                        className="w-full h-full object-cover rounded-xl"
                        onError={(e) => {
                            const parent = e.currentTarget.parentElement;
                            if (parent) {
                                parent.innerHTML = `
                                    <div class="w-full h-full bg-custom-light-bg dark:bg-custom-dark-blue rounded-xl flex items-center justify-center">
                                        <svg class="w-16 h-16 text-custom-purple/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                                        </svg>
                                    </div>
                                `;
                            }
                        }}
                    />
                ) : (
                    <div className="w-full h-full bg-custom-light-bg dark:bg-custom-dark-blue rounded-xl flex items-center justify-center">
                        {isRequest ?
                            <ECommerceIcon className="w-16 h-16 text-custom-purple/50" /> :
                            <UserIcon className="w-16 h-16 text-custom-purple/50" />
                        }
                    </div>
                )}
            </div>

            {/* محتوا */}
            <div className="flex flex-col flex-grow w-full">
                <div className="flex justify-between items-start mb-3">
                    <div>
                        <div className={`flex items-center gap-2 mb-1 ${isRequest ? 'text-custom-cyan' : 'text-custom-orange'}`}>
                            {isRequest ? <ECommerceIcon className="w-5 h-5" /> : <UserIcon className="w-5 h-5" />}
                            <span className="text-sm font-semibold">
                                {isRequest ? 'درخواست خرید' : 'قبول کردن خرید'}
                            </span>
                        </div>
                        <h3 className="text-lg font-bold text-gray-800 dark:text-white">{item.title}</h3>
                    </div>
                    <div className="flex-shrink-0">
                        {getStatusChip()}
                    </div>
                </div>

                {/* اطلاعات */}
                <div className="flex-grow space-y-2 text-sm text-gray-600 dark:text-gray-300 border-t border-gray-200 dark:border-gray-700 pt-3">
                    <InfoRow icon={ClockIcon} label="تاریخ ثبت" value={item.requestDate} />
                    <InfoRow
                        icon={DollarSignIcon}
                        label={isRequest ? "هزینه پیشنهادی" : "شرایط کارمزد"}
                        value={`${item.fee} ${item.currency}`.trim()}
                        valueClassName={isRequest ? 'text-green-600 dark:text-green-400' : 'text-gray-800 dark:text-gray-200'}
                    />
                    <InfoRow
                        icon={MapPinIcon}
                        label={isRequest ? "محل تحویل" : "محل فعالیت"}
                        value={isRequest ? item.location : (item as ShopperItem).shopperLocation}
                    />
                </div>

                {/* دکمه‌های عمل */}
                <div className="mt-4 flex items-center justify-end gap-3">
                    <button
                        onClick={() => onDelete(item)}
                        disabled={isDeleting}
                        className="flex items-center gap-2 bg-red-500 hover:bg-red-600 disabled:bg-gray-400 text-white font-bold py-2 px-4 rounded-lg transition-colors duration-300 text-sm"
                    >
                        {isDeleting ? (
                            <>
                                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                <span>در حال حذف...</span>
                            </>
                        ) : (
                            <>
                                <XIcon className="w-4 h-4" />
                                <span>حذف</span>
                            </>
                        )}
                    </button>
                    <button
                        onClick={() => onViewDetails(item)}
                        className="bg-custom-purple hover:bg-custom-light-purple text-white font-bold py-2 px-6 rounded-lg transition-colors duration-300 text-sm"
                    >
                        مشاهده جزئیات
                    </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 MyPurchaseRequestsPage;
