/* Copyright (C) 2024-2025 LibreWeddingPlanner contributors*/

'use client'

import { AbstractApi } from "@/app/api/abstract-api";
import { TableArrangementStatus } from "@/app/lib/definitions";
import { TableSimulation, TableSimulationSerializer } from "@/app/lib/tableSimulation";
import { getSlug } from "@/app/lib/utils";
import { Toast } from "primereact/toast";
import { useEffect, useRef, useState } from "react";
import { ProgressSpinner } from 'primereact/progressspinner';
import { classNames } from "../components/button";

export default function CalculatingSummary() {
  const [stats, setStats] = useState<{ [key in TableArrangementStatus]: number }>({
    in_progress: 0,
    completed: 0,
    not_started: 0,
  });

  const [inProgress, setInProgress] = useState<number[]>([]);

  useEffect(() => {
    const fetchStats = () => {
      fetch(`/api/${getSlug()}/tables_arrangements/stats`)
        .then((response) => response.json())
        .then((data) => {
          setStats(data.count);
          setInProgress(data.in_progress);
        });
    };

    fetchStats();
    const interval = setInterval(fetchStats, 10000);

    return () => clearInterval(interval);
  }, []);

  const toast = useRef<Toast>(null);

  function createSimulation() {
    const api = new AbstractApi<TableSimulation>();
    const serializer = new TableSimulationSerializer();
    api.create(serializer, new TableSimulation(), () => {
      toast.current?.show({
        severity: 'success',
        summary: 'Simulation created',
        detail: 'Table distributions will be calculated shortly, please come back in some minutes'
      });
    });
  }
  
  return (
    <>
      <Toast ref={toast} />
      <p className="text-lg font-semibold mb-4">Processing engine</p>
      <p>{stats.in_progress || 0 } processing</p>

      <div className="my-4">
          <div className="flex flex-row items-center gap-2">
        {inProgress.map((progress, index) => (
            <div key={index} className="relative size-16 flex items-center justify-center">
              <ProgressSpinner className="size-16" strokeWidth="4" animationDuration={`${Math.random() * 2 + 2}s`} />
              <span className="absolute text-s">
              {Math.round(progress * 100)}%
              </span>
            </div>
        ))}
          </div>
      </div>

      <p>+{stats.not_started || 0 } in queue</p>

      <div className="flex justify-center">
        <button onClick={createSimulation} className={classNames('primary')}>Add new</button>
      </div>
    </>
  );
}