'use client'; import { OrderItem, PurchaseOrder } from '@/lib/types'; import { pb } from '@/lib/pocketbase'; import { X, FileText, Share2, Mail, Check, AlertCircle, Copy, ExternalLink, } from 'lucide-react'; import { useState } from 'react'; interface ItemDetailModalProps { item: OrderItem; purchaseOrder: PurchaseOrder | null; isOpen: boolean; onClose: () => void; } // PocketBase's pb.files.getUrl expects a record object with id and // collectionId. We satisfy the contract with a typed inline object rather // than a broader `any` cast. function buildPoFileUrl(po: PurchaseOrder): string | null { if (!po.documents?.length) return null; const record = { id: po.id, collectionId: (po as unknown as { collectionId: string }).collectionId ?? '', }; return pb.files.getUrl(record, po.documents[0]); } function statusColor(status: string): string { switch (status.toLowerCase()) { case 'sent': case 'approved': return 'bg-[#e6f1ec] text-[#125a3e]'; case 'pending': return 'bg-[#fcf3d8] text-[#8a5a02]'; case 'cancelled': return 'bg-[#fbeaef] text-[#8a1b3a]'; default: return 'bg-[#ebeae5] text-[#26251e]'; } } export default function ItemDetailModal({ item, purchaseOrder, isOpen, onClose, }: ItemDetailModalProps) { const [copied, setCopied] = useState(false); const [sharing, setSharing] = useState(false); if (!isOpen) return null; const poUrl = purchaseOrder ? buildPoFileUrl(purchaseOrder) : null; const supplier = item.expand?.supplier; const hasNotes = Boolean(item.notes?.trim()); const handleShare = async () => { if (!poUrl || !purchaseOrder) return; setSharing(true); try { if (navigator.share) { await navigator.share({ title: `Purchase Order ${purchaseOrder.po_number}`, text: `Purchase Order ${purchaseOrder.po_number} for ${supplier?.suppliername ?? 'your order'}`, url: poUrl, }); } else { await navigator.clipboard.writeText(poUrl); setCopied(true); setTimeout(() => setCopied(false), 2500); } } catch (err) { if ((err as Error).name !== 'AbortError') { console.error('Share failed:', err); } } finally { setSharing(false); } }; const handleEmail = () => { if (!purchaseOrder?.email_payload) return; const { subject, bodyText } = purchaseOrder.email_payload; const bodyWithLink = poUrl ? `${bodyText}\n\nPDF Download: ${poUrl}` : bodyText; const mailto = `mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(bodyWithLink)}`; window.location.href = mailto; }; const handleCopyLink = async () => { if (!poUrl) return; try { await navigator.clipboard.writeText(poUrl); setCopied(true); setTimeout(() => setCopied(false), 2500); } catch { // clipboard may be blocked } }; return (
{/* Backdrop */} ); }