import type { Route } from "./+types/home";
import { useEffect, useState } from 'react'
import Card from './components/card'

export function meta({}: Route.MetaArgs) {
  return [
    { title: "Index" }
  ];
}

interface TagInfo{
    name: string,
    price: number,
    sale: number
}

interface Peer{
    peer_id: number,
    last_online: number,
    tags: [TagInfo]
}


export default function Home(){
    const [Peers, setPeers] = useState<Peer[]>([])
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)

    useEffect(()=>{
        const fetchData = async () => {
            try{
                const response = await fetch('https://backend-service.docker.orb.local/list')
                if(!response.ok){
                    throw new Error('Network error')
                }
                const data = await response.json()
                setPeers(data)
            }catch(error){
                if(error instanceof Error){
                    setError(error.message)
                }else{
                    setError('Unknown error')
                }
            }finally{
                setLoading(false)
            }
        }
        fetchData()
    }, [])

    return (
        <>
            <h1>機器列表</h1>
            <div className="machine-list">
             {loading && <p>Loading...</p>}
             {error && <p>Error: {error}</p>}
             {!loading && !error && Peers.map(Peer=>{
                return Peer.tags.map(Tag=>{
                    return <Card key={Tag.name} name={Tag.name} status='1' metadata={Tag}/>
                })
             })}
            </div>
        </>
    )
}
