import { Head, Link, router } from '@inertiajs/react';
import { BookOpen, GraduationCap, ShoppingCart, Trash2 } from 'lucide-react';
import { useState } from 'react';
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 CartItem = {
    id: number;
    course: CourseItem;
    is_enrolled: boolean;
};

type Props = {
    items: CartItem[];
    total: number;
};

const BRAND = '#118AB2';

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

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

export default function CartIndex({ items }: Props) {
    const activeItems = items.filter((i) => !i.is_enrolled);
    const enrolledItems = items.filter((i) => i.is_enrolled);

    const [selectedIds, setSelectedIds] = useState<Set<number>>(
        new Set(activeItems.map((i) => i.id)),
    );

    function toggleItem(id: number) {
        setSelectedIds((prev) => {
            const next = new Set(prev);
            next.has(id) ? next.delete(id) : next.add(id);
            return next;
        });
    }

    function toggleAll() {
        if (selectedIds.size === activeItems.length) {
            setSelectedIds(new Set());
        } else {
            setSelectedIds(new Set(activeItems.map((i) => i.id)));
        }
    }

    function removeItem(cartItemId: number) {
        setSelectedIds((prev) => { const n = new Set(prev); n.delete(cartItemId); return n; });
        router.delete(`/cart/${cartItemId}`, { preserveScroll: true });
    }

    const selectedItems = activeItems.filter((i) => selectedIds.has(i.id));
    const selectedTotal = selectedItems
        .filter((i) => i.course.price_type === 'paid')
        .reduce((sum, i) => sum + i.course.price, 0);

    const checkoutUrl = selectedIds.size > 0
        ? `/checkout?items=${[...selectedIds].join(',')}`
        : '/checkout';

    const allSelected = activeItems.length > 0 && selectedIds.size === activeItems.length;
    const someSelected = selectedIds.size > 0 && selectedIds.size < activeItems.length;

    return (
        <>
            <Head title="Keranjang" />

            <div className="mx-auto max-w-6xl px-5 py-8">
                <div className="mb-6">
                    <h1 className="text-2xl font-bold" style={{ color: '#1A1A1A' }}>Keranjang</h1>
                    <p className="mt-0.5 text-sm" style={{ color: '#888888' }}>
                        {activeItems.length} kelas siap dibeli
                    </p>
                </div>

                {items.length === 0 ? (
                    <div
                        className="flex flex-col items-center justify-center rounded-2xl py-20 text-center"
                        style={{ border: '1.5px dashed rgba(17,138,178,0.2)', backgroundColor: 'rgba(17,138,178,0.02)' }}
                    >
                        <div
                            className="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl"
                            style={{ backgroundColor: 'rgba(17,138,178,0.08)' }}
                        >
                            <ShoppingCart className="h-8 w-8" style={{ color: BRAND }} />
                        </div>
                        <p className="font-semibold" style={{ color: '#1A1A1A' }}>Keranjangmu kosong</p>
                        <p className="mt-1 text-sm" style={{ color: '#888888' }}>Cari kelas menarik dan tambahkan ke sini</p>
                        <Link
                            href="/courses"
                            className="mt-5 rounded-xl px-5 py-2.5 text-sm font-semibold text-white transition-all hover:-translate-y-0.5"
                            style={{ backgroundColor: BRAND }}
                        >
                            Jelajahi Kelas
                        </Link>
                    </div>
                ) : (
                    <div className="grid gap-6 lg:grid-cols-[1fr_320px]">
                        {/* Item list */}
                        <div className="flex flex-col gap-3">
                            {/* Select all */}
                            {activeItems.length > 1 && (
                                <label className="flex cursor-pointer items-center gap-2.5 px-1 py-0.5">
                                    <input
                                        type="checkbox"
                                        checked={allSelected}
                                        ref={(el) => { if (el) el.indeterminate = someSelected; }}
                                        onChange={toggleAll}
                                        className="h-4 w-4 cursor-pointer rounded border-gray-300"
                                        style={{ accentColor: BRAND }}
                                    />
                                    <span className="text-sm font-medium" style={{ color: '#555' }}>
                                        {allSelected ? 'Batalkan semua' : 'Pilih semua'}
                                    </span>
                                    {selectedIds.size > 0 && (
                                        <span className="text-xs" style={{ color: '#999' }}>
                                            ({selectedIds.size} dipilih)
                                        </span>
                                    )}
                                </label>
                            )}

                            {activeItems.map((item) => (
                                <CartCard
                                    key={item.id}
                                    item={item}
                                    selected={selectedIds.has(item.id)}
                                    onToggle={() => toggleItem(item.id)}
                                    onRemove={() => removeItem(item.id)}
                                />
                            ))}

                            {enrolledItems.length > 0 && (
                                <>
                                    <p className="mt-2 text-xs font-semibold uppercase tracking-wide" style={{ color: '#AAAAAA' }}>
                                        Sudah terdaftar
                                    </p>
                                    {enrolledItems.map((item) => (
                                        <CartCard key={item.id} item={item} onRemove={() => removeItem(item.id)} dimmed />
                                    ))}
                                </>
                            )}
                        </div>

                        {/* Summary */}
                        <div
                            className="h-fit rounded-2xl p-6"
                            style={{ border: '1px solid rgba(0,0,0,0.07)', backgroundColor: '#FFFFFF', boxShadow: '0 2px 16px rgba(0,0,0,0.05)' }}
                        >
                            <h2 className="mb-4 font-bold" style={{ color: '#1A1A1A' }}>Ringkasan</h2>

                            {selectedItems.length === 0 ? (
                                <p className="text-sm" style={{ color: '#AAAAAA' }}>Belum ada kelas dipilih.</p>
                            ) : (
                                <div className="space-y-2 text-sm" style={{ color: '#555555' }}>
                                    {selectedItems.map((item) => (
                                        <div key={item.id} className="flex justify-between gap-3">
                                            <span className="min-w-0 flex-1 truncate">{item.course.title}</span>
                                            <span className="shrink-0 font-medium">
                                                {item.course.price_type === 'free' ? 'Gratis' : formatPrice(item.course.price)}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            )}

                            <div
                                className="mt-4 flex justify-between border-t pt-4 font-bold"
                                style={{ borderColor: 'rgba(0,0,0,0.06)', color: '#1A1A1A' }}
                            >
                                <span>Total</span>
                                <span style={{ color: BRAND }}>
                                    {selectedTotal > 0 ? formatPrice(selectedTotal) : selectedItems.length > 0 ? 'Gratis' : 'Rp 0'}
                                </span>
                            </div>

                            {selectedIds.size > 0 ? (
                                <Link
                                    href={checkoutUrl}
                                    className="mt-5 flex w-full items-center justify-center rounded-xl py-3 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0"
                                    style={{ backgroundColor: BRAND, boxShadow: '0 4px 16px rgba(17,138,178,0.28)' }}
                                >
                                    Checkout ({selectedIds.size} kelas)
                                </Link>
                            ) : (
                                <button
                                    disabled
                                    className="mt-5 flex w-full cursor-not-allowed items-center justify-center rounded-xl py-3 text-sm font-semibold text-white opacity-40"
                                    style={{ backgroundColor: BRAND }}
                                >
                                    Pilih kelas dulu
                                </button>
                            )}

                            <Link
                                href="/courses"
                                className="mt-3 flex w-full items-center justify-center rounded-xl py-2.5 text-sm font-medium transition-colors hover:bg-gray-50"
                                style={{ color: '#777777' }}
                            >
                                Tambah kelas lain
                            </Link>
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}

function CartCard({
    item,
    selected,
    onToggle,
    onRemove,
    dimmed = false,
}: {
    item: CartItem;
    selected?: boolean;
    onToggle?: () => void;
    onRemove: () => void;
    dimmed?: boolean;
}) {
    return (
        <div
            className="overflow-hidden rounded-2xl transition-all"
            style={{
                border: selected
                    ? `1.5px solid ${BRAND}`
                    : '1px solid rgba(0,0,0,0.07)',
                backgroundColor: '#FFFFFF',
                opacity: dimmed ? 0.6 : 1,
                boxShadow: selected
                    ? '0 2px 12px rgba(17,138,178,0.12)'
                    : '0 1px 8px rgba(0,0,0,0.04)',
            }}
        >
            <div className="flex gap-4 p-4">
                {/* Checkbox for selectable items */}
                {!dimmed && onToggle && (
                    <div className="flex shrink-0 items-center">
                        <input
                            type="checkbox"
                            checked={selected ?? false}
                            onChange={onToggle}
                            className="h-4 w-4 cursor-pointer rounded border-gray-300"
                            style={{ accentColor: BRAND }}
                        />
                    </div>
                )}

                {item.course.thumbnail ? (
                    <img
                        src={item.course.thumbnail}
                        alt={item.course.title}
                        className="h-20 w-32 shrink-0 rounded-xl object-cover"
                    />
                ) : (
                    <div
                        className="flex h-20 w-32 shrink-0 items-center justify-center rounded-xl"
                        style={{ backgroundColor: 'rgba(17,138,178,0.08)' }}
                    >
                        <GraduationCap className="h-8 w-8" style={{ color: 'rgba(17,138,178,0.3)' }} />
                    </div>
                )}

                <div className="min-w-0 flex-1">
                    <Link
                        href={`/courses/${item.course.slug}`}
                        className="block font-semibold leading-snug transition-colors hover:underline"
                        style={{ color: '#1A1A1A' }}
                    >
                        {item.course.title}
                    </Link>
                    <p className="mt-0.5 text-sm" style={{ color: '#888888' }}>
                        {item.course.instructor.name} · {levelLabels[item.course.level] ?? item.course.level}
                    </p>
                    <p className="mt-1 text-xs" style={{ color: '#AAAAAA' }}>
                        <BookOpen className="mr-1 inline h-3.5 w-3.5" />
                        {item.course.lessons_count} lesson
                    </p>

                    {item.is_enrolled && (
                        <span
                            className="mt-2 inline-block rounded-full px-2.5 py-0.5 text-xs font-semibold"
                            style={{ backgroundColor: 'rgba(6,214,160,0.12)', color: '#059669' }}
                        >
                            Sudah terdaftar
                        </span>
                    )}
                </div>

                <div className="flex shrink-0 flex-col items-end justify-between">
                    <button
                        onClick={onRemove}
                        className="flex h-8 w-8 items-center justify-center rounded-lg transition-colors hover:bg-red-50"
                        style={{ color: '#CCCCCC' }}
                        onMouseEnter={(e) => (e.currentTarget.style.color = '#EF4444')}
                        onMouseLeave={(e) => (e.currentTarget.style.color = '#CCCCCC')}
                    >
                        <Trash2 className="h-4 w-4" />
                    </button>
                    <span className="font-bold" style={{ color: item.course.price_type === 'free' ? '#06D6A0' : '#1A1A1A' }}>
                        {item.course.price_type === 'free' ? 'Gratis' : formatPrice(item.course.price)}
                    </span>
                </div>
            </div>
        </div>
    );
}

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