import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, CheckCircle, Clock } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Commission = {
    id: number;
    amount: number;
    status: 'pending' | 'paid';
    paid_at: string | null;
    created_at: string;
    order: {
        id: number;
        total_amount: number;
        status: string;
        created_at: string;
        user: { id: number; name: string };
    };
};

type AffiliateCode = {
    id: number;
    code: string;
    status: 'pending' | 'approved' | 'rejected';
    commission_rate: number;
    notes: string | null;
    user: { id: number; name: string; email: string };
};

type Paginator<T> = {
    data: T[];
    current_page: number;
    last_page: number;
    links: { url: string | null; label: string; active: boolean }[];
};

type Props = { affiliateCode: AffiliateCode; commissions: Paginator<Commission> };

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

export default function AdminAffiliatesShow({ affiliateCode, commissions }: Props) {
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Admin', href: '/admin' },
        { title: 'Affiliate', href: '/admin/affiliates' },
        { title: affiliateCode.user.name, href: `/admin/affiliates/${affiliateCode.id}` },
    ];

    function payCommission(id: number) {
        router.post(`/admin/affiliate-commissions/${id}/pay`);
    }

    const totalPaid = commissions.data
        .filter((c) => c.status === 'paid')
        .reduce((sum, c) => sum + c.amount, 0);

    const totalPending = commissions.data
        .filter((c) => c.status === 'pending')
        .reduce((sum, c) => sum + c.amount, 0);

    return (
        <>
            <Head title={`Affiliate – ${affiliateCode.user.name}`} />
            <div className="space-y-6">
                <div className="flex items-center gap-4">
                    <Link href="/admin/affiliates" className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-700 transition-colors">
                        <ArrowLeft className="h-5 w-5" />
                    </Link>
                    <div>
                        <h1 className="text-xl font-bold text-gray-900">{affiliateCode.user.name}</h1>
                        <p className="text-sm text-gray-500">{affiliateCode.user.email}</p>
                    </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-3">
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">Kode Referral</p>
                        <p className="mt-1 font-mono text-2xl font-black text-gray-900">{affiliateCode.code}</p>
                        <p className="mt-1 text-sm text-gray-500">Komisi {affiliateCode.commission_rate}%</p>
                    </div>
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">Komisi Dibayar</p>
                        <p className="mt-1 text-2xl font-black text-emerald-600">{formatPrice(totalPaid)}</p>
                    </div>
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <p className="text-xs font-semibold uppercase tracking-wider text-gray-400">Menunggu Pembayaran</p>
                        <p className="mt-1 text-2xl font-black text-amber-600">{formatPrice(totalPending)}</p>
                    </div>
                </div>

                <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
                    <div className="border-b border-gray-100 px-6 py-4">
                        <h2 className="font-bold text-gray-900">Riwayat Komisi</h2>
                    </div>
                    <table className="min-w-full divide-y divide-gray-50">
                        <thead className="bg-gray-50">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Order</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Pembeli</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Komisi</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider text-gray-500">Status</th>
                                <th className="px-6 py-3" />
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-50">
                            {commissions.data.map((commission) => (
                                <tr key={commission.id} className="hover:bg-gray-50/50">
                                    <td className="px-6 py-4 text-sm">
                                        <p className="font-semibold text-gray-900">Order #{commission.order.id}</p>
                                        <p className="text-xs text-gray-400">
                                            {new Date(commission.order.created_at).toLocaleDateString('id-ID')}
                                        </p>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-gray-600">
                                        {commission.order.user.name}
                                    </td>
                                    <td className="px-6 py-4 text-sm font-bold text-gray-900">
                                        {formatPrice(commission.amount)}
                                    </td>
                                    <td className="px-6 py-4">
                                        {commission.status === 'paid' ? (
                                            <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
                                                <CheckCircle className="h-3 w-3" /> Dibayar
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-semibold text-amber-700">
                                                <Clock className="h-3 w-3" /> Menunggu
                                            </span>
                                        )}
                                    </td>
                                    <td className="px-6 py-4">
                                        {commission.status === 'pending' && (
                                            <button
                                                onClick={() => payCommission(commission.id)}
                                                className="rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-600 hover:bg-gray-50 transition-colors"
                                            >
                                                Tandai Dibayar
                                            </button>
                                        )}
                                    </td>
                                </tr>
                            ))}
                            {commissions.data.length === 0 && (
                                <tr>
                                    <td colSpan={5} className="px-6 py-10 text-center text-sm text-gray-400">
                                        Belum ada komisi.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

AdminAffiliatesShow.layout = (page: React.ReactNode) => (
    <AppLayout breadcrumbs={[
        { title: 'Admin', href: '/admin' },
        { title: 'Affiliate', href: '/admin/affiliates' },
        { title: 'Detail', href: '#' },
    ]}>{page}</AppLayout>
);
