import { Head, Link, useForm, router } from '@inertiajs/react';
import { AlertCircle, BookOpen, GraduationCap, Upload, Copy, Check, ShieldCheck, CreditCard, Lock, Tag, X } from 'lucide-react';
import { useRef, useState } from 'react';
import InputError from '@/components/input-error';
import AppLayout from '@/layouts/app-layout';

type CourseItem = {
    id: number;
    title: string;
    slug: string;
    thumbnail: string | null;
    price: number;
    price_type: 'free' | 'paid';
    level: string;
    lessons_count: number;
    instructor: { id: number; name: string };
};

type CheckoutItem = {
    id: number;
    course: CourseItem;
};

type BankInfo = {
    bank_name: string | null;
    bank_account: string | null;
    bank_holder: string | null;
};

type AppliedCoupon = {
    code: string;
    discount: number;
    type: 'percentage' | 'fixed';
    value: number;
};

type Props = {
    items: CheckoutItem[];
    subtotal: number;
    discountAmount: number;
    total: number;
    appliedCoupon: AppliedCoupon | null;
    hasPaidItems: boolean;
    bankInfo: BankInfo | null;
};

const BRAND = '#118AB2';

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

const levelLabels: Record<string, string> = {
    beginner: 'Pemula',
    intermediate: 'Menengah',
    advanced: 'Mahir',
};

export default function CheckoutIndex({ items, subtotal, discountAmount, total, appliedCoupon, hasPaidItems, bankInfo }: Props) {
    const fileRef = useRef<HTMLInputElement>(null);
    const [copiedAccount, setCopiedAccount] = useState(false);
    const [copiedAmount, setCopiedAmount] = useState(false);
    const [couponCode, setCouponCode] = useState('');
    const [couponLoading, setCouponLoading] = useState(false);

    const { data, setData, post, processing, errors } = useForm<{ proof: File | null; selected_items: string }>({
        proof: null,
        selected_items: items.map((i) => i.id).join(','),
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post('/checkout', { forceFormData: true });
    }

    function copyToClipboard(text: string, type: 'account' | 'amount') {
        navigator.clipboard.writeText(text);
        if (type === 'account') {
            setCopiedAccount(true);
            setTimeout(() => setCopiedAccount(false), 2000);
        } else {
            setCopiedAmount(true);
            setTimeout(() => setCopiedAmount(false), 2000);
        }
    }

    function applyCoupon(e: React.FormEvent) {
        e.preventDefault();
        if (!couponCode.trim()) { return; }
        setCouponLoading(true);
        router.post('/checkout/coupon', { code: couponCode }, {
            onFinish: () => setCouponLoading(false),
        });
    }

    function removeCoupon() {
        router.delete('/checkout/coupon');
    }

    return (
        <>
            <Head title="Checkout Aman – Pakandi" />

            <div className="mx-auto max-w-5xl px-4 py-8 sm:px-6 lg:px-8">
                {/* Back Link & Title */}
                <div className="mb-8">
                    <Link href="/cart" className="group mb-3 inline-flex items-center gap-1 text-sm font-medium text-gray-500 transition-colors hover:text-gray-900">
                        <span className="transition-transform group-hover:-translate-x-0.5">←</span> Kembali ke keranjang
                    </Link>

                    <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                        <div>
                            <h1 className="text-3xl font-extrabold tracking-tight text-gray-900">Checkout</h1>
                            <p className="mt-1 text-sm text-gray-500">Selesaikan pendaftaran kelas Anda dengan aman.</p>
                        </div>

                        {/* Progress Steps */}
                        <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-gray-400">
                            <span className="text-gray-900">1. Keranjang</span>
                            <span className="text-gray-300">/</span>
                            <span className="text-[#118AB2] border-b-2 border-[#118AB2] pb-0.5">2. Checkout</span>
                            <span className="text-gray-300">/</span>
                            <span className="text-gray-400">3. Selesai</span>
                        </div>
                    </div>
                </div>

                <form onSubmit={submit}>
                    <div className="grid gap-8 lg:grid-cols-[1fr_360px]">
                        {/* Left Column */}
                        <div className="flex flex-col gap-6">
                            {/* Course list */}
                            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
                                <div className="border-b border-gray-50 px-6 py-4">
                                    <h2 className="text-lg font-bold text-gray-900">Rincian Kelas</h2>
                                </div>
                                <div className="divide-y divide-gray-50 px-6">
                                    {items.map((item) => (
                                        <div key={item.id} className="flex gap-4 py-4 first:pt-4 last:pb-4">
                                            {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 line-clamp-1 leading-snug">
                                                        {item.course.title}
                                                    </h3>
                                                    <p className="text-xs font-medium text-gray-500 mt-0.5">
                                                        {item.course.instructor.name} · <span className="text-gray-400">{levelLabels[item.course.level] ?? item.course.level}</span>
                                                    </p>
                                                </div>
                                                <div className="flex items-center gap-3 mt-1.5 text-xs text-gray-400">
                                                    <span className="flex items-center gap-1">
                                                        <BookOpen className="h-3.5 w-3.5" />
                                                        {item.course.lessons_count} Lesson
                                                    </span>
                                                </div>
                                            </div>
                                            <div className="text-right shrink-0">
                                                <span className="font-extrabold text-base block" style={{ color: item.course.price_type === 'free' ? '#06D6A0' : '#1A1A1A' }}>
                                                    {item.course.price_type === 'free' ? 'Gratis' : formatPrice(item.course.price)}
                                                </span>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Coupon Section */}
                            {hasPaidItems && (
                                <div className="rounded-2xl bg-white p-6 shadow-sm">
                                    <div className="mb-4 flex items-center gap-2.5">
                                        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-[#118AB2]/10 text-[#118AB2]">
                                            <Tag className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h2 className="text-base font-bold text-gray-900">Kode Kupon</h2>
                                            <p className="text-xs text-gray-500">Punya kode diskon? Masukkan di sini.</p>
                                        </div>
                                    </div>

                                    {appliedCoupon ? (
                                        <div className="flex items-center justify-between rounded-xl border-2 border-emerald-200 bg-emerald-50 px-4 py-3">
                                            <div className="flex items-center gap-3">
                                                <Check className="h-5 w-5 text-emerald-500" />
                                                <div>
                                                    <p className="font-mono font-bold text-emerald-800">{appliedCoupon.code}</p>
                                                    <p className="text-xs text-emerald-600">
                                                        Hemat {appliedCoupon.type === 'percentage' ? `${appliedCoupon.value}%` : formatPrice(appliedCoupon.value)}
                                                        {' — '}Diskon {formatPrice(discountAmount)}
                                                    </p>
                                                </div>
                                            </div>
                                            <button
                                                type="button"
                                                onClick={removeCoupon}
                                                className="rounded-lg p-1.5 text-emerald-400 hover:bg-emerald-100 hover:text-emerald-600 transition-colors"
                                            >
                                                <X className="h-4 w-4" />
                                            </button>
                                        </div>
                                    ) : (
                                        <div className="flex gap-2">
                                            <input
                                                type="text"
                                                value={couponCode}
                                                onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
                                                placeholder="Masukkan kode kupon"
                                                className="flex-1 rounded-xl border border-gray-200 px-4 py-2.5 font-mono text-sm uppercase focus:border-[#118AB2] focus:outline-none focus:ring-1 focus:ring-[#118AB2]"
                                            />
                                            <button
                                                type="button"
                                                onClick={applyCoupon}
                                                disabled={couponLoading || !couponCode.trim()}
                                                className="rounded-xl bg-[#118AB2] px-4 py-2.5 text-sm font-semibold text-white hover:bg-[#0e7a9e] disabled:opacity-50 transition-colors"
                                            >
                                                {couponLoading ? '...' : 'Pakai'}
                                            </button>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* Payment Instruction Section */}
                            {hasPaidItems && bankInfo && (
                                <div className="rounded-2xl bg-white p-6 shadow-sm">
                                    <div className="mb-5 flex items-center gap-2.5">
                                        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-[#118AB2]/10 text-[#118AB2]">
                                            <CreditCard className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h2 className="text-lg font-bold text-gray-900">Metode Pembayaran</h2>
                                            <p className="text-xs text-gray-500">Silakan lakukan transfer manual ke rekening di bawah ini.</p>
                                        </div>
                                    </div>

                                    {/* Bank Transfer Card */}
                                    <div className="relative overflow-hidden rounded-2xl bg-slate-50/50 p-5">
                                        <div className="absolute top-0 right-0 h-24 w-24 translate-x-6 -translate-y-6 rounded-full bg-[#118AB2]/5 blur-xl" />

                                        <div className="grid gap-4 sm:grid-cols-2">
                                            <div>
                                                <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400">Nama Bank</span>
                                                <p className="text-lg font-black text-[#118AB2]">{bankInfo.bank_name}</p>
                                            </div>
                                            <div>
                                                <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400">Atas Nama</span>
                                                <p className="text-sm font-bold text-gray-800">{bankInfo.bank_holder}</p>
                                            </div>
                                        </div>

                                        <div className="mt-4 border-t border-gray-100 pt-4">
                                            <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400">Nomor Rekening</span>
                                            <div className="mt-1 flex items-center justify-between">
                                                <p className="font-mono text-2xl font-black tracking-widest text-gray-900">
                                                    {bankInfo.bank_account}
                                                </p>
                                                <button
                                                    type="button"
                                                    onClick={() => copyToClipboard(bankInfo.bank_account ?? '', 'account')}
                                                    className="flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-2.5 py-1.5 text-xs font-semibold text-gray-600 shadow-2xs hover:bg-gray-50 transition-colors"
                                                >
                                                    {copiedAccount ? (
                                                        <><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" /><span>Salin</span></>
                                                    )}
                                                </button>
                                            </div>
                                        </div>

                                        <div className="mt-4 border-t border-gray-100 pt-4 flex items-center justify-between">
                                            <div>
                                                <span className="text-[10px] font-bold uppercase tracking-widest text-gray-400">Jumlah Transfer</span>
                                                <p className="text-xl font-extrabold text-gray-900 mt-0.5">{formatPrice(total)}</p>
                                                {discountAmount > 0 && (
                                                    <p className="text-xs text-emerald-600 font-medium">Sudah termasuk diskon {formatPrice(discountAmount)}</p>
                                                )}
                                            </div>
                                            <button
                                                type="button"
                                                onClick={() => copyToClipboard(total.toString(), 'amount')}
                                                className="flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-2.5 py-1.5 text-xs font-semibold text-gray-600 shadow-2xs hover:bg-gray-50 transition-colors"
                                            >
                                                {copiedAmount ? (
                                                    <><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" /><span>Salin</span></>
                                                )}
                                            </button>
                                        </div>
                                    </div>

                                    {/* Upload Proof */}
                                    <div className="mt-6">
                                        <label className="block text-sm font-bold text-gray-900 mb-2">Upload Bukti Transfer</label>

                                        <input
                                            ref={fileRef}
                                            type="file"
                                            accept=".jpg,.jpeg,.png,.pdf"
                                            className="hidden"
                                            onChange={(e) => setData('proof', e.target.files?.[0] ?? null)}
                                        />

                                        <button
                                            type="button"
                                            onClick={() => fileRef.current?.click()}
                                            className="group flex w-full flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed py-8 px-4 transition-all duration-200"
                                            style={{
                                                borderColor: data.proof ? '#06D6A0' : 'rgba(17,138,178,0.25)',
                                                backgroundColor: data.proof ? 'rgba(6,214,160,0.03)' : 'rgba(17,138,178,0.01)',
                                            }}
                                        >
                                            <div className="flex h-12 w-12 items-center justify-center rounded-full transition-colors"
                                                 style={{
                                                     backgroundColor: data.proof ? 'rgba(6,214,160,0.1)' : 'rgba(17,138,178,0.06)',
                                                     color: data.proof ? '#06D6A0' : '#118AB2',
                                                 }}
                                            >
                                                <Upload className="h-5 w-5" />
                                            </div>

                                            <div className="text-center">
                                                <p className="text-sm font-bold text-gray-800">
                                                    {data.proof ? data.proof.name : 'Pilih file bukti transfer'}
                                                </p>
                                                <p className="mt-1 text-xs text-gray-400">
                                                    {data.proof ? `${(data.proof.size / (1024 * 1024)).toFixed(2)} MB` : 'Seret & letakkan atau klik untuk menelusuri (.jpg, .png, .pdf hingga 5MB)'}
                                                </p>
                                            </div>
                                        </button>

                                        <InputError message={errors.proof} className="mt-2" />
                                    </div>

                                    {/* Info Alert */}
                                    <div className="mt-5 flex gap-3 rounded-xl bg-amber-50/70 border border-amber-100 p-4 text-sm text-amber-800">
                                        <AlertCircle className="h-5 w-5 shrink-0 text-amber-500" />
                                        <div>
                                            <p className="font-bold">Verifikasi Pembayaran</p>
                                            <p className="mt-0.5 text-xs text-amber-700 leading-relaxed">
                                                Akses kelas akan diaktifkan secara otomatis setelah tim admin kami memverifikasi bukti transfer yang Anda unggah. Proses ini biasanya memakan waktu kurang dari 1 jam.
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Right Column (Sidebar Summary) */}
                        <div className="flex flex-col gap-4">
                            <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-xs h-fit">
                                <h2 className="text-lg font-bold text-gray-900 mb-4">Ringkasan Pesanan</h2>

                                <div className="space-y-3 pb-4">
                                    <div className="flex justify-between text-sm text-gray-500">
                                        <span>Total Item</span>
                                        <span className="font-semibold text-gray-800">{items.length} Kelas</span>
                                    </div>
                                    {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.course.price_type === 'free' ? 'Gratis' : formatPrice(item.course.price)}
                                            </span>
                                        </div>
                                    ))}
                                </div>

                                {discountAmount > 0 && (
                                    <div className="border-t border-gray-50 py-3 space-y-2">
                                        <div className="flex justify-between text-sm">
                                            <span className="text-gray-500">Subtotal</span>
                                            <span className="font-medium text-gray-700">{formatPrice(subtotal)}</span>
                                        </div>
                                        <div className="flex justify-between text-sm">
                                            <span className="flex items-center gap-1.5 text-emerald-600">
                                                <Tag className="h-3.5 w-3.5" />
                                                {appliedCoupon?.code}
                                            </span>
                                            <span className="font-semibold text-emerald-600">-{formatPrice(discountAmount)}</span>
                                        </div>
                                    </div>
                                )}

                                <div className={`${discountAmount > 0 ? 'border-t border-gray-50 pt-3' : 'border-t border-gray-50 pt-4 mt-1'} flex justify-between items-baseline`}>
                                    <span className="text-sm font-semibold text-gray-900">Total Pembayaran</span>
                                    <span className="text-2xl font-black text-[#118AB2]">{total > 0 ? formatPrice(total) : 'Gratis'}</span>
                                </div>

                                <button
                                    type="submit"
                                    disabled={processing || (hasPaidItems && !data.proof)}
                                    className="mt-6 flex w-full items-center justify-center gap-2 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 disabled:cursor-not-allowed disabled:opacity-50"
                                    style={{
                                        backgroundColor: BRAND,
                                        boxShadow: '0 4px 16px rgba(17,138,178,0.24)',
                                    }}
                                >
                                    {processing ? (
                                        'Memproses...'
                                    ) : (
                                        <>
                                            <ShieldCheck className="h-4 w-4" />
                                            {hasPaidItems ? 'Kirim Bukti Pembayaran' : 'Daftar Kelas Gratis'}
                                        </>
                                    )}
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </>
    );
}

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