import React, { useState, useEffect } from 'react';
import { SearchIcon, ChevronDownIcon, MapPinIcon, ClockIcon, PackageIcon, PlaneIcon, ScaleIcon, DollarSignIcon, XIcon } from '../Icons';
import { authFetch } from '../../App';
import ConfirmDeleteModal from "../ConfirmDeleteModal";
import { API_BASE_URL } from '@/src/config.js';
interface ShipmentItem {
    id: string;
    type: 'send' | 'carry';
    title: string;
    status: 'active' | 'pending' | 'rejected';
    origin_country: string;
    origin_city: string;
    destination_country: string;
    destination_city: string;
    weight?: number;
    carry_weight_capacity?: number;
    price_type: 'fixed' | 'negotiable';
    currency?: string;
    amount?: number;
    departure_date?: string;
    arrival_date?: string;
    created_at: string;
    images: { id: number; url: string }[];
}

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

const MyShipmentRequestsPage: React.FC<MyShipmentRequestsPageProps> = ({ onNavigate, showSuccess, showError }) => {
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');
    const [shipments, setShipments] = useState<ShipmentItem[]>([]);
    const [filteredShipments, setFilteredShipments] = useState<ShipmentItem[]>([]);
    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: ShipmentItem | 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)} هفته پیش`;
    };

    // دریافت داده‌ها از API
    const fetchData = async () => {
        try {
            setLoading(true);
            setError(null);

            const response = await authFetch(`${API_BASE_URL}/shipments/my-list`);

            if (!response.ok) {
                throw new Error('خطا در دریافت لیست مرسوله‌ها');
            }

            const result = await response.json();
            setShipments(result.data || []);

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

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

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

    // تابع باز کردن مدال حذف
    const handleDeleteClick = (item: ShipmentItem) => {
        setDeleteModal({ open: true, item });
    };

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

        const itemToDelete = deleteModal.item;
        setDeletingId(itemToDelete.id);
        setDeleteModal({ open: false, item: null });

        try {
            const response = await authFetch(`${API_BASE_URL}/shipments/${itemToDelete.id}`, {
                method: 'DELETE',
            });

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

            showSuccess('مرسوله با موفقیت حذف شد');
            // به‌روزرسانی لیست
            setShipments(prev => prev.filter(s => s.id !== itemToDelete.id));

        } catch (err: any) {
            showError(err.message || 'خطا در حذف مرسوله');
        } finally {
            setDeletingId(null);
        }
    };

    // تابع لغو حذف
    const handleCancelDelete = () => {
        setDeleteModal({ open: false, item: null });
    };

    // تابع مشاهده جزئیات
    const handleViewDetails = (item: ShipmentItem) => {
        onNavigate('shipment-detail', item.id, { isOwnerView: true });
    };

    // Loading State
    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>
        );
    }

    // Error State
    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>
                            <option value="rejected">رد شده</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="send">ارسال مرسوله</option>
                            <option value="carry">حمل مرسوله (سفر)</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">{shipments.length}</p>
                        </div>
                        <PackageIcon 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">
                                {shipments.filter(s => s.type === 'send').length}
                            </p>
                        </div>
                        <PackageIcon 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">
                                {shipments.filter(s => s.type === 'carry').length}
                            </p>
                        </div>
                        <PlaneIcon className="w-8 h-8 text-custom-orange" />
                    </div>
                </div>
            </div>

            {/* لیست آیتم‌ها */}
            <div className="space-y-6">
                {filteredShipments.length > 0 ? (
                    filteredShipments.map(item => (
                        <ShipmentCard
                            key={item.id}
                            item={item}
                            formatDate={formatDate}
                            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">
                        <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">
                            {shipments.length === 0
                                ? 'شما هنوز مرسوله یا سفری ثبت نکرده‌اید.'
                                : 'هیچ مرسوله‌ای با این مشخصات یافت نشد.'
                            }
                        </p>
                        {shipments.length === 0 && (
                            <button
                                onClick={() => onNavigate('register-shipment')}
                                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>

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


// کامپوننت کارت مرسوله
interface ShipmentCardProps {
    item: ShipmentItem;
    formatDate: (date: string) => string;
    onViewDetails: (item: ShipmentItem) => void;
    onDelete: (item: ShipmentItem) => void;
    isDeleting: boolean;
}

const ShipmentCard: React.FC<ShipmentCardProps> = ({ item, formatDate, onViewDetails, onDelete, isDeleting }) => {
    const isSend = item.type === 'send';

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

    const getOrigin = () => [item.origin_city, item.origin_country].filter(Boolean).join('، ') || '—';
    const getDestination = () => [item.destination_city, item.destination_country].filter(Boolean).join('، ') || '—';

    const getPrice = () => {
        if (item.price_type === 'negotiable') return 'توافقی';
        if (item.amount && item.currency) {
            const currencyLabels: Record<string, string> = { IRT: 'تومان', USD: 'دلار', CAD: 'دلار کانادا', IQD: 'دینار' };
            return `${item.amount} ${currencyLabels[item.currency] || item.currency}`;
        }
        return '—';
    };

    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">
                {isSend && item.images && item.images.length > 0 ? (
                    <img
                        src={item.images[0].url}
                        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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></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">
                        {isSend ?
                            <PackageIcon className="w-16 h-16 text-custom-purple/50" /> :
                            <PlaneIcon 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 ${isSend ? 'text-custom-cyan' : 'text-custom-orange'}`}>
                            {isSend ? <PackageIcon className="w-5 h-5" /> : <PlaneIcon className="w-5 h-5" />}
                            <span className="text-sm font-semibold">
                                {isSend ? 'ارسال مرسوله' : 'حمل مرسوله (سفر)'}
                            </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={formatDate(item.created_at)} />
                    <InfoRow icon={MapPinIcon} label="مبدأ" value={getOrigin()} />
                    <InfoRow icon={MapPinIcon} label="مقصد" value={getDestination()} />
                    {isSend ? (
                        <InfoRow icon={ScaleIcon} label="وزن" value={item.weight ? `${item.weight} کیلوگرم` : '—'} />
                    ) : (
                        <InfoRow icon={ScaleIcon} label="ظرفیت حمل" value={item.carry_weight_capacity ? `${item.carry_weight_capacity} کیلوگرم` : '—'} />
                    )}
                    <InfoRow
                        icon={DollarSignIcon}
                        label="قیمت"
                        value={getPrice()}
                        valueClassName="text-green-600 dark:text-green-400"
                    />
                </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 MyShipmentRequestsPage;
