'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, mutate } = useSWR(
    `/api/orders?waiter=${id}`,
    fetcher,
    {
      refreshInterval: 1000,
    }
  );

  const update_finished = (o: number, i: number, v: boolean) => {
    const d = data;
    d[o].data[i].finished = v;
    fetch(`/api/orders?id=${d[o].id}`, {
      method: 'PUT',
      body: JSON.stringify(d[o]),
      headers: {
        'Content-Type': 'application/json',
      },
    }).then(() => mutate(d));
  };

  const update_status = (o: number, v: number) => {
    const d = data;
    d[o].status = v;
    fetch(`/api/orders?id=${d[o].id}`, {
      method: 'PUT',
      body: JSON.stringify(d[o]),
      headers: {
        'Content-Type': 'application/json',
      },
    }).then(() => mutate(d));
  };

  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, oi: number) => (
          <li
            key={order.id}
            className={`m-2 p-2 rounded-md border-2 ${getOrderBg(order)}`}
          >
            <OrderID order={order} />
            <h2 className="text-xl">{order.waiter_name}</h2>
            { (order.client) ? <h2 className="text-xl">Klient: {order.client}</h2> : <></>}
            <h3>
              <select
                value={order.status}
                onChange={(e) =>
                  update_status(oi, e.target.value as unknown as number)
                }
                className="form border-2 my-2 border-gray-500"
              >
                {/* <option value="1">Zamówienie złożone</option> */}
                <option value="2">Zamówienie w trakcie przygotowywania</option>
                <option value="3">Zamówienie gotowe</option>
                {/* <option value="4">Zamówienie zrealizowane</option> */}
              </select>
            </h3>
            <div className="">
              <ul>
                {order.data.map((dish, i) => (
                  <li
                    key={dish.item}
                    className={`p-2 m-2 flex gap-4 border-2 ${getDishBg(dish)}`}
                  >
                    <input
                      type="checkbox"
                      checked={dish.finished}
                      onChange={(e) => update_finished(oi, i, e.target.checked)}
                    />
                    <div>
                      <p className="text-lg">{dish.item}{dish.times > 1 ? ` - x${dish.times}`: ''} - {dish.takeout ? 'Na wynos' : 'Na miejscu'}</p>
                      <div>{dish.additional_info}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}
