Spaces:
Running

File size: 13,228 Bytes
f287aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useMemo, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import { Fish, AlertCircle } from "lucide-react";
import { FishInventoryBatch } from "../types";
import { mockTanks } from "../mockData";

interface AllocateFishToTankProps {
  batch: FishInventoryBatch;
  isOpen: boolean;
  onClose: () => void;
  onAllocate: (
    batchId: string,
    tankId: string,
    quantity: number,
    avgWeight: number,
    stockingDate: string,
    notes?: string,
  ) => void;
  farmId: string;
  availableTanks?: any[];
}

interface FormErrors {
  tank?: string;
  quantity?: string;
  avgWeight?: string;
  stockingDate?: string;
  notes?: string;
}

const MAX_NOTES_LENGTH = 500;

export default function AllocateFishToTank({
  batch,
  isOpen,
  onClose,
  onAllocate,
  farmId,
  availableTanks = [],
}: AllocateFishToTankProps) {
  const todayDate = new Date().toISOString().split("T")[0];

  const [selectedTankId, setSelectedTankId] = useState<string>("");
  const [quantity, setQuantity] = useState<string>("");
  const [avgWeight, setAvgWeight] = useState<string>(
    String(batch.averageWeight ?? 0),
  );
  const [stockingDate, setStockingDate] = useState<string>(todayDate);
  const [notes, setNotes] = useState<string>("");
  const [errors, setErrors] = useState<FormErrors>({});

  useEffect(() => {
    setAvgWeight(String(batch.averageWeight ?? 0));
  }, [batch.id, batch.averageWeight]);

  const normalizeTank = (tank: any) => {
    const id = tank?.id || tank?._id;
    if (!id) return null;

    return {
      id: String(id),
      name: String(tank?.name || `Tank ${String(id).slice(0, 6)}`),
      farmId: String(tank?.farmId || ""),
      status: String(tank?.status || "UNKNOWN").toUpperCase(),
      biomass: Number(tank?.biomass?.actual ?? tank?.biomass ?? 0),
      capacity: Number(
        tank?.biomass?.capacity ?? tank?.capacity ?? tank?.biomassLimit ?? 0,
      ),
    };
  };

  const tanks = useMemo(() => {
    const source = availableTanks.length > 0 ? availableTanks : mockTanks;
    const normalized = source.map(normalizeTank).filter(Boolean) as Array<{
      id: string;
      name: string;
      farmId: string;
      status: string;
      biomass: number;
      capacity: number;
    }>;

    return normalized.filter((tank) => {
      const farmMatch = !farmId || tank.farmId === farmId;
      const isEmpty = tank.biomass <= 0;
      return farmMatch && isEmpty;
    });
  }, [availableTanks, farmId]);

  const validateForm = () => {
    const newErrors: FormErrors = {};

    if (tanks.length === 0) {
      newErrors.tank = "No allocatable tanks available";
    }

    if (!selectedTankId) {
      newErrors.tank = "Please select a tank";
    } else if (!tanks.some((tank) => tank.id === selectedTankId)) {
      newErrors.tank = "Selected tank is not valid";
    }

    const parsedQuantity = Number(quantity);
    if (!quantity || Number.isNaN(parsedQuantity)) {
      newErrors.quantity = "Please enter a valid quantity";
    } else if (!Number.isInteger(parsedQuantity) || parsedQuantity <= 0) {
      newErrors.quantity = "Quantity must be a whole number greater than zero";
    } else if (parsedQuantity > batch.quantity) {
      newErrors.quantity = `Quantity cannot exceed ${batch.quantity.toLocaleString()} fish`;
    }

    const parsedAvgWeight = Number(avgWeight);
    if (avgWeight === "" || Number.isNaN(parsedAvgWeight)) {
      newErrors.avgWeight = "Please enter average weight";
    } else if (parsedAvgWeight < 0) {
      newErrors.avgWeight = "Average weight cannot be negative";
    } else if (parsedAvgWeight > 10000) {
      newErrors.avgWeight = "Average weight is too high";
    }

    if (!stockingDate) {
      newErrors.stockingDate = "Please select a stocking date";
    } else if (stockingDate > todayDate) {
      newErrors.stockingDate = "Stocking date cannot be in the future";
    }

    if (notes.length > MAX_NOTES_LENGTH) {
      newErrors.notes = `Notes cannot exceed ${MAX_NOTES_LENGTH} characters`;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = () => {
    if (!validateForm()) return;

    onAllocate(
      batch.id,
      selectedTankId,
      Number(quantity),
      Number(avgWeight),
      stockingDate,
      notes.trim() || undefined,
    );

    handleClose();
  };

  const handleClose = () => {
    setSelectedTankId("");
    setQuantity("");
    setAvgWeight(String(batch.averageWeight ?? 0));
    setStockingDate(todayDate);
    setNotes("");
    setErrors({});
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent
        className="max-w-2xl p-0 h-[90vh] max-h-[90vh] overflow-hidden gap-0"
        style={{ display: "flex", flexDirection: "column" }}
      >
        <div className="h-full flex flex-col" style={{ minHeight: 0 }}>
          <DialogHeader className="px-6 pt-6 pb-3 shrink-0 border-b">
            <DialogTitle className="text-2xl flex items-center gap-2">
              <Fish className="w-6 h-6 text-[#0A4D68]" />
              Allocate Fish to Tank
            </DialogTitle>
          </DialogHeader>

          <div
            className="allocate-modal-scroll px-6 py-4 space-y-6 pb-8"
            style={{ flex: 1, minHeight: 0 }}
          >
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <div className="bg-blue-100 p-2 rounded-lg">
                  <Fish className="w-5 h-5 text-[#0A4D68]" />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <p className="text-sm font-bold text-gray-700">
                      Inventory Batch
                    </p>
                    <span className="text-[10px] text-gray-400 font-mono">
                      ID: {batch.id.split("-")[0]}
                    </span>
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <p className="text-xs text-gray-600">Species</p>
                      <p className="font-medium">{batch.species}</p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-600">Available</p>
                      <p className="font-medium">
                        {batch.quantity.toLocaleString()} fish
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="tank">
                Select Tank <span className="text-red-500">*</span>
              </Label>
              <Select value={selectedTankId} onValueChange={setSelectedTankId}>
                <SelectTrigger
                  id="tank"
                  className={errors.tank ? "border-red-500" : ""}
                >
                  <SelectValue placeholder="Choose a tank..." />
                </SelectTrigger>
                <SelectContent>
                  {tanks.map((tank) => (
                    <SelectItem key={tank.id} value={tank.id}>
                      {tank.name}
                    </SelectItem>
                  ))}
                  {tanks.length === 0 && (
                    <SelectItem value="__no_tanks__" disabled>
                      No available tanks for allocation
                    </SelectItem>
                  )}
                </SelectContent>
              </Select>
              {errors.tank && (
                <p className="text-xs text-red-600">{errors.tank}</p>
              )}
              {tanks.length === 0 && (
                <p className="text-xs text-orange-600">
                  No allocatable tanks found. Tank must be in ACTIVE, READY, or
                  EMPTY status.
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="avgWeight">
                Avg Weight (g) <span className="text-red-500">*</span>
              </Label>
              <Input
                id="avgWeight"
                type="number"
                value={avgWeight}
                onChange={(e) => {
                  setAvgWeight(e.target.value);
                  if (errors.avgWeight) {
                    setErrors({ ...errors, avgWeight: undefined });
                  }
                }}
                placeholder="Enter average weight in grams"
                className={errors.avgWeight ? "border-red-500" : ""}
                min="0"
                step="0.01"
              />
              {errors.avgWeight && (
                <p className="text-xs text-red-600 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" />
                  {errors.avgWeight}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="quantity">
                Quantity to Stock <span className="text-red-500">*</span>
              </Label>
              <div className="relative">
                <Input
                  id="quantity"
                  type="number"
                  value={quantity}
                  onChange={(e) => {
                    setQuantity(e.target.value);
                    if (errors.quantity) {
                      setErrors({ ...errors, quantity: undefined });
                    }
                  }}
                  placeholder="Enter number of fish"
                  className={errors.quantity ? "border-red-500" : ""}
                  min="1"
                  step="1"
                  max={batch.quantity}
                />
                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">
                  fish
                </span>
              </div>
              {errors.quantity && (
                <p className="text-xs text-red-600 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" />
                  {errors.quantity}
                </p>
              )}
              {quantity && !errors.quantity && Number(quantity) > 0 && (
                <p className="text-xs text-gray-600">
                  Remaining in inventory:{" "}
                  <span className="font-medium">
                    {(batch.quantity - Number(quantity)).toLocaleString()} fish
                  </span>
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="stockingDate">
                Stocking Date <span className="text-red-500">*</span>
              </Label>
              <Input
                id="stockingDate"
                type="date"
                value={stockingDate}
                onChange={(e) => {
                  setStockingDate(e.target.value);
                  if (errors.stockingDate) {
                    setErrors({ ...errors, stockingDate: undefined });
                  }
                }}
                max={todayDate}
                className={errors.stockingDate ? "border-red-500" : ""}
              />
              <p className="text-xs text-gray-500">Default: Today</p>
              {errors.stockingDate && (
                <p className="text-xs text-red-600">{errors.stockingDate}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="notes">Notes (optional)</Label>
              <Textarea
                id="notes"
                value={notes}
                onChange={(e) => {
                  setNotes(e.target.value);
                  if (errors.notes) {
                    setErrors({ ...errors, notes: undefined });
                  }
                }}
                placeholder="Add any additional notes..."
                rows={3}
                className={errors.notes ? "border-red-500" : ""}
              />
              <div className="flex items-center justify-between">
                <p className="text-xs text-gray-500">
                  {notes.length}/{MAX_NOTES_LENGTH}
                </p>
                {errors.notes && (
                  <p className="text-xs text-red-600">{errors.notes}</p>
                )}
              </div>
            </div>
          </div>

          <div className="shrink-0 border-t px-6 py-4 bg-background flex items-center justify-end gap-3">
            <Button variant="outline" onClick={handleClose}>
              Cancel
            </Button>
            <Button
              onClick={handleSubmit}
              className="bg-[#0A4D68] hover:bg-[#083d52]"
            >
              <Fish className="w-4 h-4 mr-2" />
              Stock Tank
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}