"use client";

import { useCallback, useState } from "react";
import {
  animate,
  useMotionValue,
  useTransform,
  type PanInfo,
} from "framer-motion";

const SWIPE_THRESHOLD = 52;
const MAX_DRAG = 72;

/** incoming: سوایپ به راست — outgoing: سوایپ به چپ (مثل اینستاگرام در RTL) */
export function useSwipeToReply(
  onReply: () => void,
  enabled = true,
  direction: "left" | "right" = "left"
) {
  const x = useMotionValue(0);
  const [dragging, setDragging] = useState(false);
  const swipeRight = direction === "right";

  const replyOpacity = useTransform(
    x,
    swipeRight ? [10, 40] : [-10, -40],
    [0, 1]
  );
  const replyScale = useTransform(
    x,
    swipeRight ? [10, 40] : [-10, -40],
    [0.6, 1]
  );

  const resetPosition = useCallback(() => {
    void animate(x, 0, {
      type: "spring",
      stiffness: 520,
      damping: 38,
      mass: 0.85,
    });
  }, [x]);

  const onDragStart = useCallback(() => {
    setDragging(true);
  }, []);

  const onDragEnd = useCallback(
    (_: unknown, info: PanInfo) => {
      setDragging(false);
      const triggered = swipeRight
        ? info.offset.x >= SWIPE_THRESHOLD
        : info.offset.x <= -SWIPE_THRESHOLD;
      if (triggered) {
        if (typeof navigator !== "undefined" && navigator.vibrate) {
          navigator.vibrate(12);
        }
        onReply();
      }
      resetPosition();
    },
    [onReply, resetPosition, swipeRight]
  );

  const dragProps = enabled
    ? {
        drag: "x" as const,
        dragConstraints: swipeRight
          ? { left: 0, right: MAX_DRAG }
          : { left: -MAX_DRAG, right: 0 },
        dragElastic: swipeRight
          ? { left: 0, right: 0.15 }
          : { left: 0.15, right: 0 },
        dragMomentum: false,
        dragSnapToOrigin: true,
        style: { x, touchAction: "pan-y" as const },
        onDragStart,
        onDragEnd,
      }
    : {};

  return {
    dragProps,
    dragging,
    replyOpacity,
    replyScale,
    x,
    resetPosition,
  };
}
