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

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

const WIDGET_PAGE_SIZE = 5;

function daysRemaining(followUpDueDate) {
  const due = new Date(followUpDueDate);
  const now = new Date();
  due.setHours(0, 0, 0, 0);
  now.setHours(0, 0, 0, 0);
  return Math.round((due - now) / (1000 * 60 * 60 * 24));
}

function badgeStatusFor(days) {
  if (days <= 7) {
    return "krank";
  }
  if (days <= 21) {
    return "urlaub";
  }
  return "einsatz";
}

function remainingLabel(days) {
  if (days < 0) {
    return `überfällig seit ${Math.abs(days)} Tag${Math.abs(days) === 1 ? "" : "en"}`;
  }
  if (days === 0) {
    return "fällig heute";
  }
  if (days === 1) {
    return "fällig morgen";
  }
  return `fällig in ${days} Tagen`;
}

export default function FollowUpWidget() {
  const { hasPermission } = useAuth();
  const canView = hasPermission("Facilities", "View");

  const [facilities, setFacilities] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

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

    let cancelled = false;

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

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

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

  if (!canView) {
    return null;
  }

  return (
    <OmsorgCard title="Fällige Wiedervorlagen">
      <div className="contract-widget">
        <div className="contract-widget__intro">
          <CalendarClock size={20} />

          <p>Einrichtungen, deren Wiedervorlage ansteht.</p>
        </div>

        {!isLoading && facilities.length === 0 && <p>Keine fälligen Wiedervorlagen.</p>}

        <div className="contract-widget__list">
          {facilities.map((facility) => {
            const days = daysRemaining(facility.followUpDueDate);
            const urgency = days <= 7 ? "danger" : days <= 21 ? "warning" : "info";

            return (
              <article key={facility.id} className={`contract-item contract-item--${urgency}`}>
                <div className="contract-item__header">
                  <div>
                    <strong>{facility.name}</strong>
                    <span>{facility.crmStatus}</span>
                  </div>

                  <OmsorgBadge status={badgeStatusFor(days)} />
                </div>

                <div className="contract-item__meta">
                  <span>
                    Wiedervorlage: {new Date(facility.followUpDueDate).toLocaleDateString("de-DE")}
                  </span>

                  <strong>{remainingLabel(days)}</strong>
                </div>
              </article>
            );
          })}
        </div>
      </div>
    </OmsorgCard>
  );
}
