"use client";

import React from "react";
import { X, Save, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { useSidebarOverlay } from "@/context/SidebarContext";

export interface FooterDataItem {
  label: string;
  value: string | number;
}

export interface FloatingFooterProps {
  data: FooterDataItem[];
  onSave: () => void;
  cancelHref?: string;
  isSaving?: boolean;
  saveLabel?: string;
  savingLabel?: string;
}

/**
 * Sticky save bar for the transaction forms — carries the running totals and
 * the primary action.
 *
 * Changes:
 *   - The Save button had a permanent white shimmer sweeping across it every
 *     2.4s. A looping animation on the primary action reads as "busy" and
 *     competes with the genuine saving state, so it is gone; the button now
 *     animates only in response to input (hover/press) and while saving.
 *   - Save is ordered last in the DOM and first visually on mobile, so the
 *     primary action sits under the thumb rather than above Cancel.
 *   - The totals are a real `<dl>` with visible labels at a readable size —
 *     they were 10px, below the practical floor for financial figures.
 */
export default function FloatingFooter({
  data,
  onSave,
  cancelHref,
  isSaving = false,
  saveLabel = "Save",
  savingLabel = "Saving…",
}: FloatingFooterProps) {
  const router = useRouter();
  const sidebarOverlayActive = useSidebarOverlay();

  const handleCancel = () => (cancelHref ? router.push(cancelHref) : router.back());

  return (
    <div
      className={cn(
        "fixed inset-x-0 bottom-0 border-t border-border bg-card/95 backdrop-blur transition-opacity duration-200",
        "pb-[env(safe-area-inset-bottom)] shadow-[0_-4px_16px_-8px_rgb(16_24_40_/_0.12)]",
        sidebarOverlayActive
          ? "z-30 pointer-events-none opacity-50"
          : "z-40 opacity-100"
      )}
    >
      <div className="mx-auto flex w-full max-w-[1600px] flex-col gap-3 px-4 py-3 sm:px-6 md:flex-row md:items-center md:justify-between">
        {data.length > 0 && (
          <dl className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs md:min-w-[300px] md:flex-1">
            {data.map((item, idx) => {
              const emphasize = item.label.toLowerCase().includes("net");
              return (
                <React.Fragment key={idx}>
                  <dt
                    className={cn(
                      "truncate text-muted-foreground",
                      emphasize && "font-semibold text-foreground"
                    )}
                  >
                    {item.label}
                  </dt>
                  <dd
                    className={cn(
                      "text-right tabular-nums text-foreground",
                      emphasize && "font-bold text-primary"
                    )}
                  >
                    {item.value}
                  </dd>
                </React.Fragment>
              );
            })}
          </dl>
        )}

        {/* flex-col-reverse: Save renders last in the DOM but sits on top on
            phones, i.e. closest to the thumb. */}
        <div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-end md:shrink-0">
          <Button
            type="button"
            variant="outline"
            onClick={handleCancel}
            disabled={isSaving}
            className="w-full sm:w-auto"
          >
            <X className="size-4" aria-hidden />
            Cancel
          </Button>

          <Button
            type="button"
            onClick={onSave}
            disabled={isSaving}
            aria-busy={isSaving}
            className="w-full sm:w-auto sm:min-w-32"
          >
            {isSaving ? (
              <Loader2 className="size-4 animate-spin" aria-hidden />
            ) : (
              <Save className="size-4" aria-hidden />
            )}
            {isSaving ? savingLabel : saveLabel}
          </Button>
        </div>
      </div>
    </div>
  );
}
