'use client';

import { fetcher } from '@/app/api/tools';
import useSWR from 'swr';
import { useParams } from 'next/navigation';
import Link from 'next/link';

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: {
            id: number;
            created_on: string;
            updated_on: string;
            waiter: number;
            waiter_name: string;
            data: [
              { item: string; additional_info: string; finished: boolean }
            ];
            status: string;
            status_name: string;
          }) => (
            <li
              key={order.id}
              className={`m-2 p-2 rounded-md border-2 ${
                {
                  1: 'bg-red-200 border-red-400',
                  2: 'bg-purple-200 border-purple-400',
                  3: 'bg-green-200 border-green-400',
                  4: 'bg-gray-100 border-gray-400',
                }[order.status]
              }`}
            >
              <h1 className="text-xl">
                <span className="font-mono">
                  {'['}
                  {String(order.id % 1000).padStart(3, '0')}
                  {']'}
                </span>{' '}
                - {new Date(order.updated_on).toLocaleTimeString('pl-PL')}
              </h1>
              <h2 className="text-xl">{order.waiter_name}</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 bg-white border-2 border-gray-400"
                    >
                      <input type="checkbox" checked={dish.finished} readOnly />
                      <div>
                        <p className="text-lg">{dish.item}</p>
                        <div>{dish.additional_info}</div>
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            </li>
          )
        )}
      </ul>
    </>
  );
}
