import { Head, Link } from '@inertiajs/react';
import {
    ArrowDown,
    ArrowLeft,
    ArrowRightLeft,
    ArrowUp,
    Loader2,
    Package,
    Pencil,
    ScrollText,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useInfiniteScroll } from '@/hooks/use-infinite-scroll';
import { formatNumber } from '@/lib/format';
import { index as productIndex } from '@/routes/admin/master/products';
import { stockMutations } from '@/routes/admin/master/products/variants';

type Mutation = {
    id: number;
    type: 'in' | 'out';
    quantity: number;
    stock_before: number;
    stock_after: number;
    stock_quality: string;
    description: string | null;
    created_at: string;
    user: {
        id: number;
        username: string;
        email: string;
        full_name?: string;
    };
};

type PaginatedMutations = {
    data: Mutation[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
};

type Props = {
    product: { id: number; name: string };
    variant: { id: number; name: string };
    mutations: PaginatedMutations;
};

function formatDate(dateStr: string): string {
    return new Intl.DateTimeFormat('id-ID', {
        day: 'numeric',
        month: 'long',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    }).format(new Date(dateStr));
}

function getQualityLabel(quality: string): string {
    const labels: Record<string, string> = {
        good: 'Bagus',
        reject: 'Reject',
        retail: 'Ecer',
    };

    return labels[quality] ?? quality;
}

function getQualityColor(quality: string): string {
    const colors: Record<string, string> = {
        good: 'bg-green-100 text-green-800',
        reject: 'bg-red-100 text-red-800',
        retail: 'bg-blue-100 text-blue-800',
    };

    return colors[quality] ?? 'bg-gray-100 text-gray-800';
}

function getTypeLabel(type: string, quantity: number): string {
    if (type === 'in') {
        return quantity >= 0 ? 'Penambahan' : 'Pengurangan';
    }

    return quantity < 0 ? 'Pengurangan' : 'Penambahan';
}

function getMutationTitle(description: string | null): string {
    if (!description) {
        return 'Perubahan Stok';
    }

    if (description.includes('Transfer stok')) {
        return 'Transfer Stok';
    }

    if (description.includes('Stok awal')) {
        return 'Stok Awal';
    }

    if (description.includes('Penyesuaian stok')) {
        return 'Edit Varian';
    }

    return 'Perubahan Stok';
}

function getMutationIcon(description: string | null): React.ReactNode {
    if (description?.includes('Transfer stok')) {
        return <ArrowRightLeft className="h-4 w-4" />;
    }

    if (description?.includes('Stok awal')) {
        return <Package className="h-4 w-4" />;
    }

    if (description?.includes('Penyesuaian stok')) {
        return <Pencil className="h-4 w-4" />;
    }

    return <ScrollText className="h-4 w-4" />;
}

export default function StockMutationsPage({
    product,
    variant,
    mutations,
}: Props) {
    const { items, loading, hasNextPage, sentinelRef } = useInfiniteScroll({
        initialData: mutations,
        fetchUrl: stockMutations.url({
            product: product.id,
            variant: variant.id,
        }),
    });

    return (
        <>
            <Head title="Mutasi Stok" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Mutasi Stok
                        </h2>
                        <p className="mt-1 text-sm text-muted-foreground">
                            {product.name} — {variant.name}
                        </p>
                    </div>
                    <Button asChild variant="outline">
                        <Link href={productIndex.url()}>
                            <ArrowLeft className="h-4 w-4" />
                            Kembali
                        </Link>
                    </Button>
                </div>

                <div className="grid gap-4">
                    {items.length === 0 && !loading ? (
                        <Card>
                            <CardContent className="flex flex-col items-center justify-center py-12">
                                <ScrollText className="h-12 w-12 text-muted-foreground/50" />
                                <p className="mt-4 text-sm text-muted-foreground">
                                    Belum ada mutasi stok.
                                </p>
                            </CardContent>
                        </Card>
                    ) : (
                        items.map((mutation) => {
                            const isPositive = mutation.quantity > 0;
                            const qualityColor = getQualityColor(
                                mutation.stock_quality,
                            );

                            return (
                                <Card key={mutation.id}>
                                    <CardContent className="p-4">
                                        <div className="flex items-start gap-4">
                                            <div
                                                className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full ${isPositive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}
                                            >
                                                {isPositive ? (
                                                    <ArrowUp className="h-5 w-5" />
                                                ) : (
                                                    <ArrowDown className="h-5 w-5" />
                                                )}
                                            </div>

                                            <div className="min-w-0 flex-1">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <span className="font-medium">
                                                        {getMutationTitle(
                                                            mutation.description,
                                                        )}
                                                    </span>
                                                    <span
                                                        className={`inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium ${qualityColor}`}
                                                    >
                                                        {getQualityLabel(
                                                            mutation.stock_quality,
                                                        )}
                                                    </span>
                                                </div>

                                                <div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
                                                    <span>
                                                        {formatDate(
                                                            mutation.created_at,
                                                        )}
                                                    </span>
                                                    <span>
                                                        {mutation.user
                                                            ?.full_name ??
                                                            mutation.user
                                                                ?.username}
                                                    </span>
                                                </div>

                                                <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
                                                    <span
                                                        className={
                                                            isPositive
                                                                ? 'font-medium text-green-600'
                                                                : 'font-medium text-red-600'
                                                        }
                                                    >
                                                        {isPositive ? '+' : ''}
                                                        {formatNumber(
                                                            mutation.quantity,
                                                        )}
                                                    </span>
                                                    <span className="text-muted-foreground">
                                                        {formatNumber(
                                                            mutation.stock_before,
                                                        )}{' '}
                                                        →{' '}
                                                        {formatNumber(
                                                            mutation.stock_after,
                                                        )}
                                                    </span>
                                                </div>

                                                {mutation.description && (
                                                    <p className="mt-1 text-xs text-muted-foreground">
                                                        {mutation.description}
                                                    </p>
                                                )}
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            );
                        })
                    )}

                    {hasNextPage && (
                        <div
                            ref={sentinelRef}
                            className="flex items-center justify-center py-4"
                        >
                            {loading && (
                                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                    <Loader2 className="h-4 w-4 animate-spin" />
                                    Memuat data...
                                </div>
                            )}
                        </div>
                    )}

                    {!hasNextPage && items.length > 0 && (
                        <p className="py-4 text-center text-sm text-muted-foreground">
                            Semua data sudah dimuat.
                        </p>
                    )}
                </div>
            </div>
        </>
    );
}
