import { Head, Link, router, useForm } from '@inertiajs/react';
import {
    ArrowLeft,
    BookOpen,
    Building2,
    Check,
    CheckCircle,
    Clock,
    GraduationCap,
    Link2,
    Settings2,
    User,
    Users,
    X,
} from 'lucide-react';
import { useState } from 'react';
import { DataTable, type Column, type TableFilter } from '@/components/data-table';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Commission = {
    id: number;
    amount: number;
    status: 'pending' | 'paid';
    affiliate_type: 'alumni' | 'non_alumni' | null;
    paid_at: string | null;
    created_at: string;
    order: {
        id: number;
        total_amount: number;
        status: string;
        created_at: string;
        user: { id: number; name: string };
    } | null;
    course: { id: number; title: string; slug: string } | null;
};

type CourseBreakdown = {
    course_id: number | null;
    affiliate_type: 'alumni' | 'non_alumni' | null;
    total: number;
    count: number;
    paid_total: number;
    pending_total: number;
    course: { id: number; title: string; slug: string } | null;
};

type AffiliateCode = {
    id: number;
    code: string;
    status: 'pending' | 'approved' | 'rejected';
    commission_rate: number;
    notes: string | null;
    bank_name: string | null;
    bank_account: string | null;
    bank_holder: 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>;
    courseBreakdown: CourseBreakdown[];
};

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

const STATUS_CONFIG = {
    pending:  { label: 'Menunggu',  badge: 'bg-amber-100 text-amber-700',   icon: Clock },
    approved: { label: 'Aktif',     badge: 'bg-emerald-100 text-emerald-700', icon: CheckCircle },
    rejected: { label: 'Ditolak',   badge: 'bg-red-100 text-red-700',        icon: X },
};

function StatusModal({ affiliateCode, onClose }: { affiliateCode: AffiliateCode; onClose: () => void }) {
    const { data, setData, patch, processing } = useForm({
        status: affiliateCode.status as 'approved' | 'rejected',
        commission_rate: String(affiliateCode.commission_rate),
        notes: affiliateCode.notes ?? '',
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        patch(`/admin/affiliates/${affiliateCode.id}/status`, { onSuccess: onClose });
    }

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <form onSubmit={submit} className="w-full max-w-md rounded-2xl bg-white p-6 shadow-xl space-y-4">
                <h3 className="text-lg font-bold text-gray-900">Update Status Affiliate</h3>
                <p className="text-sm text-gray-500">
                    {affiliateCode.user.name} — <span className="font-mono font-bold">{affiliateCode.code}</span>
                </p>

                <div>
                    <p className="mb-1.5 text-sm font-semibold text-gray-700">Status</p>
                    <div className="flex gap-3">
                        {(['approved', 'rejected'] as const).map((s) => (
                            <label key={s} className={`flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-xl border-2 p-3 text-sm font-semibold transition-all ${data.status === s ? (s === 'approved' ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-red-400 bg-red-50 text-red-700') : 'border-gray-200 text-gray-500 hover:border-gray-300'}`}>
                                <input type="radio" className="sr-only" value={s} checked={data.status === s} onChange={() => setData('status', s)} />
                                {s === 'approved' ? <Check className="h-4 w-4" /> : <X className="h-4 w-4" />}
                                {s === 'approved' ? 'Setujui' : 'Tolak'}
                            </label>
                        ))}
                    </div>
                </div>

                <div className="grid gap-2">
                    <Label className="text-sm font-semibold text-gray-700">Rate Komisi (%)</Label>
                    <Input
                        type="number"
                        min="0"
                        max="100"
                        step="0.5"
                        value={data.commission_rate}
                        onChange={(e) => setData('commission_rate', e.target.value)}
                        className="rounded-xl"
                    />
                </div>

                <div className="grid gap-2">
                    <Label className="text-sm font-semibold text-gray-700">Catatan (opsional)</Label>
                    <textarea
                        rows={2}
                        value={data.notes}
                        onChange={(e) => setData('notes', e.target.value)}
                        placeholder="Catatan untuk affiliator..."
                        className="w-full rounded-xl border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-200"
                    />
                </div>

                <div className="flex gap-3 pt-2">
                    <button type="button" onClick={onClose} className="flex-1 rounded-xl border border-gray-200 py-2 text-sm font-semibold text-gray-600 hover:bg-gray-50 transition-colors">
                        Batal
                    </button>
                    <button type="submit" disabled={processing} className="flex-1 rounded-xl bg-blue-100 py-2 text-sm font-semibold text-blue-700 hover:bg-blue-200 border border-blue-200 transition-colors disabled:opacity-50">
                        Simpan
                    </button>
                </div>
            </form>
        </div>
    );
}

export default function AdminAffiliatesShow({ affiliateCode, commissions, courseBreakdown }: Props) {
    const [showModal, setShowModal] = useState(false);

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Admin', href: '/admin' },
        { title: 'Affiliate', href: '/admin/affiliates' },
        { title: affiliateCode.user.name, href: '#' },
    ];

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

    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);

    const statusCfg = STATUS_CONFIG[affiliateCode.status];
    const StatusIcon = statusCfg.icon;

    // Flatten courseBreakdown for DataTable
    type BreakdownRow = CourseBreakdown & Record<string, unknown>;
    const breakdownRows: BreakdownRow[] = courseBreakdown as BreakdownRow[];

    const breakdownColumns: Column<BreakdownRow>[] = [
        {
            key: 'course.title',
            header: 'Kelas',
            searchable: true,
            render: (r) =>
                r.course ? (
                    <Link href={`/admin/courses/${r.course.id}/affiliators`} className="font-semibold text-blue-600 hover:underline text-sm">
                        {r.course.title}
                    </Link>
                ) : (
                    <span className="text-sm text-gray-400">Kelas dihapus</span>
                ),
        },
        {
            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: 'count',
            header: 'Referral',
            headerClass: 'w-24 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-semibold tabular-nums">{r.count}x</span>,
        },
        {
            key: 'total',
            header: 'Total',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-bold text-gray-900 tabular-nums">{formatPrice(r.total)}</span>,
        },
        {
            key: 'paid_total',
            header: 'Dibayar',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-semibold text-emerald-600 tabular-nums">{formatPrice(r.paid_total)}</span>,
        },
        {
            key: 'pending_total',
            header: 'Menunggu',
            headerClass: 'w-36 text-right',
            cellClass: 'text-right',
            render: (r) => <span className="font-semibold text-amber-600 tabular-nums">{formatPrice(r.pending_total)}</span>,
        },
    ];

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

    const commColumns: Column<CommRow>[] = [
        {
            key: 'course.title',
            header: 'Kelas / Order',
            searchable: true,
            render: (c) => (
                <div>
                    <p className="font-semibold text-sm text-gray-900">
                        {c.course?.title ?? (c.order ? `Order #${c.order.id}` : '-')}
                    </p>
                    {c.order && (
                        <p className="text-xs text-gray-400">
                            {new Date(c.order.created_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })}
                        </p>
                    )}
                </div>
            ),
        },
        {
            key: 'order.user.name',
            header: 'Pembeli',
            searchable: true,
            render: (c) => <span className="text-sm text-gray-600">{c.order?.user.name ?? '-'}</span>,
        },
        {
            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: '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-32',
            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 whitespace-nowrap">
                        <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 whitespace-nowrap">
                        <Clock className="h-3 w-3" /> Menunggu
                    </span>
                ),
        },
        {
            key: 'id',
            header: '',
            sortable: false,
            headerClass: 'w-36',
            render: (c) =>
                c.status === 'pending' ? (
                    <button
                        onClick={() => payCommission(c.id)}
                        className="rounded-xl border border-blue-200 bg-blue-100 px-3 py-1.5 text-xs font-semibold text-blue-700 hover:bg-blue-200 transition-colors whitespace-nowrap"
                    >
                        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={`Affiliate – ${affiliateCode.user.name}`} />
            {showModal && <StatusModal affiliateCode={affiliateCode} onClose={() => setShowModal(false)} />}

            <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">
                    <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"
                        >
                            <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-12 w-12 shrink-0 items-center justify-center rounded-2xl bg-blue-100 text-lg font-black text-blue-700">
                                    {affiliateCode.user.name.charAt(0).toUpperCase()}
                                </div>
                                <div>
                                    <div className="flex items-center gap-2 flex-wrap">
                                        <h1 className="text-lg font-bold text-blue-900 leading-tight">{affiliateCode.user.name}</h1>
                                        <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold ${statusCfg.badge}`}>
                                            <StatusIcon className="h-3 w-3" />
                                            {statusCfg.label}
                                        </span>
                                    </div>
                                    <p className="text-xs text-blue-500 mt-0.5">{affiliateCode.user.email}</p>
                                    <div className="mt-1 flex items-center gap-3 text-xs text-blue-600">
                                        <span className="flex items-center gap-1">
                                            <Link2 className="h-3 w-3" />
                                            <span className="font-mono font-bold">{affiliateCode.code}</span>
                                        </span>
                                        <span>Komisi {affiliateCode.commission_rate}%</span>
                                    </div>
                                </div>
                            </div>

                            <div className="flex flex-wrap items-center gap-3">
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5">
                                    <p className="text-lg font-black text-emerald-600 tabular-nums">{formatPrice(totalPaid)}</p>
                                    <p className="text-[11px] font-medium text-gray-500">Dibayar</p>
                                </div>
                                <div className="rounded-xl bg-white/70 px-4 py-2 text-center shadow-xs ring-1 ring-black/5">
                                    <p className="text-lg font-black text-amber-600 tabular-nums">{formatPrice(totalPending)}</p>
                                    <p className="text-[11px] font-medium text-gray-500">Menunggu</p>
                                </div>
                                <button
                                    onClick={() => setShowModal(true)}
                                    className="flex items-center gap-1.5 rounded-xl border border-blue-200 bg-blue-100 px-4 py-2 text-sm font-semibold text-blue-700 hover:bg-blue-200 transition-colors shadow-xs"
                                >
                                    <Settings2 className="h-4 w-4" />
                                    Update Status
                                </button>
                            </div>
                        </div>
                    </div>
                    <div className="absolute -right-4 -top-4 h-20 w-20 rounded-full bg-blue-100/40" />
                    <div className="absolute right-10 -bottom-6 h-28 w-28 rounded-full bg-sky-100/30" />
                </div>

                {/* Bank Info */}
                {(affiliateCode.bank_name || affiliateCode.bank_account) && (
                    <div className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-black/5">
                        <div className="mb-3 flex items-center gap-2">
                            <Building2 className="h-4 w-4 text-gray-400" />
                            <h2 className="font-bold text-gray-900">Rekening Bank</h2>
                        </div>
                        <div className="flex flex-wrap gap-x-8 gap-y-2 text-sm">
                            <div className="flex flex-col gap-0.5">
                                <span className="text-xs text-gray-400 uppercase tracking-wider font-semibold">Bank</span>
                                <span className="font-semibold text-gray-900">{affiliateCode.bank_name ?? '-'}</span>
                            </div>
                            <div className="flex flex-col gap-0.5">
                                <span className="text-xs text-gray-400 uppercase tracking-wider font-semibold">No. Rekening</span>
                                <span className="font-mono font-semibold text-gray-900">{affiliateCode.bank_account ?? '-'}</span>
                            </div>
                            <div className="flex flex-col gap-0.5">
                                <span className="text-xs text-gray-400 uppercase tracking-wider font-semibold">Nama Pemilik</span>
                                <span className="font-semibold text-gray-900">{affiliateCode.bank_holder ?? '-'}</span>
                            </div>
                        </div>
                    </div>
                )}

                {/* Per-course Breakdown */}
                {courseBreakdown.length > 0 && (
                    <div>
                        <h2 className="mb-3 text-sm font-bold text-gray-700 uppercase tracking-wider">Komisi per Kelas</h2>
                        <DataTable
                            data={breakdownRows}
                            columns={breakdownColumns}
                            searchPlaceholder="Cari nama kelas..."
                            defaultPageSize={25}
                            emptyIcon={BookOpen}
                            emptyMessage="Belum ada data per kelas"
                            emptyDescription=""
                        />
                    </div>
                )}

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

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