<script setup lang="ts">
import { Minus, Plus, Search } from '@lucide/vue';
import { ref } from 'vue';
import PosCatalogCard from '@/components/catalog/PosCatalogCard.vue';
import PosCatalogVariantThumb from '@/components/catalog/PosCatalogVariantThumb.vue';
import MediaPreviewDialog from '@/components/media/MediaPreviewDialog.vue';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyTitle,
} from '@/components/ui/empty';
import { Input } from '@/components/ui/input';
import { getFirstCoverImage } from '@/lib/catalog-cover';
import type { RestockCartItem, RestockProductCatalogItem } from '@/types/restock';
import type { RestockCatalogVariant } from './useRestockPosCart';

const props = defineProps<{
    filteredProducts: RestockProductCatalogItem[];
    getCartItem: (variantId: number) => RestockCartItem | undefined;
    isCreateMode: boolean;
}>();

const previewOpen = ref(false);
const previewUrl = ref<string | null>(null);
const previewTitle = ref('');
const previewStock = ref('');

const productSearch = defineModel<string>('search', { required: true });

const emit = defineEmits<{
    'add-product': [product: RestockProductCatalogItem, variant: RestockCatalogVariant];
    'decrease-qty': [variantId: number];
}>();

function handleThumbClick(variantId: number) {
    for (const product of props.filteredProducts) {
        const variant = product.variants.find((v) => v.id === variantId);
        if (variant && variant.images && variant.images.length > 0) {
            previewUrl.value = variant.images[0].url;
            previewTitle.value = `${product.name} - ${variant.name}`;
            previewStock.value = `Stok: ${variant.stock} pcs`;
            previewOpen.value = true;
            break;
        }
    }
}
</script>

<template>
    <Card class="min-w-0">
        <CardHeader class="flex flex-row items-center justify-between pb-3 space-y-0">
            <CardTitle class="text-base">Pilih Produk</CardTitle>
        </CardHeader>
        <CardContent>
            <div class="space-y-4">
                <div class="relative">
                    <Search class="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                    <Input v-model="productSearch" placeholder="Cari produk..." class="pl-9" />
                </div>

                <div v-if="filteredProducts.length === 0" class="py-8">
                    <Empty>
                        <EmptyHeader>
                            <EmptyTitle>Tidak ada produk ditemukan</EmptyTitle>
                            <EmptyDescription>
                                Silakan lakukan pencarian untuk menemukan produk.
                            </EmptyDescription>
                        </EmptyHeader>
                    </Empty>
                </div>

                <div v-else class="columns-1 gap-4 sm:columns-2 xl:columns-3">
                    <PosCatalogCard v-for="product in filteredProducts" :key="product.id" :title="product.name"
                        :cover-image="getFirstCoverImage(product.variants)">
                        <p v-if="!product.variants.length" class="px-3 py-4 text-sm text-muted-foreground">
                            Belum ada varian
                        </p>
                        <div v-for="variant in product.variants" :key="variant.id"
                            class="flex items-center gap-2.5 px-3 py-2.5 transition-all duration-200" :class="[
                                'cursor-pointer hover:bg-muted/30',
                                getCartItem(variant.id)
                                    ? 'mx-1 my-0.5 rounded-md border-2 border-primary bg-primary/5'
                                    : '',
                            ]" @click="!getCartItem(variant.id) && emit('add-product', product, variant)">
                            <PosCatalogVariantThumb :items="variant.images" custom-preview
                                @click-thumb="handleThumbClick(variant.id)" />
                            <div class="min-w-0 flex-1">
                                <p class="truncate text-sm font-medium">
                                    {{ variant.name }}
                                </p>
                                <p class="text-xs text-muted-foreground">
                                    <span class="tabular-nums">Stok: {{ variant.stock }} pcs</span>
                                </p>
                            </div>
                            <div v-if="getCartItem(variant.id)" class="flex shrink-0 items-center gap-1.5">
                                <Button type="button" variant="outline" size="icon-sm"
                                    @click.stop="emit('decrease-qty', variant.id)">
                                    <Minus class="size-3.5" />
                                </Button>
                                <span class="min-w-5 text-center text-xs font-semibold tabular-nums">
                                    {{ getCartItem(variant.id)!.quantity }}
                                </span>
                                <Button type="button" variant="outline" size="icon-sm"
                                    @click.stop="emit('add-product', product, variant)">
                                    <Plus class="size-3.5" />
                                </Button>
                            </div>
                            <Button v-else type="button" variant="outline" size="icon-sm" class="shrink-0"
                                @click.stop="emit('add-product', product, variant)">
                                <Plus class="size-3.5" />
                            </Button>
                        </div>
                    </PosCatalogCard>
                </div>
            </div>
        </CardContent>
    </Card>

    <MediaPreviewDialog v-model:open="previewOpen" v-model:url="previewUrl" :title="previewTitle" :stocks="previewStock ? [previewStock] : []" />
</template>
