-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScrapMaterials.tsx
More file actions
458 lines (427 loc) · 19.3 KB
/
ScrapMaterials.tsx
File metadata and controls
458 lines (427 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import React from 'react';
import Navbar from "@/components/Navbar";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useState, useEffect } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/lib/supabaseClient";
import { Upload, Camera, CheckCircle, Search as SearchIcon } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { useAuth } from "@/hooks/useAuth"; // Import useAuth
import ScrapMaterialDetailModal from "@/components/ScrapMaterialDetailModal"; // Import the new modal component
interface ScrapMaterial {
id: string;
title: string;
description: string;
category: string;
price: number;
image_urls: string[];
created_at: string;
quality: "poor";
surplus_price?: number;
scrap_price?: number;
currency?: string;
}
const ScrapMaterials = () => {
const { toast } = useToast();
const { user } = useAuth(); // Get the authenticated user
// State for Sell Scrap form
const [sellTitle, setSellTitle] = useState("");
const [sellDescription, setSellDescription] = useState("");
const [sellCategory, setSellCategory] = useState("");
const [sellPrice, setSellPrice] = useState("");
const [sellSurplusPrice, setSellSurplusPrice] = useState("");
const [sellScrapPrice, setSellScrapPrice] = useState("");
const [sellFiles, setSellFiles] = useState<FileList | null>(null);
const [sellLoading, setSellLoading] = useState(false);
const [isSellSubmitted, setIsSellSubmitted] = useState(false);
// State for Buy Scrap search and listings
const [searchMaterial, setSearchMaterial] = useState("");
const [searchCategory, setSearchCategory] = useState("all");
const [scrapListings, setScrapListings] = useState<ScrapMaterial[]>([]);
const [buyLoading, setBuyLoading] = useState(true);
const [buyError, setBuyError] = useState<string | null>(null);
// State for detail modal
const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
const [selectedMaterialId, setSelectedMaterialId] = useState<string | null>(null);
const handleOpenDetailModal = (id: string) => {
setSelectedMaterialId(id);
setIsDetailModalOpen(true);
};
const handleCloseDetailModal = () => {
setIsDetailModalOpen(false);
setSelectedMaterialId(null);
};
const handleSellFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
setSellFiles(e.target.files);
}
};
const handleSubmitSell = async (e: React.FormEvent) => {
e.preventDefault();
setSellLoading(true);
if (!user) {
toast({
title: "Error",
description: "You must be logged in to list scrap materials.",
variant: "destructive",
});
setSellLoading(false);
return;
}
if (!sellFiles || sellFiles.length === 0) {
toast({
title: "Error",
description: "Please upload at least one image.",
variant: "destructive",
});
setSellLoading(false);
return;
}
try {
const imageUrls: string[] = [];
for (let i = 0; i < sellFiles.length; i++) {
const file = sellFiles[i];
const fileExt = file.name.split(".").pop();
const fileName = `${Date.now()}-${Math.random()}.${fileExt}`;
const filePath = `scrap_material_images/${fileName}`;
const { error: uploadError } = await supabase.storage
.from("material-loop-images") // Assuming this bucket is used for all materials
.upload(filePath, file);
if (uploadError) {
throw uploadError;
}
const { data: publicUrlData } = supabase.storage
.from("material-loop-images")
.getPublicUrl(filePath);
if (publicUrlData) {
imageUrls.push(publicUrlData.publicUrl);
}
}
const { error: insertError } = await supabase
.from("scrap_materials_poor_quality") // New table for poor quality scrap
.insert([
{
title: sellTitle,
description: sellDescription,
category: sellCategory,
price: parseFloat(sellPrice),
image_urls: imageUrls,
quality: "poor", // Explicitly set quality to poor
user_id: user.id, // Include the user's ID
surplus_price: sellSurplusPrice ? parseFloat(sellSurplusPrice) : null,
scrap_price: sellScrapPrice ? parseFloat(sellScrapPrice) : null,
},
]);
if (insertError) {
throw insertError;
}
setIsSellSubmitted(true);
toast({
title: "Scrap Material Listed Successfully!",
description: "Your scrap material is now available for buyers.",
});
// Clear form
setSellTitle("");
setSellDescription("");
setSellCategory("");
setSellPrice("");
setSellSurplusPrice("");
setSellScrapPrice("");
setSellFiles(null);
} catch (error: unknown) {
let errorMessage = "An unknown error occurred.";
if (error instanceof Error) {
errorMessage = error.message;
}
console.error("Error listing scrap material:", errorMessage);
toast({
title: "Error listing scrap material",
description: errorMessage,
variant: "destructive",
});
} finally {
setSellLoading(false);
}
};
const fetchScrapMaterials = async () => {
setBuyLoading(true);
setBuyError(null);
try {
let query = supabase
.from("scrap_materials_poor_quality")
.select("*")
.eq("quality", "poor"); // Ensure only poor quality is fetched
if (searchMaterial) {
query = query.ilike("title", `%${searchMaterial}%`);
}
if (searchCategory && searchCategory !== "all") {
query = query.eq("category", searchCategory);
}
const { data, error } = await query;
if (error) {
throw error;
}
setScrapListings(data as ScrapMaterial[]);
} catch (error: unknown) {
let errorMessage = "Failed to load scrap materials. Please try again later.";
if (error instanceof Error) {
errorMessage = error.message;
}
console.error("Error fetching scrap materials:", errorMessage);
setBuyError(errorMessage);
} finally {
setBuyLoading(false);
}
};
useEffect(() => {
fetchScrapMaterials();
}, [searchMaterial, searchCategory]); // Refetch when search/category changes
if (isSellSubmitted) {
return (
<div className="min-h-screen bg-background">
<Navbar />
<div className="container py-20">
<div className="max-w-2xl mx-auto text-center">
<div className="w-20 h-20 rounded-full bg-success/10 flex items-center justify-center mx-auto mb-6">
<CheckCircle className="h-10 w-10 text-success" />
</div>
<h1 className="text-4xl font-bold mb-4">Scrap Material Listed Successfully!</h1>
<p className="text-xl text-muted-foreground mb-8">
Your scrap material is now available for buyers.
</p>
<div className="flex gap-4 justify-center">
<Button onClick={() => setIsSellSubmitted(false)} variant="outline">
List Another
</Button>
<Button className="bg-cta text-cta-foreground hover:bg-cta/90">
View My Scrap Listings
</Button>
</div>
</div>
</div>
</div>
);
}
return (
<React.Fragment>
<div className="min-h-screen">
<Navbar />
<section className="py-20 bg-muted/30">
<div className="container">
<div className="text-center mb-12">
<h1 className="text-4xl font-bold mb-4">Scrap Materials Exchange</h1>
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
Buy and sell poor quality scrap materials to promote recycling and sustainable practices.
</p>
</div>
<Tabs defaultValue="buy" className="w-full max-w-4xl mx-auto">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="buy">Buy Scrap</TabsTrigger>
<TabsTrigger value="sell">Sell Scrap</TabsTrigger>
</TabsList>
<TabsContent value="buy">
<Card className="card-lift">
<CardHeader>
<CardTitle>Find Scrap Materials</CardTitle>
</CardHeader>
<CardContent>
<form className="space-y-4" onSubmit={(e) => { e.preventDefault(); fetchScrapMaterials(); }}>
<div>
<Label htmlFor="searchMaterial">Search Material</Label>
<Input
id="searchMaterial"
placeholder="e.g., Scrap Metal"
value={searchMaterial}
onChange={(e) => setSearchMaterial(e.target.value)}
/>
</div>
<div>
<Label htmlFor="searchCategory">Category</Label>
<Select value={searchCategory} onValueChange={setSearchCategory}>
<SelectTrigger>
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Categories</SelectItem>
<SelectItem value="metal">Metal</SelectItem>
<SelectItem value="plastic">Plastic</SelectItem>
<SelectItem value="glass">Glass</SelectItem>
<SelectItem value="wood">Wood</SelectItem>
<SelectItem value="tile">Tile</SelectItem>
<SelectItem value="brick">Brick</SelectItem>
<SelectItem value="other">Other</SelectItem>
</SelectContent>
</Select>
</div>
<Button type="submit" className="w-full" disabled={buyLoading}>
<SearchIcon className="mr-2 h-4 w-4" />
Search
</Button>
</form>
<div className="mt-6 space-y-4">
<h3 className="text-xl font-semibold">Available Scrap Listings</h3>
{buyLoading && (
<div className="grid grid-cols-1 gap-4">
{[...Array(3)].map((_, i) => (
<Skeleton key={i} className="h-[120px] w-full rounded-xl" />
))}
</div>
)}
{buyError && (
<div className="text-center text-destructive text-lg mt-4">
{buyError}
</div>
)}
{!buyLoading && !buyError && scrapListings.length === 0 && (
<div className="text-center text-muted-foreground text-lg mt-4">
No scrap materials found.
</div>
)}
{!buyLoading && !buyError && scrapListings.length > 0 && (
<div className="grid grid-cols-1 gap-4">
{scrapListings.map((material) => (
<Card key={material.id}>
<CardContent className="p-4">
<h4 className="font-bold">{material.title}</h4>
<p className="text-sm text-muted-foreground">Category: {material.category} | Price: ₹{material.price}/unit</p>
<p className="text-sm">Description: {material.description}</p>
{material.image_urls && material.image_urls.length > 0 && (
<img src={material.image_urls[0]} alt={material.title} className="w-24 h-24 object-cover rounded-md mt-2" />
)}
<Button variant="outline" size="sm" className="mt-2" onClick={() => handleOpenDetailModal(material.id)}>View Details</Button>
</CardContent>
</Card>
))}
</div>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="sell">
{/* The existing Sell Scrap form */}
<Card className="card-lift">
<CardHeader>
<CardTitle>List Your Scrap Material</CardTitle>
</CardHeader>
<CardContent>
<form className="space-y-4" onSubmit={handleSubmitSell}>
{/* Images Upload */}
<div className="bg-card rounded-2xl p-6 border border-border">
<Label className="text-lg font-semibold mb-4 block">Material Photos</Label>
<div className="border-2 border-dashed border-border rounded-xl p-12 text-center hover:border-accent transition-colors cursor-pointer">
<input
type="file"
id="sell-file-upload"
multiple
accept="image/*"
onChange={handleSellFileChange}
className="hidden"
/>
<label htmlFor="sell-file-upload" className="cursor-pointer">
<Camera className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-lg font-medium mb-2">Upload Photos</p>
<p className="text-sm text-muted-foreground mb-4">
Add at least 3 photos showing different angles.
</p>
<Button type="button" variant="outline" onClick={() => document.getElementById('sell-file-upload')?.click()}>
<Upload className="mr-2 h-5 w-5" />
Choose Files ({sellFiles ? sellFiles.length : 0} selected)
</Button>
</label>
</div>
</div>
<div>
<Label htmlFor="sellTitle">Material Name</Label>
<Input
id="sellTitle"
placeholder="e.g., Broken Glass, Rusty Metal"
value={sellTitle}
onChange={(e) => setSellTitle(e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="sellDescription">Description</Label>
<Textarea
id="sellDescription"
placeholder="Provide details about the material, quantity, and condition (poor quality)"
value={sellDescription}
onChange={(e) => setSellDescription(e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="sellCategory">Category</Label>
<Select value={sellCategory} onValueChange={setSellCategory} required>
<SelectTrigger id="sellCategory">
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
<SelectItem value="metal">Metal</SelectItem>
<SelectItem value="plastic">Plastic</SelectItem>
<SelectItem value="glass">Glass</SelectItem>
<SelectItem value="wood">Wood</SelectItem>
<SelectItem value="tile">Tile</SelectItem>
<SelectItem value="brick">Brick</SelectItem>
<SelectItem value="other">Other</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="sellPrice">Price (per unit/kg)</Label>
<Input
id="sellPrice"
type="number"
placeholder="e.g., 50.00"
value={sellPrice}
onChange={(e) => setSellPrice(e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="sellSurplusPrice">Surplus Price (for comparison)</Label>
<Input
id="sellSurplusPrice"
type="number"
placeholder="e.g., 100.00"
value={sellSurplusPrice}
onChange={(e) => setSellSurplusPrice(e.target.value)}
/>
</div>
<div>
<Label htmlFor="sellScrapPrice">Scrap Price (for comparison)</Label>
<Input
id="sellScrapPrice"
type="number"
placeholder="e.g., 50.00"
value={sellScrapPrice}
onChange={(e) => setSellScrapPrice(e.target.value)}
/>
</div>
<Button type="submit" className="w-full bg-cta text-cta-foreground hover:bg-cta/90" disabled={sellLoading}>
{sellLoading ? "Listing Material..." : "List Material"}
</Button>
</form>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
</section>
</div>
<ScrapMaterialDetailModal
isOpen={isDetailModalOpen}
onClose={handleCloseDetailModal}
materialId={selectedMaterialId}
/>
</React.Fragment>
);
};
export default ScrapMaterials;