"use client";

import { deleteSampleItem, useSampleItems } from "@/hooks/use-sample-items";
import { Suspense } from "react";
import Image from 'next/image';
import Link from "next/link";
import Loader from '../../components/ui/loader.svg';

export default function Sample() {
  const formatDate = (date: Date) =>
    Intl.DateTimeFormat("en-US").format(new Date(date));
  let refreshData: any;

  const DeleteButton = (itemId: any) => {
    return (
      <button 
        className="button deleteBtn"
        value="Delete"
        onClick={async () => {await deleteSampleItem(itemId.itemId); refreshData()}}
      >
        Delete
      </button>
    );
  };

  const ItemsData = () => {
    const { items, error, isLoading, mutate } = useSampleItems();
    refreshData = mutate;
    if (!isLoading && !error && items != null) {
      return items.map((item) => (
        <tr key={item.id}>
          <td>
            <Link href={`sample/${item.id}`}>{item.testName}</Link>
          </td>
          <td>{item.statusCode}</td>
          <td>{item.numValue}</td>
          <td>{formatDate(item.createdAt)}</td>
          <td>
            <div className="flex flex-nowrap">
              <Link className="button editBtn" href={`sample/${item.id}`}>
                  Edit
              </Link>
              <DeleteButton itemId={item.id}></DeleteButton>
            </div>
          </td>
        </tr>
      ));
    } else return Loading();
  };

  const Loading = () => (
    <tr>
      <td className="flex align-items-end" colSpan={5}><Image src={Loader} alt='Loading' width={62} />Loading</td>
    </tr>
  );
  return (

      <div id="container" className="flex align-items-start place-content-center">
        <div>
        <table>
          <thead>
            <tr>
              <th colSpan={5}>
                <Link className="button" href={`sample/create`}>
                    <span>Add new</span>
                </Link>
              </th>
            </tr>
            <tr>
              <th>Name</th>
              <th>Status</th>
              <th>Value</th>
              <th>Created At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <Suspense fallback={Loading()}>
              <ItemsData></ItemsData>
            </Suspense>
          </tbody>
        </table>
        </div>
        {process.env.PUBLIC_API_URL}
      </div>
      

  );
}
