'use client' import { useEffect, useMemo, useState } from 'react' import { trpc } from '@/lib/trpc/client' import { toast } from 'sonner' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Mail, Send, Eye } from 'lucide-react' interface Props { open: boolean onClose: () => void projectId: string projectTitle: string } function useDebounced(value: T, delayMs: number): T { const [debounced, setDebounced] = useState(value) useEffect(() => { const t = setTimeout(() => setDebounced(value), delayMs) return () => clearTimeout(t) }, [value, delayMs]) return debounced } export function ProjectEmailDialog({ open, onClose, projectId, projectTitle }: Props) { const initialBody = useMemo(() => `Hello ${projectTitle} team,\n\n`, [projectTitle]) const [subject, setSubject] = useState('') const [body, setBody] = useState(initialBody) const [showPreview, setShowPreview] = useState(false) // Reset state whenever the dialog opens for a new project useEffect(() => { if (open) { setSubject('') setBody(initialBody) setShowPreview(false) } }, [open, initialBody]) const debouncedSubject = useDebounced(subject, 300) const debouncedBody = useDebounced(body, 300) const recipientPreview = trpc.message.previewRecipients.useQuery( { recipientType: 'PROJECT_TEAM', recipientFilter: { projectId } }, { enabled: open } ) const emailPreview = trpc.message.previewEmail.useQuery( { subject: debouncedSubject, body: debouncedBody }, { enabled: showPreview && debouncedSubject.length > 0 && debouncedBody.length > 0 } ) const sendTestMutation = trpc.message.sendTest.useMutation({ onSuccess: ({ to }) => toast.success(`Test email sent to ${to}`), onError: (e) => toast.error(e.message), }) const sendMutation = trpc.message.send.useMutation({ onSuccess: () => { toast.success(`Email sent to ${recipientPreview.data?.totalApplicants ?? 0} team members`) onClose() }, onError: (e) => toast.error(e.message), }) const recipientCount = recipientPreview.data?.totalApplicants ?? 0 const canSend = subject.length > 0 && body.length > 0 && recipientCount > 0 return ( !v && onClose()}> Email Team — {projectTitle} Compose a custom email to all members of this project's team. {recipientPreview.isLoading ? ' Loading recipients…' : ` Will be sent to ${recipientCount} team member${recipientCount === 1 ? '' : 's'}.`}
setSubject(e.target.value)} placeholder="Subject of your email" maxLength={500} />