'use client';

import { fetcher } from '@/app/api/tools';
import useSWR from 'swr';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { getDishBg, getOrderBg, Order } from '@/app/tools';
import { OrderID } from '@/app/components';

export default function Home() {
  const { id } = useParams();
  const { data, error, isLoading } = useSWR(
    `/api/orders?waiter=${id}`,
    fetcher,
    {
      refreshInterval: 1000,
    }
  );

  if (error) return <div>Błąd przy ładowaniu danych</div>;
  if (isLoading) return <div>Ładowanie</div>;

  return (
    <>
      <p className="text-lg">
        <Link href={`/waiter/${id}/new`}>
          <button>Nowe zamówienie</button>
        </Link>
      </p>
      <p className="text-4xl">Zamówienia:</p>
      <ul className="max-w-screen-md w-full">
        {data?.map((order: Order) => (
          <li
            key={order.id}
            className={`m-2 p-2 rounded-md border-2 ${getOrderBg(order)}`}
          >
            <OrderID order={order} />
            <h2 className="text-xl">Kelner: {order.waiter_name}</h2>
            { (order.client) ? <h2 className="text-xl">Klient: {order.client}</h2> : <></>}
            <h3>{order.status_name}</h3>
            <div className="">
              <ul>
                {order.data.map((dish) => (
                  <li
                    key={dish.item}
                    className={`p-2 m-2 flex gap-4 border-2 ${getDishBg(dish)}`}
                  >
                    <input type="checkbox" checked={dish.finished} readOnly />
                    <div>
                      <p className="text-lg">{dish.item} - {dish.takeout ? 'Na wynos' : 'Na miejscu'}</p>
                      <div>{dish.additional_info}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}
