import {Stack, Typography, Box, Grid2 as Grid, Button, MenuItem, Select, FormControl, InputLabel} from '@mui/material' import {useShow} from '@refinedev/core' import {Show, TextFieldComponent as TextField} from '@refinedev/mui' import {useEffect, useState} from 'react' import axios from 'axios' import {BACKEND_URL} from '../../lib/constants' type SightItem = { id: number name: string latitude: number longitude: number city_id: number } export const StationShow = () => { const {query} = useShow({}) const {data, isLoading} = query const record = data?.data const [sights, setSights] = useState([]) const [linkedSights, setLinkedSights] = useState([]) const [selectedSightId, setSelectedSightId] = useState('') const [sightsLoading, setSightsLoading] = useState(true) useEffect(() => { if (record?.id) { axios .get(`${BACKEND_URL}/station/${record.id}/sight`) .then((response) => { setLinkedSights(response?.data || []) }) .catch(() => { setLinkedSights([]) }) } }, [record?.id]) useEffect(() => { axios .get(`${BACKEND_URL}/sight/`) // without "/" throws CORS error .then((response) => { setSights(response?.data || []) setSightsLoading(false) }) .catch(() => { setSights([]) setSightsLoading(false) }) }, []) const availableSights = sights.filter((sight) => !linkedSights.some((linked) => linked.id === sight.id)) const linkSight = () => { if (selectedSightId) { axios .post( `${BACKEND_URL}/station/${record?.id}/sight`, {sight_id: selectedSightId}, { headers: { accept: 'application/json', 'Content-Type': 'application/json', }, }, ) .then(() => { axios .get(`${BACKEND_URL}/station/${record?.id}/sight`) .then((response) => { setLinkedSights(response?.data || []) }) .catch(() => { setLinkedSights([]) }) }) .catch((error) => { console.error('Error linking sight:', error) }) } } const deleteSight = (sightId: number) => { axios .delete(`${BACKEND_URL}/station/${record?.id}/sight`, { data: {sight_id: sightId}, }) .then(() => { setLinkedSights((prevSights) => prevSights.filter((item) => item.id !== sightId)) }) .catch((error) => { console.error('Error deleting sight:', error) }) } const fields = [ {label: 'ID', data: 'id'}, {label: 'Name', data: 'name'}, {label: 'Latitude', data: 'latitude'}, {label: 'Longitude', data: 'longitude'}, {label: 'Description', data: 'description'}, ] const sightFields = [ {label: 'ID', data: 'id' as keyof SightItem}, {label: 'Name', data: 'name' as keyof SightItem}, {label: 'Latitude', data: 'latitude' as keyof SightItem}, {label: 'Longitude', data: 'longitude' as keyof SightItem}, {label: 'City ID', data: 'city_id' as keyof SightItem}, ] return ( {fields.map(({label, data}) => ( {label} ))} Linked Sights {sightsLoading ? ( Loading sights... ) : linkedSights.length > 0 ? ( linkedSights.map((sight, index) => ( {sightFields.map(({label, data}) => ( {label}: {sight?.[data]} ))} )) ) : ( No sights found )} Link Sight Sight ) }