freshyo/apps/web-ui/src/components/ComplaintForm.tsx
2026-09-05 11:12:47 +05:30

168 lines
No EOL
5.5 KiB
TypeScript

import { useState, useRef } from 'react'
import { X, Upload, ImageIcon, Loader2 } from 'lucide-react'
import { trpc } from '../lib/trpc-client'
import { useUploadToObjectStorage } from '../hooks/useUploadToObjectStorage'
import type { ComplaintFormProps } from '@packages/shared'
interface ComplaintImage {
imgUrl: string
mimeType: string
file: File
}
export default function ComplaintForm({ open, onClose, orderId }: ComplaintFormProps) {
const [complaintBody, setComplaintBody] = useState('')
const [complaintImages, setComplaintImages] = useState<ComplaintImage[]>([])
const fileInputRef = useRef<HTMLInputElement>(null)
const raiseComplaintMutation = trpc.user.complaint.raise.useMutation()
const { refetch: refetchComplaints } = trpc.user.complaint.getAll.useQuery(undefined, {
enabled: false,
})
const { upload, isUploading } = useUploadToObjectStorage()
const handleAddImages = (files: FileList | null) => {
if (!files || files.length === 0) return
const newImages: ComplaintImage[] = []
Array.from(files).forEach((file) => {
if (!file.type.startsWith('image/')) return
newImages.push({
imgUrl: URL.createObjectURL(file),
mimeType: file.type || 'image/jpeg',
file,
})
})
setComplaintImages((prev) => [...prev, ...newImages])
}
const handleRemoveImage = (image: ComplaintImage) => {
setComplaintImages((prev) => {
URL.revokeObjectURL(image.imgUrl)
return prev.filter((item) => item.imgUrl !== image.imgUrl)
})
}
const handleSubmit = async () => {
if (!complaintBody.trim()) {
alert('Please enter complaint details')
return
}
try {
let imageUrls: string[] = []
if (complaintImages.length > 0) {
const uploadImages = complaintImages.map((image) => ({
blob: image.file,
mimeType: image.mimeType || 'image/jpeg',
}))
const { keys } = await upload({
images: uploadImages,
contextString: 'complaint',
})
imageUrls = keys
}
await raiseComplaintMutation.mutateAsync({
orderId: orderId.toString(),
complaintBody: complaintBody.trim(),
imageUrls,
})
await refetchComplaints()
alert('Complaint raised successfully')
setComplaintBody('')
setComplaintImages([])
onClose()
} catch (error: any) {
alert(error.message || 'Failed to raise complaint')
}
}
if (!open) return null
return (
<div className="p-6">
<div className="mb-4 flex flex-row items-center justify-between">
<p className="text-xl font-bold text-gray-900">Raise Complaint</p>
<button onClick={onClose}>
<X className="h-6 w-6 text-gray-400" />
</button>
</div>
<p className="mb-2 font-medium text-gray-700">Describe the issue</p>
<textarea
className="mb-4 min-h-32 w-full rounded-xl border border-gray-200 bg-gray-50 p-4 text-base text-gray-800"
value={complaintBody}
onChange={(e) => setComplaintBody(e.target.value)}
placeholder="Tell us what went wrong..."
rows={4}
/>
{/* Image uploader */}
<div className="mb-4">
<p className="mb-2 font-medium text-gray-700">Add images (optional)</p>
<div className="flex flex-row flex-wrap gap-3">
{complaintImages.map((image) => (
<div key={image.imgUrl} className="relative h-20 w-20 overflow-hidden rounded-xl border border-gray-200">
<img src={image.imgUrl} alt="complaint" className="h-full w-full object-cover" />
<button
onClick={() => handleRemoveImage(image)}
className="absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-full bg-black/60"
>
<X className="h-4 w-4 text-white" />
</button>
</div>
))}
<button
onClick={() => fileInputRef.current?.click()}
className="flex h-20 w-20 flex-col items-center justify-center rounded-xl border-2 border-dashed border-gray-300 hover:border-brand-500 hover:bg-gray-50"
>
<Upload className="h-5 w-5 text-gray-400" />
<span className="mt-1 text-[10px] font-medium text-gray-500">Add</span>
</button>
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
className="hidden"
onChange={(e) => {
handleAddImages(e.target.files)
e.target.value = ''
}}
/>
</div>
{complaintImages.length === 0 && (
<div className="mt-2 flex flex-row items-center">
<ImageIcon className="h-3.5 w-3.5 text-gray-400" />
<p className="ml-1 text-xs text-gray-400">No images selected</p>
</div>
)}
</div>
<button
className={`mt-2 flex w-full items-center justify-center gap-2 rounded-xl py-4 font-bold text-white shadow-sm transition-colors ${
raiseComplaintMutation.isPending || isUploading ? 'bg-yellow-400 opacity-70' : 'bg-yellow-500 hover:bg-yellow-600'
}`}
onClick={handleSubmit}
disabled={raiseComplaintMutation.isPending || isUploading}
>
{raiseComplaintMutation.isPending || isUploading ? (
<>
<Loader2 className="h-5 w-5 animate-spin" />
{isUploading ? 'Uploading...' : 'Submitting...'}
</>
) : (
'Submit Complaint'
)}
</button>
</div>
)
}