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

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

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 = { order: 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'
    },
    approved: { 
        label: 'Pembayaran Disetujui', 
        icon: CheckCircle2, 
        color: '#059669', 
        bg: '#D1FAE5'
    },
    rejected: { 
        label: 'Pembayaran Ditolak',   
        icon: XCircle,      
        color: '#DC2626', 
        bg: '#FEE2E2'
    },
};

export default function OrderShow({ order }: Props) {
    const cfg = STATUS_CONFIG[order.status];
    const StatusIcon = cfg.icon;

    return (
        <>
            <Head title={`Pesanan #${order.id} – Pakandi`} />

            <div className="mx-auto max-w-5xl px-4 py-8 sm:px-6 lg:px-8">
                {/* Back Navigation */}
                <Link
                    href="/orders"
                    className="group mb-6 inline-flex items-center gap-1.5 text-sm font-medium text-gray-500 transition-colors hover:text-gray-900"
                >
                    <ChevronLeft className="h-4 w-4 transition-transform group-hover:-translate-x-0.5" />
                    Kembali ke Riwayat Pembelian
                </Link>

                <div className="grid gap-8 lg:grid-cols-[1fr_340px]">
                    {/* Left Column: Order Status and Details */}
                    <div className="flex flex-col gap-6">
                        {/* Status Card - Borderless */}
                        <div className="overflow-hidden rounded-2xl bg-white p-6 shadow-sm">
                            <div className="flex items-center gap-4">
                                <div
                                    className="flex h-12 w-12 items-center justify-center rounded-2xl transition-colors"
                                    style={{ backgroundColor: cfg.bg }}
                                >
                                    <StatusIcon className="h-6 w-6" style={{ color: cfg.color }} />
                                </div>
                                <div>
                                    <div className="flex items-center gap-2">
                                        <p className="text-lg font-extrabold" style={{ color: cfg.color }}>{cfg.label}</p>
                                    </div>
                                    <p className="text-xs text-gray-500 mt-0.5">
                                        Pesanan <span className="font-mono font-bold text-gray-700">#{order.id}</span> · Terdaftar pada {order.created_at}
                                    </p>
                                </div>
                            </div>

                            {/* Dynamic Alert Banner based on status */}
                            {order.status === 'pending' && (
                                <div className="mt-5 rounded-xl bg-amber-50/70 p-4 text-sm text-amber-800 leading-relaxed">
                                    <p className="font-bold">Sedang Diproses</p>
                                    <p className="mt-0.5 text-xs text-amber-700">
                                        Bukti transfer Anda sedang diverifikasi oleh tim admin kami. Proses verifikasi biasanya selesai dalam waktu kurang dari 1 jam. Akses kelas akan segera terbuka begitu disetujui.
                                    </p>
                                </div>
                            )}

                            {order.status === 'approved' && (
                                <div className="mt-5 rounded-xl bg-emerald-50/70 p-4 text-sm text-emerald-800 leading-relaxed">
                                    <p className="font-bold">Pembayaran Berhasil</p>
                                    <p className="mt-0.5 text-xs text-emerald-700">
                                        Pembayaran Anda telah diverifikasi secara resmi pada <span className="font-semibold">{order.approved_at}</span>. Semua kelas di bawah ini kini aktif dan siap untuk dipelajari. Selamat belajar!
                                    </p>
                                </div>
                            )}

                            {order.status === 'rejected' && order.admin_notes && (
                                <div className="mt-5 rounded-xl bg-red-50/70 p-4 text-sm text-red-800 leading-relaxed">
                                    <p className="font-bold">Pembayaran Ditolak</p>
                                    <p className="mt-0.5 text-xs text-red-700">
                                        <span className="font-bold">Alasan Penolakan: </span>{order.admin_notes}
                                    </p>
                                </div>
                            )}
                        </div>

                        {/* Order Items Details - Borderless */}
                        <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
                            <div className="px-6 py-4">
                                <h2 className="text-lg font-bold text-gray-900">Rincian Kelas</h2>
                            </div>
                            <div className="px-6 pb-4 flex flex-col gap-4">
                                {order.items.map((item) => (
                                    <div key={item.id} className="flex gap-4 py-3 first:pt-0 last:pb-0">
                                        {item.course.thumbnail ? (
                                            <img
                                                src={item.course.thumbnail}
                                                alt={item.course.title}
                                                className="h-16 w-28 shrink-0 rounded-xl object-cover shadow-xs"
                                            />
                                        ) : (
                                            <div className="flex h-16 w-28 shrink-0 items-center justify-center rounded-xl bg-sky-50">
                                                <GraduationCap className="h-7 w-7 text-sky-500/60" />
                                            </div>
                                        )}
                                        <div className="min-w-0 flex-1 flex flex-col justify-between">
                                            <div>
                                                <h3 className="font-bold text-gray-900 leading-snug line-clamp-1 text-base">
                                                    {item.course.title}
                                                </h3>
                                                <p className="text-xs text-gray-500 mt-0.5">
                                                    Oleh {item.course.instructor.name}
                                                </p>
                                            </div>
                                            
                                            {order.status === 'approved' && item.course.slug && (
                                                <Link
                                                    href={`/my-courses/${item.course.slug}`}
                                                    className="mt-2 inline-flex items-center gap-1 text-xs font-bold text-[#118AB2] hover:underline"
                                                >
                                                    <PlayCircle className="h-4 w-4" />
                                                    Mulai Belajar Sekarang
                                                </Link>
                                            )}
                                        </div>
                                        <div className="text-right shrink-0">
                                            <span className="font-extrabold text-base text-gray-900">
                                                {item.price > 0 ? formatPrice(item.price) : 'Gratis'}
                                            </span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Right Column: Invoice/Payment Summary Card - Borderless */}
                    <div className="flex flex-col gap-4">
                        <div className="rounded-2xl bg-white p-6 shadow-sm h-fit">
                            <h2 className="text-lg font-bold text-gray-900 mb-4">Ringkasan Pembayaran</h2>

                            <div className="space-y-3 pb-4">
                                {order.items.map((item) => (
                                    <div key={item.id} className="flex justify-between gap-3 text-xs">
                                        <span className="text-gray-400 truncate flex-1">{item.course.title}</span>
                                        <span className="font-medium text-gray-600 shrink-0">
                                            {item.price > 0 ? formatPrice(item.price) : 'Gratis'}
                                        </span>
                                    </div>
                                ))}
                            </div>

                            <div className="mt-2 flex justify-between items-baseline border-t border-gray-50 pt-4">
                                <span className="text-sm font-semibold text-gray-900">Total Transaksi</span>
                                <span className="text-2xl font-black text-[#118AB2]">{formatPrice(order.total_amount)}</span>
                            </div>

                            {/* Order Metadata */}
                            <div className="mt-5 border-t border-gray-50 pt-4 space-y-2 text-xs text-gray-400">
                                <div className="flex justify-between">
                                    <span>Nomor Invoice</span>
                                    <span className="font-mono font-bold text-gray-700">#{order.id}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span>Tanggal Transaksi</span>
                                    <span className="font-medium text-gray-600">{order.created_at}</span>
                                </div>
                                {order.approved_at && (
                                    <div className="flex justify-between">
                                        <span>Tanggal Verifikasi</span>
                                        <span className="font-medium text-gray-600">{order.approved_at}</span>
                                    </div>
                                )}
                            </div>

                            {order.status === 'approved' && (
                                <Link
                                    href="/my-courses"
                                    className="mt-6 flex w-full items-center justify-center gap-1.5 rounded-xl py-3.5 text-sm font-bold text-white shadow-sm transition-all duration-150 hover:-translate-y-0.5 active:translate-y-0"
                                    style={{
                                        backgroundColor: BRAND,
                                        boxShadow: '0 4px 16px rgba(17,138,178,0.24)',
                                    }}
                                >
                                    Ke Kelas Saya
                                </Link>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

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