'use client';

import { fetcher } from '@/app/api/tools';
import useSWR from 'swr';
import { useEffect, useRef, useState } from 'react';
import { getDishBg, getOrderBg, Order } from '../tools';
import { OrderID } from '../components';

export default function Home() {
  const audioRef = useRef({} as HTMLAudioElement);
  const [playedIDs, setPlayedIDs] = useState<number[]>([]);

  const { data, mutate, error, isLoading } = useSWR(`/api/orders`, fetcher, {
    refreshInterval: 1000,
  });

  const play = () => {
    if (audioRef.current) audioRef.current.play();
  };

  useEffect(() => {
    if (!data) return;

    const justPlayed = (data as Order[])
      .filter(
        (o) =>
          new Date(o.updated_on).getTime() - new Date(o.created_on).getTime() <
            10000 && o.status == 1
      )
      .map((o) => o.id)
      .filter((id) => !playedIDs.includes(id));

    if (justPlayed.length > 0) {
      play();
      setPlayedIDs(playedIDs.concat(justPlayed));
    }
  }, [playedIDs, data]);

  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 (
    <>
      <audio ref={audioRef} src="/ping.wav"></audio>
      <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>
    </>
  );
}
