"use client"; import { useRouter } from "next/navigation"; import React, { useCallback, useEffect, useState, } from "react"; import { useTranslation } from "react-i18next"; import { Button, Stack, Typography, } from "@mui/material"; import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm, } from "react-hook-form"; import { Check, Close, RestartAlt } from "@mui/icons-material"; import { WarehouseInputs, createWarehouse, } from "@/app/api/warehouse/actions"; import WarehouseDetail from "./WarehouseDetail"; const CreateWarehouse: React.FC = () => { const { t } = useTranslation(["warehouse", "common"]); const formProps = useForm(); const router = useRouter(); const [serverError, setServerError] = useState(""); const resetForm = React.useCallback((e?: React.MouseEvent) => { e?.preventDefault(); e?.stopPropagation(); try { formProps.reset({ store_id: "", warehouse: "", area: "", slot: "", order: "", stockTakeSection: "", stockTakeSectionDescription: "", }); } catch (error) { console.log(error); setServerError(t("An error has occurred. Please try again later.")); } }, [formProps, t]); useEffect(() => { resetForm(); }, []); const handleCancel = () => { router.back(); }; const onSubmit = useCallback>( async (data) => { try { // Automatically append "F" to store_id if not already present // Remove any existing "F" to avoid duplication, then append it const cleanStoreId = (data.store_id || "").replace(/F$/i, "").trim(); const storeIdWithF = cleanStoreId ? `${cleanStoreId}F` : ""; // Generate code, name, description from the input fields // Format: store_idF-warehouse-area-slot (F is automatically appended) const code = storeIdWithF ? `${storeIdWithF}-${data.warehouse || ""}-${data.area || ""}-${data.slot || ""}` : `${data.warehouse || ""}-${data.area || ""}-${data.slot || ""}`; const name = storeIdWithF ? `${storeIdWithF}-${data.warehouse || ""}` : `${data.warehouse || ""}`; const description = storeIdWithF ? `${storeIdWithF}-${data.warehouse || ""}` : `${data.warehouse || ""}`; const warehouseData: WarehouseInputs = { ...data, store_id: storeIdWithF, // Save with F (F is automatically appended) code: code.trim(), name: name.trim(), description: description.trim(), capacity: 10000, // Default capacity }; await createWarehouse(warehouseData); router.replace("/settings/warehouse"); } catch (e) { console.log(e); const message = e instanceof Error ? e.message : t("An error has occurred. Please try again later."); setServerError(message); } }, [router, t], ); const onSubmitError = useCallback>( (errors) => { console.log(errors); }, [], ); return ( <> {serverError && ( {serverError} )} ); }; export default CreateWarehouse;