import React, { useState, useEffect } from 'react';
import { Head, router, usePage } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import DashboardLayout from '@/Layouts/DashboardLayout';
import PrintOrderModal from '@/Components/PrintOrderModal';
import OrderPayModal from '@/Components/OrderPayModal';
import { Input } from "@/Components/ui/input";
import { Button } from "@/Components/ui/button";
import { Search, Loader2, ArrowDownCircle, ShoppingBag } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

import OrderTabs from './Partials/OrderTabs';
import OrderCard from './Partials/OrderCard';

export default function BuyerOrderIndex({ initialOrders, counts, currentStatus, filters }) {
    const { t } = useTranslation();
    const { gateways = [], userCountryIso2 } = usePage().props;

    const [localOrders, setLocalOrders] = useState(initialOrders.data);
    const [nextPageUrl, setNextPageUrl] = useState(initialOrders.next_page_url);
    const [loadingMore, setLoadingMore] = useState(false);
    
    // --- State to track which specific order is currently processing ---
    const [processingId, setProcessingId] = useState(null);
    
    // --- Search State & Debounce ---
    const [searchTerm, setSearchTerm] = useState(filters?.search || '');

    useEffect(() => {
        const delay = setTimeout(() => {
            if (searchTerm !== (filters?.search || '')) {
                router.get(route('buyer.orders.index'), { status: currentStatus, search: searchTerm }, { preserveState: true, replace: true });
            }
        }, 500);
        return () => clearTimeout(delay);
    }, [searchTerm]);
    // ------------------------------------

    // Modals
    const [printModal, setPrintModal] = useState({ open: false, order: null });
    const [payModal, setPayModal] = useState({ open: false, order: null });

    useEffect(() => {
        setLocalOrders(initialOrders.data);
        setNextPageUrl(initialOrders.next_page_url);
    }, [initialOrders]);

    const changeTab = (status) => {
        router.get(route('buyer.orders.index'), { status, search: searchTerm }, { preserveState: true });
    };

    const handleLoadMore = async () => {
        if (!nextPageUrl) return;
        setLoadingMore(true);
        try {
            const res = await axios.get(nextPageUrl, { headers: { Accept: 'application/json' } });
            setLocalOrders(prev => [...prev, ...res.data.data]);
            setNextPageUrl(res.data.next_page_url);
        } catch (e) {
            toast.error(t("Failed to load more orders."));
        } finally {
            setLoadingMore(false);
        }
    };

    const updateSimpleStatus = (order, newStatus) => {
        setProcessingId(order.id); 
        // --- FIX: Form Method Spoofing to bypass ModSecurity Firewall ---
        router.post(route('buyer.orders.update', order.id), { 
            _method: 'PUT',
            status: newStatus 
        }, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(newStatus === 'completed' ? t('Order Complete!') : t('Order Cancelled.'));
                setLocalOrders(prev => prev.map(o => o.id === order.id ? { ...o, status: newStatus } : o));
            },
            onError: (err) => toast.error(err.error || t("Action failed.")),
            onFinish: () => setProcessingId(null) 
        });
    };

    const handleMessageSeller = (sellerId, productId) => {
        router.post(route('chat.start'), { 
            user_id: sellerId,
            product_id: productId 
        });
    };

    const handlePayNow = (order) => {
        setPayModal({ open: true, order });
    };

    return (
        <DashboardLayout mode="buyer">
            <Head title={t("My Orders")} />
            
            <PrintOrderModal 
                isOpen={printModal.open} 
                onClose={() => setPrintModal({ open: false, order: null })} 
                order={printModal.order} 
            />
            
            <OrderPayModal 
                isOpen={payModal.open} 
                onClose={() => setPayModal({ open: false, order: null })} 
                order={payModal.order} 
                gateways={gateways} 
                userCountryIso2={userCountryIso2} 
            />

            {/* HEADER */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">{t('My Orders')}</h2>
                    <p className="text-muted-foreground text-sm">{t('Manage your purchases and track shipments.')}</p>
                </div>
                <div className="relative w-full sm:w-[320px]">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input 
                        type="text" 
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        placeholder={t('Search ID or supplier...')} 
                        className="pl-9 bg-card rounded-xl" 
                    />
                </div>
            </div>

            {/* TABS COMPONENT */}
            <OrderTabs counts={counts} currentStatus={currentStatus} changeTab={changeTab} />

            {/* ORDERS LIST */}
            <div className="space-y-4 mt-4">
                {localOrders.map(order => (
                    <OrderCard 
                        key={order.id} 
                        order={order} 
                        setPrintModal={setPrintModal}
                        handleMessageSeller={handleMessageSeller}
                        updateSimpleStatus={updateSimpleStatus}
                        handlePayNow={handlePayNow}
                        processingId={processingId} // Pass processing state down
                    />
                ))}

                {localOrders.length === 0 && (
                    <div className="text-center py-24 border-2 border-dashed rounded-3xl text-muted-foreground bg-card">
                        <ShoppingBag className="w-16 h-16 mx-auto opacity-10 mb-4" />
                        <p className="font-bold text-lg">
                            {searchTerm ? t('No matches found.') : t('No orders found.')}
                        </p>
                    </div>
                )}
            </div>

            {/* LOAD MORE BUTTON */}
            {nextPageUrl && (
                <div className="mt-8 text-center pb-12">
                    <Button variant="outline" size="lg" className="rounded-full px-12 font-black shadow-sm bg-card hover:bg-muted" onClick={handleLoadMore} disabled={loadingMore}>
                        {loadingMore ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : <ArrowDownCircle className="w-5 h-5 mr-2" />}
                        {loadingMore ? t('Syncing...') : t('Show More')}
                    </Button>
                </div>
            )}
        </DashboardLayout>
    );
}