import type { Route } from "./+types/home";
import { useEffect, useState } from "react";
import "../../config.json";
import AddTransaction from "~/components/AddTransaction";

const API_URL = "http://localhost:2500";
type transaction = { id: number; tier: number; enchantment: number, type: string; silver: number; timestamp: number };

export function meta({}: Route.MetaArgs) {
  return [{ title: "Albion Online Transaction Tracker" }];
}

export default function Home() {
  return (
    <>
      <AddTransaction />
      <TransactionTable />
    </>
  );
}

function TransactionTable() {
  const [transactions, setTransactions] = useState<transaction[]>([]);

  useEffect(() => {
    fetch(`${API_URL}/transactions`)
      .then((response) => response.json())
      .then((data) => {console.log(data); setTransactions(data);});
  }, [API_URL]);

  return (
    <>
      <table>
        <thead>
          <tr>
            <th>Timestamp</th>
            <th>Tier</th>
            <th>Type</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          {transactions.map((transaction) => (
            <tr key={transaction.id}>
              <td>{new Date(transaction.timestamp*1000).toLocaleDateString()} {new Date(transaction.timestamp*1000).toLocaleTimeString()}</td>
              <td>{transaction.tier}.{transaction.enchantment}</td>
              <td>{transaction.type}</td>
              <td>{transaction.silver}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}
