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

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

const WIDGET_PAGE_SIZE = 200;
const REMINDER_DAYS_AHEAD = 5;

// Nächstes Vorkommen des Geburtstags (dieses Jahr, oder nächstes Jahr falls schon vorbei) - Alter
// spielt für die Erinnerung keine Rolle, nur der Tag/Monat.
function daysUntilNextBirthday(dateOfBirth) {
  const birth = dateOfBirth instanceof Date ? dateOfBirth : new Date(dateOfBirth);
  if (Number.isNaN(birth.getTime())) {
    return null;
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  let next = new Date(today.getFullYear(), birth.getMonth(), birth.getDate());
  next.setHours(0, 0, 0, 0);
  if (next < today) {
    next = new Date(today.getFullYear() + 1, birth.getMonth(), birth.getDate());
  }

  return Math.round((next - today) / (1000 * 60 * 60 * 24));
}

function remainingLabel(days) {
  if (days === 0) {
    return "heute";
  }
  if (days === 1) {
    return "morgen";
  }
  return `in ${days} Tagen`;
}

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

  const [employees, setEmployees] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

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

    let cancelled = false;

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

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

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

  if (!canView) {
    return null;
  }

  const upcoming = employees
    .filter((employee) => employee.dateOfBirth)
    .map((employee) => ({ employee, days: daysUntilNextBirthday(employee.dateOfBirth) }))
    .filter(({ days }) => days !== null && days >= 0 && days <= REMINDER_DAYS_AHEAD)
    .sort((a, b) => a.days - b.days);

  return (
    <OmsorgCard title="Anstehende Geburtstage">
      <div className="contract-widget">
        <div className="contract-widget__intro">
          <Cake size={20} />

          <p>Mitarbeiter, die in den nächsten {REMINDER_DAYS_AHEAD} Tagen Geburtstag haben.</p>
        </div>

        {!isLoading && upcoming.length === 0 && <p>Keine anstehenden Geburtstage.</p>}

        <div className="contract-widget__list">
          {upcoming.map(({ employee, days }) => (
            <article key={employee.id} className={`contract-item contract-item--${days === 0 ? "danger" : "info"}`}>
              <div className="contract-item__header">
                <div>
                  <strong>
                    {employee.firstName} {employee.lastName}
                  </strong>
                </div>

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