import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Building2, CheckCircle, Clock, GraduationCap, Link2, Users } from 'lucide-react';
import { DataTable, type Column, type TableFilter } from '@/components/data-table';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Course = {
    id: number;
    title: string;
    slug: string;
    alumni_commission_rate: number | null;
    non_alumni_commission_rate: number | null;
};

type AffiliatorSummary = {
    affiliate_code_id: number;
    affiliate_type: 'alumni' | 'non_alumni' | null;
    referrals: number;
    total_commission: number;
    pending_commission: number;
    affiliateCode: {
        id: number;
        code: string;
        status: string;
        bank_name: string | null;
        bank_account: string | null;
        bank_holder: string | null;
        user: { id: number; name: string; email: string };
    };
};

type Commission = {
    id: number;
    amount: number;
    status: 'pending' | 'paid';
    affiliate_type: 'alumni' | 'non_alumni' | null;
    created_at: string;
    affiliate_code: {
        id: number;
        code: string;
        user: { id: number; name: string; email: string };
    };
    order: { id: number; total_amount: number; created_at: string } | null;
};

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

type Props = {
    course: Course;
    summary: AffiliatorSummary[];
    commissions: Paginator<Commission>;
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Admin', href: '/admin' },
    { title: 'Affiliate', href: '/admin/affiliates' },
    { title: 'Affiliator Kelas', href: '#' },
];

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

export default function CourseAffiliators({ course, summary, commissions }: Props) {
    const totalCommission = summary.reduce((s, r) => s + r.total_commission, 0);
    const totalPending = summary.reduce((s, r) => s + r.pending_commission, 0);
    const totalReferrals = summary.reduce((s, r) => s + r.referrals, 0);

    // Flatten summary rows for DataTable
    type SummaryRow = AffiliatorSummary & Record<string, unknown>;
    const summaryRows: SummaryRow[] = summary as SummaryRow[];

    const summaryColumns: Column<SummaryRow>[] = [
        {
            key: 'affiliateCode.user.name',
            header: 'Affiliator',
            searchable: true,
            render: (r) => (
                <div>
                    <p className="font-semibold text-sm">{r.affiliateCode.user.name}</p>
                    <p className="text-xs text-muted-foreground">{r.affiliateCode.user.email}</p>
                    <p className="font-mono text-xs text-muted-foreground/70 mt-0.5">{r.affiliateCode.code}</p>
                </div>
            ),
        },
        {
            key: 'affiliate_type',
            header: 'Tipe',
            headerClass: 'w-32',
            cellClass: 'whitespace-nowrap',
            render: (r) =>
                r.affiliate_type === 'alumni' ? (
                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 whitespace-nowrap">
                        <GraduationCap className="h-3 w-3" /> Alumni
                    </span>
                ) : (
                    <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-semibold text-blue-700 whitespace-nowrap">
                        <Users className="h-3 w-3" /> Non-alumni
                    </span>
                ),
        },
        {
            key: 'affiliateCode.bank_name',
            header: 'Rekening',
            render: (r) =>
                r.affiliateCode.bank_name ? (
                    <div className="flex items-start gap-1.5">
                        <Building2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/40" />
                        <div>
                            <p className="text-sm font-medium">{r.affiliateCode.bank_name}</p>
                            <p className="font-mono text-xs text-muted-foreground">{r.affiliateCode.bank_account}</p>
                            <p className="text-xs text-muted-foreground/70">{r.affiliateCode.bank_holder}</p>
                        </div>
                    </div>
                ) : (
                    <span className="text-xs text-muted-foreground/40">Belum diisi</span>
                ),
        },
        {
            key: 'referrals',
            header: 'Referral',
            headerClass: 'w-24 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-semibold tabular-nums">{r.referrals}x</span>,
        },
        {
            key: 'total_commission',
            header: 'Total Komisi',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-bold text-gray-900 dark:text-gray-100 tabular-nums">{formatPrice(r.total_commission)}</span>,
        },
        {
            key: 'pending_commission',
            header: 'Menunggu',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-semibold text-amber-600 tabular-nums">{formatPrice(r.pending_commission)}</span>,
        },
        {
            key: 'affiliate_code_id',
            header: 'Aksi',
            sortable: false,
            headerClass: 'w-24',
            render: (r) => (
                <Link
                    href={`/admin/affiliates/${r.affiliate_code_id}`}
                    className="flex h-8 items-center rounded-xl bg-blue-50 px-3 text-xs font-semibold text-blue-600 hover:bg-blue-100 transition-colors dark:bg-blue-900/30 dark:text-blue-400"
                >
                    Detail
                </Link>
            ),
        },
    ];

    const summaryFilters: TableFilter[] = [
        {
            key: 'affiliate_type',
            label: 'Tipe',
            allLabel: 'Semua Tipe',
            options: [
                { label: 'Alumni', value: 'alumni' },
                { label: 'Non-alumni', value: 'non_alumni' },
            ],
        },
    ];

    // Commission rows for DataTable
    type CommRow = Commission & Record<string, unknown>;
    const commRows: CommRow[] = commissions.data as CommRow[];

    const commColumns: Column<CommRow>[] = [
        {
            key: 'affiliate_code.user.name',
            header: 'Affiliator',
            searchable: true,
            render: (c) => (
                <div>
                    <p className="font-semibold text-sm">{c.affiliate_code.user.name}</p>
                    <p className="font-mono text-xs text-muted-foreground">{c.affiliate_code.code}</p>
                </div>
            ),
        },
        {
            key: 'affiliate_type',
            header: 'Tipe',
            headerClass: 'w-32',
            cellClass: 'whitespace-nowrap',
            render: (c) =>
                c.affiliate_type === 'alumni' ? (
                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 whitespace-nowrap">
                        <GraduationCap className="h-3 w-3" /> Alumni
                    </span>
                ) : c.affiliate_type === 'non_alumni' ? (
                    <span className="inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-semibold text-blue-700 whitespace-nowrap">
                        Non-alumni
                    </span>
                ) : null,
        },
        {
            key: 'order',
            header: 'Order',
            headerClass: 'w-28',
            render: (c) =>
                c.order ? (
                    <div>
                        <p className="text-sm font-medium">#{c.order.id}</p>
                        <p className="text-xs text-muted-foreground">
                            {new Date(c.order.created_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })}
                        </p>
                    </div>
                ) : <span className="text-xs text-muted-foreground/40">-</span>,
        },
        {
            key: 'amount',
            header: 'Komisi',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (c) => <span className="font-bold tabular-nums">{formatPrice(c.amount)}</span>,
        },
        {
            key: 'status',
            header: 'Status',
            headerClass: 'w-28',
            render: (c) =>
                c.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>
                ),
        },
        {
            key: 'id',
            header: 'Aksi',
            sortable: false,
            headerClass: 'w-36',
            render: (c) =>
                c.status === 'pending' ? (
                    <button
                        onClick={() =>
                            router.post(
                                `/admin/affiliate-commissions/${c.id}/pay`,
                                {},
                                { preserveScroll: true },
                            )
                        }
                        className="inline-flex h-7 items-center gap-1.5 rounded-lg bg-emerald-100 px-3 text-xs font-semibold text-emerald-700 transition-colors hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400"
                    >
                        <CheckCircle className="h-3 w-3" /> Tandai Dibayar
                    </button>
                ) : null,
        },
    ];

    const commFilters: TableFilter[] = [
        {
            key: 'status',
            label: 'Status',
            allLabel: 'Semua Status',
            options: [
                { label: 'Menunggu', value: 'pending' },
                { label: 'Dibayar', value: 'paid' },
            ],
        },
        {
            key: 'affiliate_type',
            label: 'Tipe',
            allLabel: 'Semua Tipe',
            options: [
                { label: 'Alumni', value: 'alumni' },
                { label: 'Non-alumni', value: 'non_alumni' },
            ],
        },
    ];

    return (
        <>
            <Head title={`Affiliator – ${course.title}`} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                {/* Header */}
                <div className="relative overflow-hidden rounded-2xl border border-blue-100 bg-gradient-to-br from-blue-50 via-white to-sky-50 p-5 shadow-sm dark:border-blue-800/30 dark:from-blue-950/40 dark:via-card dark:to-sky-950/30">
                    <div className="relative z-10">
                        <Link
                            href="/admin/affiliates"
                            className="mb-3 inline-flex items-center gap-1.5 text-xs font-medium text-blue-600 hover:text-blue-800 transition-colors dark:text-blue-400"
                        >
                            <ArrowLeft className="h-3.5 w-3.5" /> Kembali ke Affiliate
                        </Link>
                        <div className="flex flex-wrap items-start justify-between gap-4">
                            <div className="flex items-center gap-3">
                                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-800/60">
                                    <Link2 className="h-5 w-5 text-blue-600 dark:text-blue-300" />
                                </div>
                                <div>
                                    <h1 className="text-lg font-bold text-blue-900 dark:text-blue-100 leading-tight">{course.title}</h1>
                                    <div className="mt-0.5 flex items-center gap-3 text-xs text-blue-600 dark:text-blue-400">
                                        {course.alumni_commission_rate !== null && (
                                            <span className="flex items-center gap-1">
                                                <GraduationCap className="h-3 w-3" /> Alumni {course.alumni_commission_rate}%
                                            </span>
                                        )}
                                        {course.non_alumni_commission_rate !== null && (
                                            <span className="flex items-center gap-1">
                                                <Users className="h-3 w-3" /> Non-alumni {course.non_alumni_commission_rate}%
                                            </span>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Stats */}
                            <div className="flex flex-wrap gap-3">
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5 dark:bg-card/60">
                                    <p className="text-lg font-black text-gray-900 dark:text-gray-100 tabular-nums">{summary.length}</p>
                                    <p className="text-[11px] font-medium text-muted-foreground">Affiliator</p>
                                </div>
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5 dark:bg-card/60">
                                    <p className="text-lg font-black text-gray-900 dark:text-gray-100 tabular-nums">{totalReferrals}</p>
                                    <p className="text-[11px] font-medium text-muted-foreground">Referral</p>
                                </div>
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5 dark:bg-card/60">
                                    <p className="text-lg font-black text-emerald-600 tabular-nums">{formatPrice(totalCommission)}</p>
                                    <p className="text-[11px] font-medium text-muted-foreground">Total Komisi</p>
                                </div>
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5 dark:bg-card/60">
                                    <p className="text-lg font-black text-amber-600 tabular-nums">{formatPrice(totalPending)}</p>
                                    <p className="text-[11px] font-medium text-muted-foreground">Menunggu</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="absolute -right-4 -top-4 h-20 w-20 rounded-full bg-blue-100/40 dark:bg-blue-700/10" />
                    <div className="absolute right-10 -bottom-6 h-28 w-28 rounded-full bg-sky-100/30 dark:bg-sky-700/10" />
                </div>

                {/* Affiliator Summary Table */}
                <div>
                    <h2 className="mb-3 text-sm font-bold text-gray-700 dark:text-gray-300 uppercase tracking-wider">Daftar Affiliator</h2>
                    <DataTable
                        data={summaryRows}
                        columns={summaryColumns}
                        filters={summaryFilters}
                        searchPlaceholder="Cari nama, email, atau kode referral..."
                        defaultPageSize={25}
                        emptyIcon={Users}
                        emptyMessage="Belum ada affiliator"
                        emptyDescription="Belum ada affiliator yang membagikan kelas ini."
                    />
                </div>

                {/* Commission History Table */}
                <div>
                    <h2 className="mb-3 text-sm font-bold text-gray-700 dark:text-gray-300 uppercase tracking-wider">Riwayat Komisi</h2>
                    <DataTable
                        data={commRows}
                        columns={commColumns}
                        filters={commFilters}
                        searchPlaceholder="Cari nama atau kode referral..."
                        defaultPageSize={25}
                        emptyIcon={Link2}
                        emptyMessage="Belum ada riwayat komisi"
                        emptyDescription="Komisi akan muncul saat ada pembelian melalui link referral."
                    />
                </div>
            </div>
        </>
    );
}

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