import { useEffect, useState } from "react";
import { ListChecks } from "lucide-react";

import OmsorgCard from "../../components/OmsorgCard";
import { useAuth } from "../../app/AuthContext";
import { useValueListItems } from "../../app/useValueListItems";

const WIDGET_PAGE_SIZE = 200;

export default function OrderStatusWidget() {
  const { hasPermission } = useAuth();
  const canView = hasPermission("Orders", "View");
  const { items: statusItems } = useValueListItems("OrderStatus");

  const [orders, setOrders] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!canView) {
      return undefined;
    }

    let cancelled = false;

    async function load() {
      setIsLoading(true);
      const result = await window.omsorg.orders.list({ page: 1, pageSize: WIDGET_PAGE_SIZE });

      if (!cancelled) {
        setOrders(result.ok ? result.data?.items ?? [] : []);
        setIsLoading(false);
      }
    }

    load();
    return () => {
      cancelled = true;
    };
  }, [canView]);

  if (!canView) {
    return null;
  }

  const countByStatusId = new Map();
  for (const order of orders) {
    countByStatusId.set(order.statusId, (countByStatusId.get(order.statusId) ?? 0) + 1);
  }

  return (
    <OmsorgCard title="Auftragsstatus">
      <div className="contract-widget">
        <div className="contract-widget__intro">
          <ListChecks size={20} />

          <p>Aktuelle Aufträge nach Status in der Bearbeitungspipeline.</p>
        </div>

        {!isLoading && orders.length === 0 && <p>Keine Aufträge vorhanden.</p>}

        <div className="contract-widget__list">
          {statusItems.map((status) => (
            <article key={status.id} className="contract-item contract-item--info">
              <div className="contract-item__header">
                <div>
                  <strong>{status.value}</strong>
                </div>

                <strong>{countByStatusId.get(status.id) ?? 0}</strong>
              </div>
            </article>
          ))}
        </div>
      </div>
    </OmsorgCard>
  );
}
