import { router } from '@inertiajs/react';
import { Clock, Flame } from 'lucide-react';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';

export type StationOrderItem = {
    id: number;
    quantity: number;
    status: 'pending' | 'preparing' | 'ready' | 'served';
    notes: string | null;
    created_at: string;
    product: { id: number; name: string };
    order: {
        id: number;
        type: 'dine_in' | 'takeaway' | 'phone';
        is_priority: boolean;
        table: { id: number; number: string } | null;
    };
};

const statusLabels: Record<StationOrderItem['status'], string> = {
    pending: 'En attente',
    preparing: 'En préparation',
    ready: 'Prêt',
    served: 'Servi',
};

const nextStatus: Partial<
    Record<StationOrderItem['status'], StationOrderItem['status']>
> = {
    pending: 'preparing',
    preparing: 'ready',
    ready: 'served',
};

const actionLabels: Record<StationOrderItem['status'], string> = {
    pending: 'Commencer',
    preparing: 'Marquer prêt',
    ready: 'Marquer servi',
    served: 'Servi',
};

const typeLabels: Record<StationOrderItem['order']['type'], string> = {
    dine_in: 'Sur place',
    takeaway: 'À emporter',
    phone: 'Téléphone / WhatsApp',
};

function timeSince(createdAt: string): string {
    const minutes = Math.max(
        0,
        Math.round((Date.now() - new Date(createdAt).getTime()) / 60_000),
    );

    if (minutes < 1) return "à l'instant";
    if (minutes < 60) return `${minutes} min`;

    return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
}

export default function StationBoard({
    items,
    advanceUrl,
    emptyMessage,
}: {
    items: StationOrderItem[];
    advanceUrl: (item: StationOrderItem) => string;
    emptyMessage: string;
}) {
    const advance = (item: StationOrderItem) => {
        const target = nextStatus[item.status];
        if (!target) return;

        router.post(
            advanceUrl(item),
            { status: target },
            {
                preserveScroll: true,
                onError: (errors) =>
                    toast.error(errors.domain ?? 'Action impossible.'),
            },
        );
    };

    if (items.length === 0) {
        return <p className="text-muted-foreground text-sm">{emptyMessage}</p>;
    }

    return (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {items.map((item) => (
                <Card
                    key={item.id}
                    className={
                        item.order.is_priority
                            ? 'border-amber-400/60 bg-amber-50 dark:bg-amber-950/20'
                            : undefined
                    }
                >
                    <CardHeader className="flex-row items-start justify-between gap-2">
                        <div>
                            <CardTitle className="text-base">
                                {item.quantity}× {item.product.name}
                            </CardTitle>
                            <p className="text-muted-foreground text-xs">
                                {typeLabels[item.order.type]}
                                {item.order.table &&
                                    ` · Table ${item.order.table.number}`}
                            </p>
                        </div>
                        {item.order.is_priority && (
                            <Badge
                                variant="outline"
                                className="border-amber-500 text-amber-700 dark:text-amber-400"
                            >
                                <Flame className="size-3" />
                                Prioritaire
                            </Badge>
                        )}
                    </CardHeader>
                    <CardContent className="space-y-3">
                        {item.notes && (
                            <p className="text-muted-foreground text-sm italic">
                                « {item.notes} »
                            </p>
                        )}

                        <div className="text-muted-foreground flex items-center gap-1 text-xs">
                            <Clock className="size-3.5" />
                            {timeSince(item.created_at)}
                        </div>

                        <div className="flex items-center justify-between gap-2">
                            <Badge variant="secondary">
                                {statusLabels[item.status]}
                            </Badge>

                            {nextStatus[item.status] && (
                                <Button size="sm" onClick={() => advance(item)}>
                                    {actionLabels[item.status]}
                                </Button>
                            )}
                        </div>
                    </CardContent>
                </Card>
            ))}
        </div>
    );
}
