import React, { useState, useEffect } from 'react';
import {
    ArrowRightIcon,
    PlusCircleIcon,
    ClipboardListIcon,
    PackageIcon,
    PlaneIcon,
    MapPinIcon,
    CheckCircleIcon,
    UserIcon,
    SearchIcon,
    ChevronDownIcon,
    ECommerceIcon,
    AlertCircleIcon,
    DocumentIcon
} from '../Icons';
import { API_BASE_URL } from '@/src/config.js';

// مدل یکپارچه برای همه فعالیت‌ها
interface UnifiedActivity {
    id: string;
    type: 'purchase-request' | 'purchase-offer' | 'shipment-send' | 'shipment-carry' | 'trip' | 'companion' | 'ticket';
    title: string;
    status: 'active' | 'pending' | 'answered' | 'completed' | 'closed' | 'rejected';
    time: string; // زمان نسبی
    rawDate: string; // برای مرتب‌سازی
    icon: React.FC<{ className?: string }>;
    color: 'cyan' | 'orange' | 'green' | 'purple' | 'blue' | 'gray';
    detailRoute: string;
    detailId: string;
}

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

const DashboardPage: React.FC<DashboardPageProps> = ({ onNavigate }) => {
    const [activities, setActivities] = useState<UnifiedActivity[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [typeFilter, setTypeFilter] = useState('all');
    const [statusFilter, setStatusFilter] = useState('all');

    // تابع فرمت زمان نسبی (مشترک)
    const formatDateRelative = (dateString: string): string => {
        if (!dateString) return 'تاریخ نامعلوم';
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffMins < 1) return 'الان';
        if (diffMins < 60) return `${diffMins} دقیقه پیش`;
        if (diffHours < 24) return `${diffHours} ساعت پیش`;
        if (diffDays < 7) return `${diffDays} روز پیش`;
        return new Intl.DateTimeFormat('fa-IR', { day: 'numeric', month: 'short' }).format(date);
    };

    // دریافت و یکپارچه‌سازی داده‌ها
    const fetchAllActivities = async () => {
        try {
            setLoading(true);

            // درخواست‌های موازی
            const [
                purchaseRes,
                shopperRes,
                shipmentRes,
                tripRes,
                companionRes,
                ticketRes
            ] = await Promise.all([
                fetchWithAuth(`${API_BASE_URL}/online-purchase/my-requests`),
                fetchWithAuth(`${API_BASE_URL}/online-purchase/my-shopper`),
                fetchWithAuth(`${API_BASE_URL}/shipments/my-list`),
                fetchWithAuth(`${API_BASE_URL}/trips/my-trips`),
                fetchWithAuth(`${API_BASE_URL}/trips/my-companions`),
                fetchWithAuth(`${API_BASE_URL}/tickets`)
            ]);

            const allActivities: UnifiedActivity[] = [];

            // خرید
            if (purchaseRes.ok) {
                const data = await purchaseRes.json();
                (data.data || []).forEach((req: any) => {
                    allActivities.push({
                        id: `pr-${req.id}`,
                        type: 'purchase-request',
                        title: req.title || 'درخواست خرید بدون عنوان',
                        status: req.status === 'active' ? 'active' : 'pending',
                        time: formatDateRelative(req.created_at),
                        rawDate: req.created_at,
                        icon: ECommerceIcon,
                        color: 'cyan',
                        detailRoute: 'purchase-request-detail',
                        detailId: req.id
                    });
                });
            }

            if (shopperRes.ok) {
                const data = await shopperRes.json();
                if (data.data) {
                    const s = data.data;
                    allActivities.push({
                        id: `po-${s.id}`,
                        type: 'purchase-offer',
                        title: s.service_title?.trim() || `آماده خرید از ${s.country || 'کشور نامشخص'}`,
                        status: s.status === 'active' ? 'active' : 'pending',
                        time: formatDateRelative(s.created_at || s.updated_at),
                        rawDate: s.created_at || s.updated_at,
                        icon: UserIcon,
                        color: 'orange',
                        detailRoute: 'purchase-shopper-detail',
                        detailId: s.id
                    });
                }
            }

            // مرسوله
            if (shipmentRes.ok) {
                const data = await shipmentRes.json();
                (data.data || []).forEach((s: any) => {
                    allActivities.push({
                        id: `sh-${s.id}`,
                        type: s.type === 'send' ? 'shipment-send' : 'shipment-carry',
                        title: s.title,
                        status: s.status,
                        time: formatDateRelative(s.created_at),
                        rawDate: s.created_at,
                        icon: s.type === 'send' ? PackageIcon : PlaneIcon,
                        color: s.type === 'send' ? 'cyan' : 'orange',
                        detailRoute: 'shipment-detail',
                        detailId: s.id
                    });
                });
            }

            // سفر
            if (tripRes.ok) {
                const data = await tripRes.json();
                (data.data || []).forEach((t: any) => {
                    allActivities.push({
                        id: `tr-${t.id}`,
                        type: 'trip',
                        title: `سفر از ${t.origin_city} به ${t.destination_city}`,
                        status: t.status === 'active' ? 'active' : t.status === 'completed' ? 'completed' : 'pending',
                        time: formatDateRelative(t.created_at),
                        rawDate: t.created_at,
                        icon: PlaneIcon,
                        color: 'orange',
                        detailRoute: 'trip-detail',
                        detailId: t.id
                    });
                });
            }

            if (companionRes.ok) {
                const data = await companionRes.json();
                (data.data || []).forEach((c: any) => {
                    allActivities.push({
                        id: `co-${c.id}`,
                        type: 'companion',
                        title: `همسفر: ${c.origin_city} → ${c.destination_city}`,
                        status: c.status === 'active' ? 'active' : c.status === 'completed' ? 'completed' : 'pending',
                        time: formatDateRelative(c.created_at),
                        rawDate: c.created_at,
                        icon: UserIcon,
                        color: 'cyan',
                        detailRoute: 'trip-detail',
                        detailId: c.id
                    });
                });
            }

            // تیکت
            if (ticketRes.ok) {
                const data = await ticketRes.json();
                if (Array.isArray(data.data)) {
                    const statusMap: Record<string, any> = {
                        'open': 'pending', 'pending': 'pending', 'in_progress': 'pending',
                        'answered': 'answered', 'closed': 'closed'
                    };
                    data.data.forEach((t: any) => {
                        allActivities.push({
                            id: `tk-${t.id}`,
                            type: 'ticket',
                            title: t.subject || 'بدون عنوان',
                            status: statusMap[t.status] || 'pending',
                            time: formatDateRelative(t.updated_at || t.created_at),
                            rawDate: t.updated_at || t.created_at,
                            icon: DocumentIcon,
                            color: statusMap[t.status] === 'answered' ? 'green' : statusMap[t.status] === 'closed' ? 'gray' : 'orange',
                            detailRoute: 'ticket-detail',
                            detailId: t.id
                        });
                    });
                }
            }

            // مرتب‌سازی بر اساس زمان (جدیدترین اول)
            allActivities.sort((a, b) => new Date(b.rawDate).getTime() - new Date(a.rawDate).getTime());
            setActivities(allActivities);

        } catch (err) {
            console.error('Error fetching dashboard data:', err);
        } finally {
            setLoading(false);
        }
    };

    const fetchWithAuth = (url: string) => authFetch(url); // فرض بر این است که authFetch از App.js import شده

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

   

    // مپ کردن رنگ‌ها
    const getColorClass = (color: string) => {
        const map: Record<string, string> = {
            cyan: 'text-custom-cyan bg-custom-cyan/10',
            orange: 'text-custom-orange bg-custom-orange/10',
            green: 'text-green-500 bg-green-500/10',
            purple: 'text-custom-purple bg-custom-purple/10',
            blue: 'text-blue-500 bg-blue-500/10',
            gray: 'text-gray-500 bg-gray-500/10'
        };
        return map[color] || map.cyan;
    };

    // آمار کلی
    const stats = {
        total: activities.length,
        active: activities.filter(a => a.status === 'active' || a.status === 'answered').length,
        pending: activities.filter(a => a.status === 'pending').length,
        tickets: activities.filter(a => a.type === 'ticket').length
    };

    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>

            {/* Quick Actions — همان 6 تا کارت اولیه */}
            <div className="grid grid-cols-2 lg:grid-cols-6 gap-4">
                {[
                    { icon: PlusCircleIcon, title: "ثبت مرسوله جدید", color: "purple", page: "register-shipment" },
                    { icon: ClipboardListIcon, title: "مرسوله‌های من", color: "cyan", page: "my-shipment-requests" },
                    { icon: PlusCircleIcon, title: "ثبت سفر جدید", color: "orange", page: "register-trip" },
                    { icon: ClipboardListIcon, title: "سفرهای من", color: "pink", page: "my-trips" },
                    { icon: PlusCircleIcon, title: "ثبت خرید اینترنتی", color: "green", page: "register-online-purchase" },
                    { icon: ClipboardListIcon, title: "خریدهای من", color: "blue", page: "my-purchase-requests" }
                ].map((item, i) => (
                    <ActionCard
                        key={i}
                        icon={item.icon}
                        title={item.title}
                        color={item.color as any}
                        pageId={item.page}
                        onNavigate={onNavigate}
                    />
                ))}
            </div>

            {/* آمار زنده */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <StatCard icon={CheckCircleIcon} title="فعال/پاسخ داده شده" value={stats.active} variant="green" />
                <StatCard icon={AlertCircleIcon} title="در انتظار" value={stats.pending} variant="orange" />
                <StatCard icon={DocumentIcon} title="تیکت‌های باز" value={stats.tickets} variant="blue" />
                <StatCard icon={ClipboardListIcon} title="کل فعالیت‌ها" value={stats.total} variant="purple" />
            </div>

         
        </div>
    );
};

// کامپوننت ActionCard — همان نسخه‌ی فعلی‌ات (بدون تغییر)
const ActionCard: React.FC<{
    icon: React.FC<{ className?: string }>;
    title: string;
    description?: string;
    color: 'purple' | 'cyan' | 'orange' | 'pink' | 'green' | 'blue';
    pageId: string;
    onNavigate: (page: string) => void;
}> = ({ icon: Icon, title, description, color, pageId, onNavigate }) => {
    const colors = {
        purple: 'from-custom-purple to-custom-light-purple',
        cyan: 'from-custom-cyan to-teal-400',
        orange: 'from-custom-orange to-amber-400',
        pink: 'from-custom-pink to-rose-400',
        green: 'from-green-500 to-emerald-400',
        blue: 'from-blue-500 to-sky-400'
    };
    return (
        <div 
            onClick={() => onNavigate(pageId)}
            className={`relative bg-gradient-to-br ${colors[color]} p-4 rounded-2xl text-white shadow-lg hover:shadow-xl hover:scale-[1.02] transform transition-all duration-300 cursor-pointer overflow-hidden group`}
        >
            <Icon className="absolute -right-2 -top-2 w-16 h-16 text-white/10 transform rotate-12" />
            <div className="relative z-10">
                <div className="bg-white/20 w-10 h-10 rounded-full flex items-center justify-center mb-2">
                    <Icon className="w-5 h-5" />
                </div>
                <h3 className="font-bold text-sm">{title}</h3>
                {description && <p className="opacity-80 mt-1 text-xs">{description}</p>}
            </div>
        </div>
    );
};

// کامپوننت StatCard — بهبودیافته با رنگ هوشمند
const StatCard: React.FC<{ icon: React.FC<{ className?: string }>; title: string; value: number; variant?: 'green' | 'orange' | 'blue' | 'purple' }> = ({ icon: Icon, title, value, variant = 'purple' }) => {
    const colorMap = {
        green: 'text-green-500',
        orange: 'text-custom-orange',
        blue: 'text-blue-500',
        purple: 'text-custom-purple'
    };
    return (
        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-4 rounded-2xl flex items-center">
            <div className="p-2 bg-custom-light-bg dark:bg-custom-dark-blue rounded-full ml-3">
                <Icon className={`w-5 h-5 ${colorMap[variant]}`} />
            </div>
            <div>
                <p className="text-gray-500 dark:text-gray-400 text-xs">{title}</p>
                <p className="text-xl font-bold text-gray-900 dark:text-white">{value}</p>
            </div>
        </div>
    );
};

// فرض بر این است که authFetch از جایی import شده
const authFetch = (url: string, options: any = {}) => {
    // اینجا باید همان authFetch اصلی پروژه‌تان باشد
    return fetch(url, {
        ...options,
        headers: {
            'X-Auth-Token':  localStorage.getItem('auth_token'),
            'Content-Type': 'application/json',
            ...options.headers
        }
    });
};

export default DashboardPage;