"use client";
import { Dispatch, SetStateAction, useMemo, useState } from "react";
import { FaTimes } from "react-icons/fa";
import { FaCalendarPlus, FaCartShopping, FaWarehouse } from "react-icons/fa6";
import { IoFilter, IoFilterCircleOutline, IoFilterOutline, IoToday } from "react-icons/io5";
// import { Artefact } from "@appTypes/Prisma";
import type { Artefact } from "@prismaclient";
// Warehouse Artefacts Data
const warehouseArtefacts: Artefact[] = [
{
id: 1,
name: "Solidified Lava Chunk",
description: "A chunk of solidified lava from the 2023 Iceland eruption.",
location: "Reykjanes, Iceland",
code: "EQ2023ICL",
isRequired: true,
isSold: false,
isCollected: false,
dateAdded: "2025-05-04",
},
{
id: 2,
name: "Tephra Sample",
description: "Foreign debris from the 2022 Tonga volcanic eruption.",
location: "Tonga",
code: "EQ2022TGA",
isRequired: false,
isSold: true,
isCollected: true,
dateAdded: "2025-05-03",
},
{
id: 3,
name: "Ash Sample",
description: "Volcanic ash from the 2021 La Palma eruption.",
location: "La Palma, Spain",
code: "EQ2021LPA",
isRequired: false,
isSold: false,
isCollected: false,
dateAdded: "2025-05-04",
},
{
id: 4,
name: "Ground Soil",
description: "Soil sample from the 2020 Croatia earthquake site.",
location: "Zagreb, Croatia",
code: "EQ2020CRO",
isRequired: true,
isSold: false,
isCollected: false,
dateAdded: "2025-05-02",
},
{
id: 5,
name: "Basalt Fragment",
description: "Basalt rock from the 2019 New Zealand eruption.",
location: "White Island, New Zealand",
code: "EQ2019NZL",
isRequired: false,
isSold: true,
isCollected: false,
dateAdded: "2025-05-04",
},
];
// Filter Component
function FilterInput({
value,
onChange,
type = "text",
options,
}: {
value: string;
onChange: (value: string) => void;
type?: string;
options?: string[];
}) {
const showSelectedFilter = type === "text" && !["true", "false"].includes(options?.at(-1)!);
return (
{options ? (
{options.map((opt) => (
onChange(opt)}>
{opt ? (opt === "true" ? "Yes" : "No") : "All"}
))}
) : (
onChange(e.target.value)}
className="w-full p-1 border border-neutral-300 rounded-md text-sm"
placeholder="Filter..."
aria-label="Filter input"
/>
)}
{value && showSelectedFilter && (
{value === "true" ? "Yes" : value === "false" ? "No" : value}
onChange("")} />
)}
);
}
// Table Component
function ArtefactTable({
artefacts,
filters,
setFilters,
setEditArtefact,
clearSort,
}: {
artefacts: Artefact[];
filters: Record;
setFilters: Dispatch>>;
setEditArtefact: (artefact: Artefact) => void;
clearSort: () => void;
}) {
const [sortConfig, setSortConfig] = useState<{
key: keyof Artefact;
direction: "asc" | "desc";
} | null>(null);
const handleSort = (key: keyof Artefact) => {
setSortConfig((prev) => {
if (!prev || prev.key !== key) {
return { key, direction: "asc" };
} else if (prev.direction === "asc") {
return { key, direction: "desc" };
}
return null;
});
};
const clearSortConfig = () => {
setSortConfig(null);
clearSort();
};
const sortedArtefacts = useMemo(() => {
if (!sortConfig) return artefacts;
const sorted = [...artefacts].sort((a, b) => {
const aValue = a[sortConfig.key];
const bValue = b[sortConfig.key];
if (aValue < bValue) return sortConfig.direction === "asc" ? -1 : 1;
if (aValue > bValue) return sortConfig.direction === "asc" ? 1 : -1;
return 0;
});
return sorted;
}, [artefacts, sortConfig]);
const columns: { label: string; key: keyof Artefact; width: string }[] = [
{ label: "ID", key: "id", width: "5%" },
{ label: "Name", key: "name", width: "12%" },
{ label: "Earthquake ID", key: "earthquakeId", width: "10%" },
{ label: "Location", key: "location", width: "12%" },
{ label: "Description", key: "description", width: "25%" },
{ label: "Required", key: "isRequired", width: "6%" },
{ label: "Sold", key: "isSold", width: "5%" },
{ label: "Collected", key: "isCollected", width: "7%" },
{ label: "Date Added", key: "dateAdded", width: "8%" },
];
return (
{columns.map(({ label, key, width }) => (
handleSort(key as keyof Artefact)}>
{label}
{
setFilters({ ...filters, [key]: value } as Record);
if (value === "") clearSortConfig();
}}
type={key === "dateAdded" ? "date" : "text"}
options={["isRequired", "isSold", "isCollected"].includes(key) ? ["", "true", "false"] : undefined}
/>
{sortConfig?.key === key && (
{sortConfig.direction === "asc" ? "↑" : "↓"}
)}
|
))}
{sortedArtefacts.map((artefact) => (
setEditArtefact(artefact)}
>
{columns.map(({ key, width }) => (
|
{key === "isRequired"
? artefact.isRequired
? "Yes"
: "No"
: key === "isSold"
? artefact.isSold
? "Yes"
: "No"
: key === "isCollected"
? artefact.isCollected
? "Yes"
: "No"
: artefact[key]}
|
))}
))}
);
}
// Modal Component for Logging Artefact
function LogModal({ onClose }: { onClose: () => void }) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [location, setLocation] = useState("");
const [earthquakeId, setEarthquakeId] = useState("");
const [storageLocation, setStorageLocation] = useState("");
const [isRequired, setIsRequired] = useState(true);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
if (e.target === e.currentTarget) {
onClose();
}
};
const handleLog = async () => {
if (!name || !description || !location || !earthquakeId || !storageLocation) {
setError("All fields are required.");
return;
}
setIsSubmitting(true);
try {
await new Promise((resolve) => setTimeout(resolve, 500)); // Simulated API call
alert(`Logged ${name} to storage: ${storageLocation}`);
onClose();
} catch {
setError("Failed to log artefact. Please try again.");
} finally {
setIsSubmitting(false);
}
};
return (
Log New Artefact
{error &&
{error}
}
);
}
// Modal Component for Bulk Logging
function BulkLogModal({ onClose }: { onClose: () => void }) {
const [palletNote, setPalletNote] = useState("");
const [storageLocation, setStorageLocation] = useState("");
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
if (e.target === e.currentTarget) {
onClose();
}
};
const handleLog = async () => {
if (!palletNote || !storageLocation) {
setError("All fields are required.");
return;
}
setIsSubmitting(true);
try {
await new Promise((resolve) => setTimeout(resolve, 500)); // Simulated API call
alert(`Logged bulk pallet to storage: ${storageLocation}`);
onClose();
} catch {
setError("Failed to log pallet. Please try again.");
} finally {
setIsSubmitting(false);
}
};
return (
Log Bulk Pallet
{error &&
{error}
}
);
}
// Modal Component for Editing Artefact
function EditModal({ artefact, onClose }: { artefact: Artefact; onClose: () => void }) {
const [name, setName] = useState(artefact.name);
const [description, setDescription] = useState(artefact.description);
const [location, setLocation] = useState(artefact.location);
const [earthquakeId, setEarthquakeId] = useState(artefact.earthquakeId);
const [isRequired, setIsRequired] = useState(artefact.isRequired);
const [isSold, setIsSold] = useState(artefact.isSold);
const [isCollected, setIsCollected] = useState(artefact.isCollected);
const [dateAdded, setDateAdded] = useState(artefact.dateAdded);
const [error, setError] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOverlayClick = (e: { target: any; currentTarget: any }) => {
if (e.target === e.currentTarget) {
onClose();
}
};
const handleSave = async () => {
if (!name || !description || !location || !earthquakeId || !dateAdded) {
setError("All fields are required.");
return;
}
setIsSubmitting(true);
try {
await new Promise((resolve) => setTimeout(resolve, 500)); // Simulated API call
alert(`Updated artefact ${name}`);
onClose();
} catch {
setError("Failed to update artefact. Please try again.");
} finally {
setIsSubmitting(false);
}
};
return (
Edit Artefact
{error &&
{error}
}
);
}
// Filter Logic
const applyFilters = (artefacts: Artefact[], filters: Record): Artefact[] => {
return artefacts.filter((artefact) => {
return (
(filters.id === "" || artefact.id.toString().includes(filters.id)) &&
(filters.name === "" || artefact.name.toLowerCase().includes(filters.name.toLowerCase())) &&
(filters.earthquakeId === "" || artefact.earthquakeId.toLowerCase().includes(filters.earthquakeId.toLowerCase())) &&
(filters.location === "" || artefact.location.toLowerCase().includes(filters.location.toLowerCase())) &&
(filters.description === "" || artefact.description.toLowerCase().includes(filters.description.toLowerCase())) &&
(filters.isRequired === "" || (filters.isRequired === "true" ? artefact.isRequired : !artefact.isRequired)) &&
(filters.isSold === "" || (filters.isSold === "true" ? artefact.isSold : !artefact.isSold)) &&
(filters.isCollected === "" || (filters.isCollected === "true" ? artefact.isCollected : !artefact.isCollected)) &&
(filters.dateAdded === "" || artefact.dateAdded === filters.dateAdded)
);
});
};
// Warehouse Component
export default function Warehouse() {
const [currentPage, setCurrentPage] = useState(1);
const [showLogModal, setShowLogModal] = useState(false);
const [showBulkLogModal, setShowBulkLogModal] = useState(false);
const [editArtefact, setEditArtefact] = useState(null);
const [filters, setFilters] = useState>({
id: "",
name: "",
earthquakeId: "",
location: "",
description: "",
isRequired: "",
isSold: "",
isCollected: "",
dateAdded: "",
});
const [isFiltering, setIsFiltering] = useState(false);
const [sortConfig, setSortConfig] = useState<{
key: keyof Artefact;
direction: "asc" | "desc";
} | null>(null);
const artefactsPerPage = 10;
const indexOfLastArtefact = currentPage * artefactsPerPage;
const indexOfFirstArtefact = indexOfLastArtefact - artefactsPerPage;
// Apply filters with loading state
const filteredArtefacts = useMemo(() => {
setIsFiltering(true);
const result = applyFilters(warehouseArtefacts, filters);
setIsFiltering(false);
return result;
}, [filters]);
const currentArtefacts = filteredArtefacts.slice(indexOfFirstArtefact, indexOfLastArtefact);
// Overview stats
const totalArtefacts = warehouseArtefacts.length;
const today = "2025-05-04";
const artefactsAddedToday = warehouseArtefacts.filter((a) => a.dateAdded === today).length;
const artefactsSoldToday = warehouseArtefacts.filter((a) => a.isSold && a.dateAdded === today).length;
const clearFilters = () => {
setFilters({
id: "",
name: "",
earthquakeId: "",
location: "",
description: "",
isRequired: "",
isSold: "",
isCollected: "",
dateAdded: "",
});
setSortConfig(null); // Clear sorting
};
return (
{/* Main Content */}
{/* Overview Stats */}
Total Artefacts: {totalArtefacts}
Added Today: {artefactsAddedToday}
Sold Today: {artefactsSoldToday}
{/* Logging Buttons */}
{/* Table Card */}
{/* Modals */}
{showLogModal &&
setShowLogModal(false)} />}
{showBulkLogModal && setShowBulkLogModal(false)} />}
{editArtefact && setEditArtefact(null)} />}
);
}