import { Head, Link, usePage } from '@inertiajs/react';
import {
    ArrowUpRight,
    BadgeCheck,
    Boxes,
    Layers3,
    Package,
    PackageCheck,
    PackageX,
    Plus,
    Store,
    Tags,
    Warehouse,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { dashboard } from '@/routes';
import type { Auth } from '@/types';

type Totals = {
    stores: number;
    categories: number;
    brands: number;
    products: number;
};

type RecentProduct = {
    id: number;
    name: string;
    slug: string;
    price: string;
    stock: number;
    feature_image_url: string | null;
    is_active: boolean;
    created_at: string;
    store: { id: number; name: string };
    category: { id: number; name: string };
    brand: { id: number; name: string };
};

type PageProps = {
    auth: Auth;
    totals: Totals;
    active: Totals;
    inventory: {
        total_stock: number;
        low_stock: number;
        out_of_stock: number;
    };
    recentProducts: RecentProduct[];
};

const numberFormatter = new Intl.NumberFormat();

export default function Dashboard({
    totals,
    active,
    inventory,
    recentProducts,
}: PageProps) {
    const { auth } = usePage<PageProps>().props;
    const can = (permission: string) => auth.permissions.includes(permission);

    const statCards = [
        {
            label: 'Total stores',
            value: totals.stores,
            active: active.stores,
            href: '/stores',
            permission: 'stores.view',
            icon: Store,
            accent: 'from-violet-500/20 via-violet-500/5 to-transparent',
            iconStyle: 'bg-violet-500/10 text-violet-700 dark:text-violet-300',
        },
        {
            label: 'Categories',
            value: totals.categories,
            active: active.categories,
            href: '/categories',
            permission: 'categories.view',
            icon: Tags,
            accent: 'from-cyan-500/20 via-cyan-500/5 to-transparent',
            iconStyle: 'bg-cyan-500/10 text-cyan-700 dark:text-cyan-300',
        },
        {
            label: 'Brands',
            value: totals.brands,
            active: active.brands,
            href: '/brands',
            permission: 'brands.view',
            icon: BadgeCheck,
            accent: 'from-amber-500/20 via-amber-500/5 to-transparent',
            iconStyle: 'bg-amber-500/10 text-amber-700 dark:text-amber-300',
        },
        {
            label: 'Products',
            value: totals.products,
            active: active.products,
            href: '/products',
            permission: 'products.view',
            icon: Package,
            accent: 'from-emerald-500/20 via-emerald-500/5 to-transparent',
            iconStyle:
                'bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
        },
    ];

    const inventoryItems = [
        {
            label: 'Units in stock',
            value: inventory.total_stock,
            icon: Boxes,
            style: 'bg-blue-500/10 text-blue-700 dark:text-blue-300',
        },
        {
            label: 'Low-stock products',
            value: inventory.low_stock,
            icon: PackageCheck,
            style: 'bg-amber-500/10 text-amber-700 dark:text-amber-300',
        },
        {
            label: 'Out of stock',
            value: inventory.out_of_stock,
            icon: PackageX,
            style: 'bg-rose-500/10 text-rose-700 dark:text-rose-300',
        },
    ];

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <section className="relative overflow-hidden rounded-2xl border bg-slate-950 px-6 py-8 text-white shadow-xl shadow-slate-950/10 md:px-8">
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(34,211,238,0.2),transparent_35%),radial-gradient(circle_at_bottom_left,rgba(139,92,246,0.22),transparent_40%)]" />
                    <div className="absolute -top-20 right-10 size-56 rounded-full border border-white/10" />
                    <div className="absolute -right-12 -bottom-24 size-72 rounded-full border border-white/10" />

                    <div className="relative flex flex-col gap-6 md:flex-row md:items-end md:justify-between">
                        <div className="max-w-2xl space-y-3">
                            <div className="flex items-center gap-2 text-sm font-medium text-cyan-300">
                                <Warehouse className="size-4" />
                                Commerce overview
                            </div>
                            <h1 className="text-3xl font-semibold tracking-tight md:text-4xl">
                                Welcome back, {auth.user.name}
                            </h1>
                            <p className="max-w-xl text-sm leading-6 text-slate-300 md:text-base">
                                Monitor your catalog, inventory, stores, and
                                product structure from one clear workspace.
                            </p>
                        </div>

                        {can('products.create') && (
                            <Button
                                asChild
                                className="w-fit bg-white text-slate-950 hover:bg-slate-200"
                            >
                                <Link href="/products/create">
                                    <Plus />
                                    Add product
                                </Link>
                            </Button>
                        )}
                    </div>
                </section>

                <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    {statCards.map((card) => {
                        const content = (
                            <>
                                <div
                                    className={`absolute inset-0 bg-gradient-to-br ${card.accent}`}
                                />
                                <div className="relative flex items-start justify-between">
                                    <div
                                        className={`rounded-xl p-3 ${card.iconStyle}`}
                                    >
                                        <card.icon className="size-5" />
                                    </div>
                                    {can(card.permission) && (
                                        <ArrowUpRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
                                    )}
                                </div>
                                <div className="relative mt-7">
                                    <div className="text-3xl font-semibold tracking-tight">
                                        {numberFormatter.format(card.value)}
                                    </div>
                                    <div className="mt-1 text-sm font-medium">
                                        {card.label}
                                    </div>
                                    <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
                                        <span className="size-1.5 rounded-full bg-emerald-500" />
                                        {numberFormatter.format(card.active)}{' '}
                                        active
                                    </div>
                                </div>
                            </>
                        );

                        const className =
                            'group relative min-h-48 overflow-hidden rounded-2xl border bg-card p-5 shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md';

                        return can(card.permission) ? (
                            <Link
                                key={card.label}
                                href={card.href}
                                className={className}
                            >
                                {content}
                            </Link>
                        ) : (
                            <div key={card.label} className={className}>
                                {content}
                            </div>
                        );
                    })}
                </section>

                <section className="grid gap-6 xl:grid-cols-[1.5fr_0.75fr]">
                    <div className="overflow-hidden rounded-2xl border bg-card shadow-sm">
                        <div className="flex items-center justify-between gap-4 border-b px-5 py-4 md:px-6">
                            <div>
                                <h2 className="font-semibold">
                                    Recently added products
                                </h2>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    The latest items added to your catalog.
                                </p>
                            </div>
                            {can('products.view') && (
                                <Button variant="outline" size="sm" asChild>
                                    <Link href="/products">
                                        View all
                                        <ArrowUpRight />
                                    </Link>
                                </Button>
                            )}
                        </div>

                        <div className="divide-y">
                            {recentProducts.map((product) => (
                                <div
                                    key={product.id}
                                    className="flex items-center gap-4 px-5 py-4 transition-colors hover:bg-muted/40 md:px-6"
                                >
                                    <div className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-xl border bg-muted">
                                        {product.feature_image_url ? (
                                            <img
                                                src={product.feature_image_url}
                                                alt={product.name}
                                                className="size-full object-cover"
                                            />
                                        ) : (
                                            <Package className="size-5 text-muted-foreground" />
                                        )}
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <div className="truncate text-sm font-medium">
                                            {product.name}
                                        </div>
                                        <div className="mt-1 truncate text-xs text-muted-foreground">
                                            {product.brand.name} ·{' '}
                                            {product.category.name} ·{' '}
                                            {product.store.name}
                                        </div>
                                    </div>
                                    <div className="hidden text-right sm:block">
                                        <div className="text-sm font-medium">
                                            ${Number(product.price).toFixed(2)}
                                        </div>
                                        <div
                                            className={`mt-1 text-xs ${
                                                product.stock === 0
                                                    ? 'text-rose-600 dark:text-rose-400'
                                                    : product.stock <= 5
                                                      ? 'text-amber-600 dark:text-amber-400'
                                                      : 'text-muted-foreground'
                                            }`}
                                        >
                                            {product.stock} in stock
                                        </div>
                                    </div>
                                </div>
                            ))}

                            {recentProducts.length === 0 && (
                                <div className="flex flex-col items-center px-6 py-12 text-center">
                                    <div className="rounded-2xl bg-muted p-4">
                                        <Package className="size-6 text-muted-foreground" />
                                    </div>
                                    <h3 className="mt-4 font-medium">
                                        No products yet
                                    </h3>
                                    <p className="mt-1 text-sm text-muted-foreground">
                                        Add your first product to populate this
                                        dashboard.
                                    </p>
                                </div>
                            )}
                        </div>
                    </div>

                    <div className="rounded-2xl border bg-card p-5 shadow-sm md:p-6">
                        <div className="flex items-center gap-3">
                            <div className="rounded-xl bg-primary/10 p-3 text-primary">
                                <Layers3 className="size-5" />
                            </div>
                            <div>
                                <h2 className="font-semibold">
                                    Inventory health
                                </h2>
                                <p className="text-sm text-muted-foreground">
                                    Current product availability
                                </p>
                            </div>
                        </div>

                        <div className="mt-6 space-y-3">
                            {inventoryItems.map((item) => (
                                <div
                                    key={item.label}
                                    className="flex items-center gap-3 rounded-xl border p-4"
                                >
                                    <div
                                        className={`rounded-lg p-2.5 ${item.style}`}
                                    >
                                        <item.icon className="size-4" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <div className="text-sm text-muted-foreground">
                                            {item.label}
                                        </div>
                                        <div className="mt-0.5 text-xl font-semibold">
                                            {numberFormatter.format(item.value)}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </section>
            </div>
        </>
    );
}

Dashboard.layout = {
    breadcrumbs: [
        {
            title: 'Dashboard',
            href: dashboard(),
        },
    ],
};
