'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { Check } from 'lucide-react';
import { useEffect, useState } from 'react';

import { Button } from '@/components/ui/button';

/**
 * Floating glass pill at the bottom center while a form is dirty.
 * After a successful save it briefly shows a check before sliding away.
 */
export function StickySaveBar({
  dirty,
  saving,
  onSave,
  onDiscard,
}: {
  dirty: boolean;
  saving?: boolean;
  onSave: () => void;
  onDiscard: () => void;
}) {
  const reduce = useReducedMotion();
  const [state, setState] = useState({ saving: saving === true, justSaved: false });
  if (state.saving !== (saving === true)) {
    // A save just finished and the form is clean again: show the check.
    setState({ saving: saving === true, justSaved: state.saving && saving !== true && !dirty });
  }
  const justSaved = state.justSaved;
  useEffect(() => {
    if (!justSaved) return undefined;
    const timer = window.setTimeout(() => setState((current) => ({ ...current, justSaved: false })), 1400);
    return () => window.clearTimeout(timer);
  }, [justSaved]);

  const visible = dirty || justSaved;
  return (
    <AnimatePresence>
      {visible ? (
        <motion.div
          key="save-bar"
          role="region"
          aria-label="Unsaved changes"
          initial={reduce ? { opacity: 0 } : { opacity: 0, y: 24 }}
          animate={{ opacity: 1, y: 0 }}
          exit={reduce ? { opacity: 0 } : { opacity: 0, y: 24 }}
          transition={{ duration: 0.22, ease: [0.2, 0.8, 0.2, 1] }}
          className="pointer-events-none fixed inset-x-0 bottom-4 z-40 flex justify-center px-4 lg:pl-[264px]"
        >
          <div className="pointer-events-auto flex items-center gap-3 rounded-pill border border-border bg-surface/80 py-2 pl-5 pr-2 shadow-lg backdrop-blur-[12px]">
            {justSaved && !dirty ? (
              <p className="flex items-center gap-2 py-1.5 pr-3 text-small font-semibold text-success" aria-live="polite">
                <span className="grid h-6 w-6 place-items-center rounded-full bg-success text-primary-foreground">
                  <Check className="h-3.5 w-3.5" strokeWidth={3} aria-hidden="true" />
                </span>
                Changes saved
              </p>
            ) : (
              <>
                <p className="hidden text-small font-medium text-foreground sm:block">You have unsaved changes</p>
                <Button type="button" variant="ghost" size="sm" onClick={onDiscard} disabled={saving}>
                  Discard
                </Button>
                <Button type="button" size="sm" onClick={onSave} loading={saving}>
                  Save changes
                </Button>
              </>
            )}
          </div>
        </motion.div>
      ) : null}
    </AnimatePresence>
  );
}
