<script setup lang="ts">
import { Layers, Minus, Plus, Search } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import PosCatalogCard from '@/components/catalog/PosCatalogCard.vue';
import PosCatalogVariantThumb from '@/components/catalog/PosCatalogVariantThumb.vue';
import MediaPreviewDialog from '@/components/media/MediaPreviewDialog.vue';
import { Badge } from '@/components/ui/badge';
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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { getFirstCoverImage } from '@/lib/catalog-cover';
import type { CuttingMaterialCartItem, CuttingRawMaterialCatalogItem } from '@/types/cutting';
import type { EnumOption } from '@/types/raw-material';
import CuttingPosCombinationDialog from './CuttingPosCombinationDialog.vue';
import type { CuttingCatalogPrice } from './useCuttingPosCart';

const props = defineProps<{
    filteredRawMaterials: CuttingRawMaterialCatalogItem[];
    rawMaterialCatalog: CuttingRawMaterialCatalogItem[];
    materialCart: CuttingMaterialCartItem[];
    getMaterialCartItem: (priceId: number) => CuttingMaterialCartItem | undefined;
    units: EnumOption[];
}>();

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

const allVariantImages = computed(() => {
    const list: { priceId: number; title: string; stock: string; url: string }[] = [];
    props.filteredRawMaterials.forEach((rawMaterial) => {
        rawMaterial.prices.forEach((price) => {
            if (price.images && price.images.length > 0) {
                list.push({
                    priceId: price.id,
                    title: `${rawMaterial.name} - ${price.variant}`,
                    stock: `Stok: ${price.stock_formatted}`,
                    url: price.images[0].url,
                });
            }
        });
    });

    return list;
});

const previewUrls = computed(() => allVariantImages.value.map((item) => item.url));

function handleThumbClick(priceId: number) {
    const idx = allVariantImages.value.findIndex((item) => item.priceId === priceId);

    if (idx !== -1) {
        previewUrl.value = allVariantImages.value[idx].url;
        previewTitle.value = allVariantImages.value[idx].title;
        previewStock.value = allVariantImages.value[idx].stock;
        previewOpen.value = true;
    }
}

watch(previewUrl, (newUrl) => {
    const matched = allVariantImages.value.find((item) => item.url === newUrl);

    if (matched) {
        previewTitle.value = matched.title;
        previewStock.value = matched.stock;
    }
});

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

const emit = defineEmits<{
    'add-material': [rawMaterial: CuttingRawMaterialCatalogItem, price: CuttingCatalogPrice];
    'decrease-material-qty': [priceId: number];
    'combination-created': [items: CuttingMaterialCartItem[]];
}>();

const combinationOpen = ref(false);
const combinationInitialVariant = ref<{
    rawMaterial: CuttingRawMaterialCatalogItem;
    price: CuttingCatalogPrice;
} | null>(null);

function openCombination(rawMaterial: CuttingRawMaterialCatalogItem, price: CuttingCatalogPrice) {
    combinationInitialVariant.value = { rawMaterial, price };
    combinationOpen.value = true;
}
</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 Bahan Baku</CardTitle>
        </CardHeader>
        <CardContent>
            <div class="space-y-4">
                <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
                    <div class="relative flex-1">
                        <Search class="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                        <Input v-model="materialSearch" placeholder="Cari varian..." class="pl-9" />
                    </div>
                    <div class="w-full sm:w-60">
                        <Select v-model="selectedRawMaterialId">
                            <SelectTrigger class="w-full">
                                <SelectValue placeholder="FIlter Bahan Baku" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">Filter Bahan Baku</SelectItem>
                                <SelectItem v-for="item in rawMaterialCatalog" :key="item.id" :value="String(item.id)">
                                    {{ item.name }}
                                </SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </div>

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

                <div v-else class="columns-1 gap-4 sm:columns-2 xl:columns-3">
                    <template v-for="rawMaterial in filteredRawMaterials" :key="rawMaterial.id">
                        <PosCatalogCard v-if="rawMaterial.prices.length > 0" :title="rawMaterial.name"
                            :cover-image="getFirstCoverImage(rawMaterial.prices)">
                            <template #header-extra>
                                <Badge variant="secondary" class="mt-1.5">
                                    {{ rawMaterial.unit_label }}
                                </Badge>
                            </template>

                            <p v-if="!rawMaterial.prices.length" class="px-3 py-4 text-sm text-muted-foreground">
                                Belum ada varian
                            </p>
                            <div v-for="price in rawMaterial.prices" :key="price.id"
                                class="flex items-center gap-2.5 px-3 py-2.5 transition-all duration-200" :class="[
                                    'cursor-pointer hover:bg-muted/30',
                                    getMaterialCartItem(price.id)
                                        ? 'mx-1 my-0.5 rounded-md border-2 border-primary bg-primary/5'
                                        : '',
                                ]" @click="!getMaterialCartItem(price.id) && emit('add-material', rawMaterial, price)">
                                <PosCatalogVariantThumb :items="price.images" custom-preview
                                    @click-thumb="handleThumbClick(price.id)" />
                                <div class="min-w-0 flex-1">
                                    <p class="truncate text-sm font-medium">
                                        {{ price.variant }}
                                    </p>
                                    <p class="text-xs tabular-nums text-muted-foreground">
                                        Stok: {{ price.stock_formatted }}
                                    </p>
                                </div>
                                <div v-if="getMaterialCartItem(price.id)" class="flex shrink-0 items-center gap-1">
                                    <Button type="button" variant="outline" size="icon-sm" title="Kurangi Pemakaian"
                                        @click.stop="emit('decrease-material-qty', price.id)">
                                        <Minus class="size-3.5" />
                                    </Button>
                                    <span class="min-w-5 text-center text-xs font-semibold tabular-nums">
                                        {{ getMaterialCartItem(price.id)!.material_usage }}
                                    </span>
                                    <Button type="button" variant="outline" size="icon-sm" title="Tambah ke Keranjang"
                                        @click.stop="emit('add-material', rawMaterial, price)">
                                        <Plus class="size-3.5" />
                                    </Button>
                                    <Button type="button" variant="default" size="icon-sm" title="Gunakan Kombinasi"
                                        @click.stop="openCombination(rawMaterial, price)">
                                        <Layers class="size-3.5" />
                                    </Button>
                                </div>
                                <div v-else class="flex shrink-0 items-center gap-1">
                                    <Button type="button" variant="outline" size="icon-sm" title="Tambah ke Keranjang"
                                        @click.stop="emit('add-material', rawMaterial, price)">
                                        <Plus class="size-3.5" />
                                    </Button>
                                    <Button type="button" variant="default" size="icon-sm" title="Gunakan Kombinasi"
                                        @click.stop="openCombination(rawMaterial, price)">
                                        <Layers class="size-3.5" />
                                    </Button>
                                </div>
                            </div>
                        </PosCatalogCard>
                    </template>
                </div>
            </div>
        </CardContent>
    </Card>



    <CuttingPosCombinationDialog v-model:open="combinationOpen" :raw-material-catalog="rawMaterialCatalog"
        :existing-cart-items="materialCart" :initial-variant="combinationInitialVariant"
        @combination-created="emit('combination-created', $event)" />

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