import { Head } from '@inertiajs/react';
import { CheckCircle, Clock, Copy, Check, Link2, TrendingUp, Wallet } from 'lucide-react';
import { useState } from 'react';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type AffiliateCodeData = {
    id: number;
    code: string;
    status: 'pending' | 'approved' | 'rejected';
    commission_rate: number;
    total_earnings: number;
    pending_earnings: number;
};

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

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

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

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Program Affiliate', href: '/affiliate' },
];

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

export default function AffiliateIndex({ affiliateCode, commissions }: Props) {
    const [copied, setCopied] = useState(false);
    const refLink = `${window.location.origin}/ref/${affiliateCode.code}`;

    function copyLink() {
        navigator.clipboard.writeText(refLink);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    }

    const isPending = affiliateCode.status === 'pending';
    const isRejected = affiliateCode.status === 'rejected';
    const isApproved = affiliateCode.status === 'approved';

    return (
        <>
            <Head title="Program Affiliate" />
            <div className="mx-auto max-w-3xl space-y-6">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900">Program Affiliate</h1>
                    <p className="mt-1 text-sm text-gray-500">
                        Bagikan link referral Anda dan dapatkan komisi setiap ada yang membeli melalui link Anda.
                    </p>
                </div>

                {/* Status Banner */}
                {isPending && (
                    <div className="flex items-start gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-5">
                        <Clock className="mt-0.5 h-5 w-5 shrink-0 text-amber-500" />
                        <div>
                            <p className="font-semibold text-amber-800">Pendaftaran sedang direview</p>
                            <p className="mt-0.5 text-sm text-amber-700">
                                Admin sedang memverifikasi pendaftaran affiliate Anda. Link referral akan aktif setelah disetujui.
                            </p>
                        </div>
                    </div>
                )}

                {isRejected && affiliateCode && (
                    <div className="flex items-start gap-3 rounded-2xl border border-red-200 bg-red-50 p-5">
                        <p className="font-semibold text-red-800">Pendaftaran affiliate ditolak.</p>
                    </div>
                )}

                {/* Stats */}
                <div className="grid gap-4 sm:grid-cols-3">
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <div className="flex items-center gap-2.5 text-gray-400 mb-3">
                            <Link2 className="h-4 w-4" />
                            <span className="text-xs font-semibold uppercase tracking-wider">Kode Referral</span>
                        </div>
                        <p className="font-mono text-2xl font-black text-gray-900">{affiliateCode.code}</p>
                        <p className="mt-1 text-sm text-gray-400">Komisi {affiliateCode.commission_rate}% per transaksi</p>
                    </div>
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <div className="flex items-center gap-2.5 text-gray-400 mb-3">
                            <Wallet className="h-4 w-4" />
                            <span className="text-xs font-semibold uppercase tracking-wider">Total Komisi Dibayar</span>
                        </div>
                        <p className="text-2xl font-black text-emerald-600">{formatPrice(affiliateCode.total_earnings)}</p>
                    </div>
                    <div className="rounded-2xl bg-white p-5 shadow-sm">
                        <div className="flex items-center gap-2.5 text-gray-400 mb-3">
                            <TrendingUp className="h-4 w-4" />
                            <span className="text-xs font-semibold uppercase tracking-wider">Menunggu Pembayaran</span>
                        </div>
                        <p className="text-2xl font-black text-amber-600">{formatPrice(affiliateCode.pending_earnings)}</p>
                    </div>
                </div>

                {/* Referral Link */}
                {isApproved && (
                    <div className="rounded-2xl bg-white p-6 shadow-sm">
                        <h2 className="mb-4 font-bold text-gray-900">Link Referral Anda</h2>
                        <div className="flex items-center gap-3 rounded-xl bg-gray-50 p-3">
                            <p className="flex-1 truncate font-mono text-sm text-gray-700">{refLink}</p>
                            <button
                                onClick={copyLink}
                                className="flex shrink-0 items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-semibold text-gray-600 hover:bg-gray-50 transition-colors"
                            >
                                {copied ? (
                                    <><Check className="h-3.5 w-3.5 text-emerald-500" /> <span className="text-emerald-600">Tersalin</span></>
                                ) : (
                                    <><Copy className="h-3.5 w-3.5" /> Salin Link</>
                                )}
                            </button>
                        </div>
                        <p className="mt-3 text-xs text-gray-400">
                            Tambahkan <code className="rounded bg-gray-100 px-1 py-0.5 font-mono">?to=/courses/nama-kelas</code> untuk link ke kelas tertentu.
                        </p>
                    </div>
                )}

                {/* Commission History */}
                <div className="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>
                    {commissions.data.length > 0 ? (
                        <div className="divide-y divide-gray-50">
                            {commissions.data.map((commission) => (
                                <div key={commission.id} className="flex items-center justify-between px-6 py-4">
                                    <div>
                                        <p className="font-semibold text-gray-900">Order #{commission.order.id}</p>
                                        <p className="text-xs text-gray-400">
                                            {new Date(commission.created_at).toLocaleDateString('id-ID', {
                                                day: 'numeric', month: 'long', year: 'numeric'
                                            })}
                                        </p>
                                    </div>
                                    <div className="text-right">
                                        <p className="font-bold text-gray-900">{formatPrice(commission.amount)}</p>
                                        {commission.status === 'paid' ? (
                                            <span className="inline-flex items-center gap-1 text-xs font-semibold text-emerald-600">
                                                <CheckCircle className="h-3 w-3" /> Dibayar
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center gap-1 text-xs font-semibold text-amber-600">
                                                <Clock className="h-3 w-3" /> Menunggu
                                            </span>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="px-6 py-12 text-center">
                            <TrendingUp className="mx-auto mb-3 h-8 w-8 text-gray-200" />
                            <p className="text-sm text-gray-400">Belum ada komisi. Bagikan link referral Anda!</p>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

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