import React from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link } from '@inertiajs/react';
import { 
    CurrencyDollarIcon, 
    ShoppingBagIcon, 
    CalculatorIcon, 
    ClockIcon,
    EyeIcon,
    PencilIcon,
    TrashIcon,
    MagnifyingGlassIcon,
    FunnelIcon,
    ArrowPathIcon,
    CreditCardIcon
} from '@heroicons/react/24/outline';

// --- Helper function to calculate analytics ---
const getAnalytics = (orders) => {
    const totalOrders = orders.length;
    const totalRevenue = orders.reduce((sum, order) => sum + parseFloat(order.total_amount || 0), 0);
    const averageOrderValue = totalOrders > 0 ? (totalRevenue / totalOrders) : 0;

    return { 
        totalOrders, 
        totalRevenue: totalRevenue.toFixed(2), 
        averageOrderValue: averageOrderValue.toFixed(2), 
        pendingOrders 
    };
};

// --- Sub-Component: Analytics Card (Improved Color Palette) ---
const AnalyticsCard = ({ title, value, icon, color }) => {
    return (
        <div className="bg-white overflow-hidden shadow-lg rounded-xl transition-all duration-300 hover:shadow-2xl border border-gray-200">
            <div className="p-5 flex items-start justify-between">
                <div className="w-0 flex-1">
                    <dt className="text-sm font-medium text-gray-500 truncate uppercase tracking-wide">{title}</dt>
                    <dd className="mt-1 text-3xl font-extrabold text-gray-900">{value}</dd>
                </div>
                <div className={`flex-shrink-0 p-3 rounded-full ${color.bg} shadow-lg`}>
                    {React.cloneElement(icon, { className: 'h-6 w-6 text-white', 'aria-hidden': 'true' })}
                </div>
            </div>
        </div>
    );
};

// --- Sub-Component: Order Status Badge ---
const OrderStatusBadge = ({ status }) => {
    const statusText = status ? status.toLowerCase() : 'unknown';
    const statusStyles = {
        pending: 'bg-yellow-100 text-yellow-800 ring-yellow-500/10',
        completed: 'bg-emerald-100 text-emerald-800 ring-emerald-500/10',
        cancelled: 'bg-red-100 text-red-800 ring-red-500/10',
        processing: 'bg-blue-100 text-blue-800 ring-blue-500/10',
        refunded: 'bg-pink-100 text-pink-800 ring-pink-500/10',
        unknown: 'bg-gray-100 text-gray-800 ring-gray-500/10',
    };
    const style = statusStyles[statusText] || statusStyles.unknown;
    return <span className={`inline-flex items-center px-3 py-0.5 text-xs font-medium rounded-full ring-1 ring-inset ${style}`}>{status}</span>;
};


export default function Index({ auth, orders, serviceBookings, eventBookings, filters }) { // Added 'filters' prop for completeness
    const analytics = getAnalytics(orders.data);
    
    // Define better card colors
    const cardColors = {
        revenue: { bg: 'bg-emerald-500' },
        orders: { bg: 'bg-blue-500' },
        aov: { bg: 'bg-indigo-500' },
        pending: { bg: 'bg-yellow-500' },
    };

    // Dummy search state for demonstration
    const [searchTerm, setSearchTerm] = React.useState(filters?.search || '');
    const [statusFilter, setStatusFilter] = React.useState(filters?.status || '');
    
    const handleSearch = (e) => {
        e.preventDefault();
        // In a real Inertia app, you'd make a GET request here
        // router.get(route('admin.orders.index'), { search: searchTerm, status: statusFilter }, { preserveState: true });
        console.log('Searching for:', searchTerm, 'with status:', statusFilter);
    };

    return (
        <AdminLayout
            user={auth.user}
            header={
                <div>
                    <h2 className="font-extrabold text-3xl text-gray-900 leading-tight">Sales & Orders Overview 🛍️</h2>
                    <p className="mt-1 text-sm text-gray-600">Monitor your transaction metrics and manage customer fulfillment pipelines.</p>
                </div>
            }
        >
            <Head title="Orders Dashboard" />

            <div className="py-8">
                <div className="mx-auto sm:px-6 lg:px-8">
                    
                    {/* --- Analytics Section --- */}
                    <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4 mb-8">
                        <AnalyticsCard
                            title="Total Revenue"
                            value={`GH₵${analytics.totalRevenue.toLocaleString()}`}
                            icon={<CurrencyDollarIcon />}
                            color={cardColors.revenue}
                        />
                        <AnalyticsCard
                            title="Total Orders"
                            value={analytics.totalOrders.toLocaleString()}
                            icon={<ShoppingBagIcon />}
                            color={cardColors.orders}
                        />
                        <AnalyticsCard
                            title="Avg. Order Value"
                            value={`GH₵${analytics.averageOrderValue}`}
                            icon={<CalculatorIcon />}
                            color={cardColors.aov}
                        />
                        <AnalyticsCard
                            title="Pending Orders"
                            value={analytics.pendingOrders.toLocaleString()}
                            icon={<ClockIcon />}
                            color={cardColors.pending}
                        />
                    </div>
                    
                    {/* --- Orders List & Search/Filter Section --- */}
                    <div className="bg-white shadow-xl rounded-xl overflow-hidden">
                        
                        {/* Header with Search and Filter */}
                        <div className="p-6 border-b border-gray-200 flex flex-col md:flex-row md:items-center justify-between space-y-4 md:space-y-0">
                            <h3 className="text-xl font-semibold text-gray-900">Order History</h3>
                            <form onSubmit={handleSearch} className="flex space-x-3">
                                <div className="relative">
                                    <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder="Search by ID or Customer Name..."
                                        value={searchTerm}
                                        onChange={(e) => setSearchTerm(e.target.value)}
                                        className="w-full md:w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 text-sm"
                                    />
                                </div>
                                <div className="relative">
                                    <FunnelIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                                    <select
                                        value={statusFilter}
                                        onChange={(e) => setStatusFilter(e.target.value)}
                                        className="w-32 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 text-sm"
                                    >
                                        <option value="">All Statuses</option>
                                        <option value="pending">Pending</option>
                                        <option value="processing">Processing</option>
                                        <option value="completed">Completed</option>
                                        <option value="cancelled">Cancelled</option>
                                    </select>
                                </div>
                                <button type="submit" className="px-4 py-2 bg-emerald-600 text-white font-medium rounded-lg hover:bg-emerald-700 transition-colors text-sm">
                                    <ArrowPathIcon className="h-4 w-4 inline mr-1" />
                                    Filter
                                </button>
                            </form>
                        </div>
                        
                        {/* Order Table View */}
                        {orders.data.length > 0 ? (
                            <div className="overflow-x-auto">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Order ID</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Customer</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                                            <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {orders.data.map((order) => (
                                            <tr key={order.id} className="hover:bg-emerald-50/50 transition-colors duration-150">
                                                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-emerald-600">#{order.id}</td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                    {order.user ? order.user.name : <span className="text-gray-500 italic">Guest</span>}
                                                    <p className="text-xs text-gray-400">{order.user ? order.user.email : ''}</p>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-lg font-bold text-gray-900">
                                                    ${parseFloat(order.total_amount).toFixed(2)}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <OrderStatusBadge status={order.status} />
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                                    {new Date(order.order_date).toLocaleDateString()}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                                    <div className="flex justify-center space-x-2">
                                                        {/* View */}
                                                        <Link
                                                            href={route('admin.orders.show', order.id)}
                                                            title={`View Order #${order.id}`}
                                                            className="text-gray-500 hover:text-emerald-600 p-1 rounded-full hover:bg-emerald-50"
                                                        >
                                                            <EyeIcon className="h-5 w-5" />
                                                        </Link>
                                                        {/* Edit */}
                                                        <Link
                                                            href={route('admin.orders.edit', order.id)}
                                                            title={`Edit Order #${order.id}`}
                                                            className="text-gray-500 hover:text-blue-600 p-1 rounded-full hover:bg-blue-50"
                                                        >
                                                            <PencilIcon className="h-5 w-5" />
                                                        </Link>
                                                        {/* Delete (using button for visual) */}
                                                        <button
                                                            onClick={() => { /* Implement Inertia delete */ }}
                                                            title={`Delete Order #${order.id}`}
                                                            className="text-gray-500 hover:text-red-600 p-1 rounded-full hover:bg-red-50"
                                                        >
                                                            <TrashIcon className="h-5 w-5" />
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        ) : (
                            // Beautiful Empty State
                            <div className="text-center py-16 border-t border-gray-200">
                                <ShoppingBagIcon className="mx-auto h-16 w-16 text-gray-400/50" />
                                <h3 className="mt-4 text-lg font-medium text-gray-900">No Orders Found</h3>
                                <p className="mt-1 text-sm text-gray-500">Try adjusting your filters or check back later.</p>
                            </div>
                        )}
                        
                    </div>

                    {/* --- Pagination --- */}
                    {orders.links && orders.links.length > 3 && (
                        <div className="mt-8 flex justify-end">
                            {orders.links.map((link, key) => (
                                <Link
                                    key={key}
                                    href={link.url || '#'}
                                    className={`ml-1 px-4 py-2 text-sm leading-4 border rounded-lg transition-colors duration-150 ${
                                        link.active
                                            ? 'bg-emerald-600 text-white border-emerald-600 font-semibold shadow-md'
                                            : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                                    } ${!link.url ? 'opacity-50 cursor-not-allowed' : ''}`}
                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                />
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </AdminLayout>
    );
}