<script setup lang="ts">
import { Copy, MessageCircle, Share2 } from '@lucide/vue';
import { computed, ref } from 'vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { share } from '@/routes/admin/manage/cuttings';
import type { CuttingListItem } from '@/types/cutting';

const props = defineProps<{
    cutting: CuttingListItem;
    tooltip?: string;
    disabled?: boolean;
}>();

const open = ref(false);
const copied = ref(false);

const shareLink = computed(() => {
    return window.location.origin + share.url(props.cutting.id);
});

const whatsappText = computed(() => {
    const c = props.cutting;
    let text = `*Cutting #${c.id}*\n`;
    text += `Status: ${c.status_label}\n`;
    text += `Tanggal: ${c.created_at_formatted}\n`;
    text += `Oleh: ${c.created_by?.profile?.full_name ?? c.created_by?.username ?? '-'}\n`;

    if (c.description) {
        text += `Deskripsi: ${c.description}\n`;
    }

    if (c.results?.length) {
        const productNames = new Set<string>();

        c.results.forEach((result) => {
            const productName = result.product_variant?.product?.name ?? 'Produk Tidak Diketahui';
            productNames.add(productName);
        });

        text += `\nNama Produk: ${Array.from(productNames).join(', ')}\n`;
    }

    text += `Total Hasil Cutting: ${c.total_result_pieces ?? 0} pcs\n`;
    text += `\nLihat detail lengkap:\n${shareLink.value}`;

    return text;
});

async function copyLink() {
    try {
        await navigator.clipboard.writeText(shareLink.value);
        copied.value = true;
        toast.success('Link berhasil disalin');
        setTimeout(() => {
            copied.value = false;
        }, 2000);
        open.value = false;
    } catch {
        toast.error('Gagal menyalin link');
    }
}

function shareViaWhatsApp() {
    const encodedText = encodeURIComponent(whatsappText.value);
    const url = `https://wa.me/?text=${encodedText}`;
    window.open(url, '_blank');
    open.value = false;
}
</script>

<template>
    <Tooltip>
        <Popover v-model:open="open">
            <TooltipTrigger as-child>
                <PopoverTrigger as-child>
                    <Button variant="ghost" size="icon" class="size-8" :disabled="disabled">
                        <Share2 class="size-4" />
                        <span class="sr-only">{{ tooltip || 'Bagikan' }}</span>
                    </Button>
                </PopoverTrigger>
            </TooltipTrigger>

            <TooltipContent>{{ tooltip || 'Bagikan' }}</TooltipContent>

            <PopoverContent align="end" class="w-48 space-y-1 p-2">
                <Button variant="ghost" size="sm" class="w-full justify-start gap-2" @click="copyLink">
                    <Copy class="size-4" />
                    {{ copied ? 'Tersalin!' : 'Salin Link' }}
                </Button>
                <Button variant="ghost" size="sm" class="w-full justify-start gap-2" @click="shareViaWhatsApp">
                    <MessageCircle class="size-4" />
                    WhatsApp
                </Button>
            </PopoverContent>
        </Popover>
    </Tooltip>
</template>
