"use client";

/** Helpers shared by the payroll tabs (plan L). */

import * as React from "react";

import { toast } from "@/components/ui/toast";

import { apiError } from "../employees/employees-view";

export { apiError };
export { kes } from "@/components/medora/payroll";

const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

/** 2026-11-23 → 23 Nov 2026; 2026-11 → Nov 2026. */
export const human = (iso: string | null | undefined) => (!iso ? "–" : iso.length === 7 ? `${MON[Number(iso.slice(5, 7)) - 1]} ${iso.slice(0, 4)}` : `${Number(iso.slice(8, 10))} ${MON[Number(iso.slice(5, 7)) - 1]} ${iso.slice(0, 4)}`);
/** 2026-11 → November 2026. */
export const longMonth = (m: string) => `${MONTH_NAMES[Number(m.slice(5, 7)) - 1]} ${m.slice(0, 4)}`;
export const addMonths = (m: string, n: number) => {
  const [y, mo] = m.split("-").map(Number);
  const t = y * 12 + (mo - 1) + n;
  return `${Math.floor(t / 12)}-${String((t % 12) + 1).padStart(2, "0")}`;
};

/** Runs an API call with a busy flag, toasting success or the API's reason. */
export function useAction() {
  const [busy, setBusy] = React.useState(false);
  const run = React.useCallback(async <T,>(p: () => Promise<T>, ok: string | ((t: T) => string), fail = "Not saved"): Promise<T | undefined> => {
    setBusy(true);
    try {
      const t = await p();
      toast.add({ title: typeof ok === "function" ? ok(t) : ok });
      return t;
    } catch (e) {
      toast.add({ type: "error", title: fail, description: apiError(e, "Try again.") });
      return undefined;
    } finally {
      setBusy(false);
    }
  }, []);
  return { busy, run };
}

export function Section({ title, description, actions, children }: { title: string; description?: string; actions?: React.ReactNode; children: React.ReactNode }) {
  return (
    <section className="space-y-3">
      <div className="flex flex-wrap items-end justify-between gap-2">
        <div>
          <h2 className="text-sm font-semibold">{title}</h2>
          {description ? <p className="text-xs text-muted-foreground">{description}</p> : null}
        </div>
        {actions}
      </div>
      {children}
    </section>
  );
}
