'use client';

import { fetcher } from '@/app/api/tools';
import useSWR from 'swr';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';

type Order = {
  id: number;
  created_on: string;
  updated_on: string;
  waiter: number;
  waiter_name: string;
  data: [{ item: string; additional_info: string; finished: boolean }];
  status: number;
  status_name: string;
};

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();
    } else {
      // Throw error
    }
  };

  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));
    }
  }, [data]);

  const update_finished = (o: number, i: number, v: boolean) => {
    let d = data;
    d[o].data[i].finished = v;
    console.log(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) => {
    let d = data;
    d[o].status = v;
    console.log(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 ${
              {
                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>
              <select
                value={order.status}
                onChange={(e) =>
                  update_status(oi, e.target.value as unknown as number)
                }
                className="form border-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 skończone</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 bg-white border-gray-400`}
                  >
                    <input
                      type="checkbox"
                      checked={dish.finished}
                      onChange={(e) => update_finished(oi, i, e.target.checked)}
                    />
                    <div>
                      <p className="text-lg">{dish.item}</p>
                      <div>{dish.additional_info}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        ))}
      </ul>
    </>
  );
}
