import { useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { useQuery, useMutation } from '@tanstack/react-query'; import { AdminLayout } from '@/components/layout/AdminLayout'; import { CommonNameForm } from '@/components/admin/CommonNameForm'; import { commonNamesApi, speciesApi, CommonName, Species } from '@/services/adminApi'; import { useToast } from '@/hooks/use-toast'; import { Button } from '@/components/ui/button'; import { ChevronLeft } from 'lucide-react'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { Label } from '@/components/ui/label'; export default function CreateCommonName() { const [isSubmitting, setIsSubmitting] = useState(false); const [searchParams] = useSearchParams(); const { toast } = useToast(); const [selectedSpeciesId, setSelectedSpeciesId] = useState( searchParams.get('species_id') ); const navigate = useNavigate(); // Fetch all species for the dropdown const { data: species, isLoading: speciesLoading } = useQuery({ queryKey: ['admin', 'species', 'all'], queryFn: async () => { const { data } = await speciesApi.getAll(1, 500); // Fetch up to 500 species return data; } }); // If a species_id was provided in the URL params, fetch that species details const { data: selectedSpecies } = useQuery({ queryKey: ['admin', 'species', selectedSpeciesId], queryFn: () => selectedSpeciesId ? speciesApi.getById(selectedSpeciesId) : null, enabled: !!selectedSpeciesId }); // Create common name mutation const createMutation = useMutation({ mutationFn: (data: CommonName) => commonNamesApi.create(data), onSuccess: () => { toast({ title: 'Success', description: 'Common name has been added successfully.', }); // Navigate back to species detail page if we came from there // if (selectedSpeciesId) { // navigate(`/admin/species/${selectedSpeciesId}`); // } else { // navigate('/admin/common-names'); // } }, onError: (error) => { toast({ variant: 'destructive', title: 'Error', description: `Failed to create common name: ${(error as Error).message}`, }); // setIsSubmitting(false); // Will be handled by onSettled }, onSettled: () => { setIsSubmitting(false); } }); const handleSubmit = (data: CommonName) => { setIsSubmitting(true); createMutation.mutate(data); }; const handleSpeciesChange = (value: string) => { setSelectedSpeciesId(value); }; return (

Add New Common Name

Create a new common name for a species

{/* Species selection dropdown (only if not pre-selected) */} {!searchParams.get('species_id') && (

Choose the species for this common name

)} {/* Only show the form if a species is selected */} {selectedSpeciesId ? (

{selectedSpecies ? ( <> New Common Name for {selectedSpecies.scientific_name} ) : ( 'New Common Name' )}

) : ( !searchParams.get('species_id') && (

Please select a species to continue

) )}
); }