import { useEffect } from "react"; import { Controller, useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { useNavigate, useParams } from "react-router"; import { Alert, Box, Button, CircularProgress, FormControl, FormControlLabel, InputLabel, MenuItem, Paper, Select, Stack, Switch, TextField, Typography, } from "@mui/material"; import { assetSchema, type AssetFormValues } from "@/domain/assets/schemas/asset-schema"; import { useAssetDetail } from "@/domain/assets/use-cases/use-asset-detail"; import { useAssetFormOptions } from "@/domain/assets/use-cases/use-asset-form-options"; import { useCreateAsset } from "@/domain/assets/use-cases/use-create-asset"; import { useUpdateAsset } from "@/domain/assets/use-cases/use-update-asset"; const defaultValues: AssetFormValues = { assetCode: "", name: "", description: "", accountId: null, locationId: null, isActive: true, }; export default function AssetFormPage() { const { id } = useParams(); const navigate = useNavigate(); const isEdit = Boolean(id); const { data: asset, isLoading, error } = useAssetDetail(id); const { accounts, sites, isLoading: optionsLoading, error: optionsError } = useAssetFormOptions(); const createAsset = useCreateAsset(); const updateAsset = useUpdateAsset(); const { register, handleSubmit, reset, control, formState: { errors }, } = useForm({ resolver: zodResolver(assetSchema), defaultValues, }); useEffect(() => { if (asset && isEdit) { reset({ assetCode: asset.assetCode, name: asset.name, description: asset.description, accountId: asset.accountId, locationId: asset.locationId, isActive: asset.isActive, }); } }, [asset, isEdit, reset]); const isSaving = createAsset.isPending || updateAsset.isPending; const onSubmit = (values: AssetFormValues) => { if (isEdit && id) { updateAsset.mutate({ id, values }); return; } createAsset.mutate(values); }; if ((isEdit && isLoading) || optionsLoading) { return ( ); } return ( {isEdit ? "Edit Asset" : "Create Asset"} {Boolean(error || optionsError) && ( {error instanceof Error ? error.message : optionsError instanceof Error ? optionsError.message : "Failed to load asset"} )} ( Account )} /> ( Location )} /> ( } label="Active" /> )} /> ); }