import { Head, Link } from '@inertiajs/react';
import { CheckCircle2, Clock, GraduationCap, Receipt, XCircle, ChevronRight, Calendar } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';

type OrderItem = {
    id: number;
    price: number;
    course: { id: number; title: string; slug: string; thumbnail: string | null };
};

type Order = {
    id: number;
    total_amount: number;
    status: 'pending' | 'approved' | 'rejected';
    admin_notes: string | null;
    created_at: string;
    approved_at: string | null;
    items: OrderItem[];
};

type Props = { orders: Order[] };

const BRAND = '#118AB2';

function formatPrice(price: number) {
    return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(price);
}

const STATUS_CONFIG = {
    pending: { 
        label: 'Menunggu Verifikasi',  
        icon: Clock,         
        color: '#D97706', 
        bg: '#FEF3C7',    
        accent: '#F59E0B'
    },
    approved: { 
        label: 'Pembayaran Disetujui', 
        icon: CheckCircle2,  
        color: '#059669', 
        bg: '#D1FAE5',    
        accent: '#10B981'
    },
    rejected: { 
        label: 'Pembayaran Ditolak',   
        icon: XCircle,       
        color: '#DC2626', 
        bg: '#FEE2E2',    
        accent: '#EF4444'
    },
};

export default function OrdersIndex({ orders }: Props) {
    return (
        <>
            <Head title="Riwayat Pembelian – Pakandi" />

            <div className="mx-auto max-w-4xl px-4 py-8 sm:px-6 lg:px-8">
                {/* Header */}
                <div className="mb-8">
                    <h1 className="text-3xl font-extrabold tracking-tight text-gray-900">Riwayat Pembelian</h1>
                    <p className="mt-2 text-sm text-gray-500">
                        Pantau status pembayaran dan akses kelas Anda di sini. Anda memiliki total <span className="font-bold text-gray-800">{orders.length} pesanan</span>.
                    </p>
                </div>

                {orders.length === 0 ? (
                    /* Borderless Empty State */
                    <div className="flex flex-col items-center justify-center rounded-2xl bg-white py-16 px-4 text-center shadow-sm">
                        <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-sky-50 text-sky-500">
                            <Receipt className="h-8 w-8" />
                        </div>
                        <h3 className="text-lg font-bold text-gray-900">Belum ada pesanan</h3>
                        <p className="mt-1 max-w-sm text-sm text-gray-500 leading-relaxed">
                            Sepertinya Anda belum pernah melakukan pembelian kelas. Mulai cari kelas impian Anda sekarang!
                        </p>
                        <Link
                            href="/courses"
                            className="mt-6 inline-flex items-center gap-2 rounded-xl bg-[#118AB2] px-6 py-3 text-sm font-semibold text-white shadow-md shadow-sky-500/10 transition-all hover:-translate-y-0.5 hover:shadow-lg active:translate-y-0"
                        >
                            Jelajahi Kelas
                        </Link>
                    </div>
                ) : (
                    /* Borderless Order List */
                    <div className="flex flex-col gap-5">
                        {orders.map((order) => {
                            const cfg = STATUS_CONFIG[order.status];
                            const StatusIcon = cfg.icon;
                            return (
                                <Link
                                    key={order.id}
                                    href={`/orders/${order.id}`}
                                    className="group flex flex-col overflow-hidden rounded-2xl bg-white shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md active:translate-y-0"
                                >
                                    <div className="p-6">
                                        <div className="flex flex-wrap items-center justify-between gap-4 pb-4">
                                            {/* Left: Order Info & Date */}
                                            <div className="flex items-center gap-3">
                                                <div className="flex -space-x-2.5">
                                                    {order.items.slice(0, 3).map((item) =>
                                                        item.course.thumbnail ? (
                                                            <img
                                                                key={item.id}
                                                                src={item.course.thumbnail}
                                                                alt={item.course.title}
                                                                className="h-10 w-10 rounded-xl object-cover ring-2 ring-white shadow-xs"
                                                            />
                                                        ) : (
                                                            <div
                                                                key={item.id}
                                                                className="flex h-10 w-10 items-center justify-center rounded-xl bg-sky-50 ring-2 ring-white shadow-xs"
                                                            >
                                                                <GraduationCap className="h-5 w-5 text-sky-500" />
                                                            </div>
                                                        ),
                                                    )}
                                                    {order.items.length > 3 && (
                                                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gray-50 text-xs font-bold text-gray-500 ring-2 ring-white shadow-xs">
                                                            +{order.items.length - 3}
                                                        </div>
                                                    )}
                                                </div>

                                                <div>
                                                    <span className="text-xs font-bold text-gray-400 uppercase tracking-wider block">ID Pesanan</span>
                                                    <h3 className="font-mono text-sm font-bold text-gray-800">#{order.id}</h3>
                                                </div>
                                            </div>

                                            {/* Right: Status Badge */}
                                            <span
                                                className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-bold transition-colors"
                                                style={{ backgroundColor: cfg.bg, color: cfg.color }}
                                            >
                                                <StatusIcon className="h-3.5 w-3.5" />
                                                {cfg.label}
                                            </span>
                                        </div>

                                        {/* Middle Section: Items Summary */}
                                        <div className="py-2">
                                            <p className="font-bold text-gray-950 group-hover:text-[#118AB2] transition-colors leading-snug text-lg">
                                                {order.items.length === 1
                                                    ? order.items[0].course.title
                                                    : `${order.items.length} kelas terdaftar`}
                                            </p>
                                            {order.items.length > 1 && (
                                                <p className="mt-1 text-xs text-gray-400 line-clamp-1">
                                                    {order.items.map((i) => i.course.title).join(', ')}
                                                </p>
                                            )}
                                        </div>

                                        {/* Bottom Info: Price & Date */}
                                        <div className="flex flex-wrap items-center justify-between gap-4 pt-4 mt-2 text-xs text-gray-400">
                                            <div className="flex items-center gap-4">
                                                <span className="flex items-center gap-1">
                                                    <Calendar className="h-3.5 w-3.5 text-gray-400" />
                                                    {order.created_at}
                                                </span>
                                            </div>
                                            
                                            <div className="flex items-center gap-2">
                                                <span className="text-gray-400 font-medium">Total Pembayaran</span>
                                                <span className="text-lg font-black text-gray-900">
                                                    {order.total_amount > 0 ? formatPrice(order.total_amount) : 'Gratis'}
                                                </span>
                                                <ChevronRight className="h-4 w-4 text-gray-400 group-hover:translate-x-0.5 transition-transform" />
                                            </div>
                                        </div>

                                        {/* Rejection Alert */}
                                        {order.status === 'rejected' && order.admin_notes && (
                                            <div className="mt-4 rounded-xl bg-red-50/50 p-3 text-xs text-red-800">
                                                <span className="font-bold">Alasan Penolakan: </span>
                                                {order.admin_notes}
                                            </div>
                                        )}
                                    </div>
                                </Link>
                            );
                        })}
                    </div>
                )}
            </div>
        </>
    );
}

OrdersIndex.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
