import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useDrag } from '@use-gesture/react';

const EDGE_THRESHOLD = 200;
const SNAP_THRESHOLD = 0.4;
const VELOCITY_THRESHOLD = 0.5;

export function useSwipeNavigation({ enabled, canSwipeToChat }) {
  const [activeView, setActiveView] = useState('sidebar');
  const trayRef = useRef(null);

  const activeViewRef = useRef(activeView);
  const canSwipeToChatRef = useRef(canSwipeToChat);
  const screenWidthRef = useRef(window.innerWidth);

  useEffect(() => { activeViewRef.current = activeView; }, [activeView]);
  useEffect(() => { canSwipeToChatRef.current = canSwipeToChat; }, [canSwipeToChat]);

  const [isSwiping, setIsSwiping] = useState(false);

  const goToChat = useCallback(() => {
    const tray = trayRef.current;
    if (tray) {
      tray.style.transition = 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
      tray.style.transform = `translateX(-${screenWidthRef.current}px)`;
    }
    setActiveView('chat');
  }, []);

  const goToSidebar = useCallback(() => {
    const tray = trayRef.current;
    if (tray) {
      tray.style.transition = 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
      tray.style.transform = 'translateX(0px)';
    }
    setActiveView('sidebar');
  }, []);

  // Keep screen width in sync
  useEffect(() => {
    if (!enabled) return;

    const handleResize = () => {
      const tray = trayRef.current;
      const panel = tray?.querySelector('.mobile-swipe-panel');
      screenWidthRef.current = panel?.offsetWidth || window.innerWidth;
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [enabled]);

  // Measure panel width on mount
  useEffect(() => {
    if (!enabled) return;
    const tray = trayRef.current;
    if (!tray) return;
    const panel = tray.querySelector('.mobile-swipe-panel');
    if (panel) {
      screenWidthRef.current = panel.offsetWidth;
    }
  }, [enabled]);

  function getCurrentTranslateX(tray) {
    const style = window.getComputedStyle(tray);
    const matrix = style.transform;
    if (!matrix || matrix === 'none') return 0;
    const match = matrix.match(/matrix\(([^)]+)\)/);
    if (match) {
      const values = match[1].split(',').map(Number);
      return values[4] || 0;
    }
    return 0;
  }

  const bind = useDrag(
    ({ active, movement: [mx], velocity: [vx], direction: [dx], cancel, tap, first, event }) => {
      if (!enabled) return;
      if (tap) return;

      const tray = trayRef.current;
      if (!tray) return;
      const sw = screenWidthRef.current;
      const view = activeViewRef.current;

      if (first) {
        const touchX = event.touches?.[0]?.clientX ?? event.clientX;
        const fromLeftEdge = touchX <= EDGE_THRESHOLD;
        const fromRightEdge = touchX >= sw - EDGE_THRESHOLD;

        if (view === 'chat' && !fromLeftEdge) { cancel(); return; }
        if (view === 'sidebar' && (!fromRightEdge || !canSwipeToChatRef.current)) { cancel(); return; }

        // Freeze current position for mid-animation interruption
        tray.style.transition = 'none';
        const currentX = getCurrentTranslateX(tray);
        tray.style.transform = `translateX(${currentX}px)`;
      }

      if (active) {
        setIsSwiping(true);
        const base = view === 'chat' ? -sw : 0;
        const newOffset = Math.max(-sw, Math.min(0, base + mx));
        tray.style.transition = 'none';
        tray.style.transform = `translateX(${newOffset}px)`;
      } else {
        // Release — decide snap target
        setIsSwiping(false);
        const currentOffset = getCurrentTranslateX(tray);

        let shouldTransition = false;
        if (view === 'chat') {
          const progress = (currentOffset - (-sw)) / sw;
          shouldTransition = progress > SNAP_THRESHOLD || vx > VELOCITY_THRESHOLD;
        } else {
          const progress = Math.abs(currentOffset) / sw;
          shouldTransition = progress > SNAP_THRESHOLD || vx > VELOCITY_THRESHOLD;
        }

        tray.style.transition = 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)';

        if (shouldTransition) {
          if (view === 'chat') {
            tray.style.transform = 'translateX(0px)';
            setActiveView('sidebar');
          } else {
            tray.style.transform = `translateX(-${sw}px)`;
            setActiveView('chat');
          }
        } else {
          // Snap back
          if (view === 'chat') {
            tray.style.transform = `translateX(-${sw}px)`;
          } else {
            tray.style.transform = 'translateX(0px)';
          }
        }
      }
    },
    { axis: 'x', filterTaps: true, pointer: { touch: true } }
  );

  const trayStyle = useMemo(() => {
    if (!enabled) return {};
    return {
      transform: activeView === 'chat' ? `translateX(-${screenWidthRef.current}px)` : 'translateX(0px)',
    };
  }, [enabled, activeView]);

  const swipeBindProps = enabled ? bind() : {};

  return { activeView, goToChat, goToSidebar, trayRef, trayStyle, isSwiping, swipeBindProps };
}
