import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link } from '@inertiajs/react';
import { Search, ChevronLeft, ChevronRight } from 'lucide-react';
import { useState } from 'react';

interface Order {
    id: string;
    customer: string;
    email: string;
    product: string;
    amount_usd: string;
    amount_ngn: string;
    date: string;
    status: string;
}

interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

interface Props {
    orders: {
        data: Order[];
        total: number;
        links: PaginationLink[];
        current_page: number;
        last_page: number;
        prev_page_url: string | null;
        next_page_url: string | null;
    };
}

const statusStyle = (s: string) => {
    if (s === 'Paid' || s === 'completed')     return 'bg-emerald-50 text-emerald-700';
    if (s === 'Pending')  return 'bg-amber-50 text-amber-700';
    return 'bg-red-50 text-red-600';
};

export default function Index({ orders }: Props) {
    const [activeTab, setActiveTab] = useState('All');
    const tabs = ['All', 'Paid', 'Pending', 'Refunded'];

    const orderList = orders.data || [];

    const filtered = activeTab === 'All'
        ? orderList
        : orderList.filter((o) => o.status === activeTab || (activeTab === 'Paid' && o.status === 'completed'));

    const totalPaidNGN = orderList
        .filter((o) => o.status === 'Paid' || o.status === 'completed')
        .reduce((sum, o) => sum + parseInt(o.amount_ngn.replace('₦', '').replace(',', '')), 0);

    return (
        <AdminLayout>
            <Head title="Orders" />

            {/* Header */}
            <div className="mb-8">
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    Orders
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    ₦{totalPaidNGN.toLocaleString()} in paid revenue across {orders.total} orders.
                </p>
            </div>

            {/* Toolbar */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                {/* Tabs */}
                <div className="flex items-center gap-0.5 bg-[#F0EDE8] p-1 rounded-lg overflow-x-auto no-scrollbar">
                    {tabs.map((tab) => (
                        <button
                            key={tab}
                            onClick={() => setActiveTab(tab)}
                            className={`px-3.5 py-1.5 text-[11px] font-semibold rounded-md transition-all whitespace-nowrap ${
                                activeTab === tab
                                    ? 'bg-white shadow-sm text-ink'
                                    : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            {tab}
                        </button>
                    ))}
                </div>

                {/* Search */}
                <div className="relative w-full md:w-64">
                    <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#8C92AC]" />
                    <input
                        type="text"
                        placeholder="Search order ID, customer…"
                        className="pl-9 pr-4 py-2 bg-white border border-[#E8E6DF] rounded-lg text-[13px] text-ink placeholder:text-[#8C92AC] focus:outline-none focus:ring-2 focus:ring-primary/15 w-full"
                    />
                </div>
            </div>

            {/* Mobile View: Cards */}
            <div className="grid gap-2 md:hidden mb-8">
                {filtered.map((o) => (
                    <div key={o.id} className="bg-white rounded-[1.25rem] border border-[#E8E6DF] p-5 shadow-sm">
                        <div className="flex items-center justify-between mb-3">
                            <span className="text-[10px] font-bold text-[#8C92AC] tracking-wider uppercase">{o.id}</span>
                            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider ${statusStyle(o.status)}`}>
                                {o.status}
                            </span>
                        </div>
                        <div className="flex items-start justify-between gap-3">
                            <div className="flex-1 min-w-0">
                                <p className="text-[14px] font-bold text-ink leading-tight">{o.customer}</p>
                                <p className="text-[11px] text-[#8C92AC] mt-1 font-medium truncate">{o.email}</p>
                            </div>
                            <div className="text-right flex-shrink-0">
                                <p className="text-[14px] font-bold text-ink leading-tight">{o.amount_ngn}</p>
                                <p className="text-[10px] text-[#8C92AC] mt-1 font-bold uppercase tracking-tighter">{o.date}</p>
                            </div>
                        </div>
                        <div className="mt-3 pt-3 border-t border-[#F0EDE8]">
                            <p className="text-[12px] text-ink font-bold leading-tight">{o.product}</p>
                        </div>
                    </div>
                ))}
                {filtered.length === 0 && (
                    <div className="bg-white rounded-[1.25rem] border border-[#E8E6DF] p-12 text-center text-[13px] text-[#8C92AC]">
                        No orders found.
                    </div>
                )}
            </div>

            {/* Desktop View: Table */}
            <div className="hidden md:block bg-white rounded-xl border border-[#E8E6DF] overflow-hidden">
                <table className="w-full text-left border-collapse">
                    <thead>
                        <tr className="border-b border-[#F0EDE8]">
                            {['Order', 'Customer', 'Product', 'Date', 'Amount', 'Status'].map((h, i) => (
                                <th
                                    key={h}
                                    className={`px-6 py-3.5 text-[10px] font-semibold tracking-[0.14em] uppercase text-[#8C92AC] ${i >= 3 ? 'text-right' : ''}`}
                                >
                                    {h}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {filtered.map((o) => (
                            <tr
                                key={o.id}
                                className="border-b border-[#F0EDE8] last:border-0 hover:bg-[#FAFAF8] transition-colors"
                            >
                                <td className="px-6 py-4 text-[11px] text-[#8C92AC] font-medium">{o.id}</td>
                                <td className="px-6 py-4">
                                    <p className="text-[13px] font-semibold text-ink">{o.customer}</p>
                                    <p className="text-[11px] text-[#8C92AC] mt-0.5">{o.email}</p>
                                </td>
                                <td className="px-6 py-4 text-[13px] text-ink">{o.product}</td>
                                <td className="px-6 py-4 text-right text-[12px] text-primary/70">{o.date}</td>
                                <td className="px-6 py-4 text-right">
                                    <p className="text-[13px] font-semibold text-ink">{o.amount_usd}</p>
                                    <p className="text-[10px] text-[#8C92AC] mt-0.5">{o.amount_ngn}</p>
                                </td>
                                <td className="px-6 py-4 text-right">
                                    <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[10px] font-semibold uppercase tracking-wider ${statusStyle(o.status)}`}>
                                        {o.status}
                                    </span>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                {filtered.length === 0 && (
                    <div className="px-6 py-16 text-center text-[13px] text-[#8C92AC]">
                        No orders found.
                    </div>
                )}
            </div>

            {/* Pagination */}
            {orders.last_page > 1 && (
                <div className="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                    <p className="text-[11px] text-[#8C92AC] font-medium">
                        Showing page {orders.current_page} of {orders.last_page}
                    </p>
                    <div className="flex items-center gap-1.5">
                        {orders.links.map((link, i) => {
                            // Only show Prev, Next and numbered links
                            const isPrev = i === 0;
                            const isNext = i === orders.links.length - 1;
                            
                            if (isPrev) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronLeft className="h-4 w-4" />
                                    </Link>
                                );
                            }
                            
                            if (isNext) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`p-2 rounded-lg border border-[#E8E6DF] transition-all ${!link.url ? 'opacity-30 cursor-not-allowed' : 'bg-white hover:bg-[#FAFAF8] text-ink'}`}
                                    >
                                        <ChevronRight className="h-4 w-4" />
                                    </Link>
                                );
                            }

                            // Show current, first, last, and pages around current
                            const isCurrent = link.active;
                            const pageNum = parseInt(link.label);
                            const isNear = Math.abs(pageNum - orders.current_page) <= 1;
                            const isEdge = pageNum === 1 || pageNum === orders.last_page;

                            if (isCurrent || isNear || isEdge) {
                                return (
                                    <Link
                                        key={i}
                                        href={link.url || '#'}
                                        className={`min-w-[36px] h-[36px] flex items-center justify-center rounded-lg border text-[12px] font-semibold transition-all ${
                                            link.active
                                                ? 'bg-primary border-primary text-white'
                                                : 'bg-white border-[#E8E6DF] text-ink hover:bg-[#FAFAF8]'
                                        }`}
                                        dangerouslySetInnerHTML={{ __html: link.label }}
                                    />
                                );
                            }
                            
                            // Show ellipsis for gaps
                            if (pageNum === orders.current_page - 2 || pageNum === orders.current_page + 2) {
                                return <span key={i} className="px-1 text-[#8C92AC]">...</span>;
                            }

                            return null;
                        })}
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}
